Files
infra/stacks/astra-bot/restart-check.py
T

35 lines
1.8 KiB
Python

#!/usr/bin/env python3
"""One-shot restart and readiness notification; run with EnvironmentFile, never print tokens."""
import json
import os
import subprocess
import time
import urllib.request
started = str(int(time.time()))
try:
subprocess.run(['systemctl', 'restart', 'astra-bot.service'], check=True, timeout=30)
ready = False
for _ in range(20):
active = subprocess.run(['systemctl', 'is-active', '--quiet', 'astra-bot.service']).returncode == 0
journal = subprocess.run(['journalctl', '-u', 'astra-bot.service', '--since', '@' + started,
'--no-pager', '-o', 'cat'], capture_output=True, text=True, timeout=5).stdout
if active and 'astra-bot запущен' in journal:
ready = True
break
time.sleep(1)
text = ('Бот перезапущен и готов. Теперь принимает картинки, подписи и пересланный текст. '
'Пришли картинку с подписью ещё раз для проверки.' if ready else
'После перезапуска бот пока не подтвердил готовность. Нужна проверка astra-bot.service.')
except Exception:
text = 'Перезапуск бота не прошёл. Нужна проверка astra-bot.service.'
try:
payload = json.dumps({'chat_id': 607015, 'text': text}).encode()
request = urllib.request.Request('https://api.telegram.org/bot' + os.environ['TG_TOKEN'] + '/sendMessage',
payload, {'Content-Type': 'application/json'})
with urllib.request.urlopen(request, timeout=15) as response:
result = json.load(response)
print('Telegram readiness notification:', bool(result.get('ok')))
except Exception:
print('Telegram readiness notification failed')