- events.py (bot): one grep-able line per event into data/events.log (10 MB x 5 rotation,
survives container recreation): user_start, cmd, text/callback/non_text, addgamer_input/
addgamer_result, addtoken_result, gamer_added, gamer_deleted, period_set, lang_set,
check (decision=request|skip_unchanged|skip_closed, games, notified, lag), check_error,
closed_notice, reopened_notice, blocked, token_rejected, status_refresh, admin_notify,
tg_error; a SUMMARY line at midnight, also shown by admin /status as "Вчера".
Service side: EVT lichess_429 (kind=concurrency|burst|unknown) and lichess_error in its log.
- /games/{username}/period?by_finish=true: query Lichess from since-3h and keep games with
since < lastMoveAt <= until. Periodic checks use it, so a game created 14:58 and finished
15:06 is reported in the 15:00-16:00 window instead of being lost on the boundary.
- reopened-account notice is sent as soon as the status flips, not after the next game.
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
132 lines
6.3 KiB
Python
132 lines
6.3 KiB
Python
"""
|
|
Admin notifications shared by the bot and the admin-panel processes.
|
|
|
|
Both processes post straight to the Telegram Bot API with the admin-panel bot
|
|
token (aiohttp), so the bot process needs no running admin Application to reach
|
|
the admin chat and the admin process needs no second code path. The admin chat
|
|
id comes from the database (/start in the admin bot stores it).
|
|
"""
|
|
import logging
|
|
import urllib.parse
|
|
from typing import Optional
|
|
|
|
import aiohttp
|
|
|
|
from config import ADMINPANEL_TELEGRAM_BOT_TOKEN, TTS_URL
|
|
from database import Database
|
|
from events import event
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
|
|
class AdminNotifier:
|
|
def __init__(self, db: Database):
|
|
self.db = db
|
|
|
|
async def _send(self, text_html: str, kind: str = 'other') -> bool:
|
|
"""
|
|
Post one HTML message to the admin chat via the Telegram Bot API. Never
|
|
raises; returns True when Telegram accepted it. `kind` only labels the
|
|
`admin_notify` event line.
|
|
"""
|
|
ok = False
|
|
try:
|
|
admin_chat_id = self.db.get_admin_chat_id()
|
|
if not admin_chat_id:
|
|
logger.warning("Admin chat id is not set; cannot send admin notification.")
|
|
event('admin_notify', kind=kind, ok=False)
|
|
return False
|
|
url = f"https://api.telegram.org/bot{ADMINPANEL_TELEGRAM_BOT_TOKEN}/sendMessage"
|
|
logger.info(f"Sending admin notification via direct API to chat_id={admin_chat_id}")
|
|
async with aiohttp.ClientSession() as session:
|
|
async with session.post(url, json={
|
|
"chat_id": admin_chat_id,
|
|
"text": text_html,
|
|
"parse_mode": "HTML"
|
|
}, timeout=aiohttp.ClientTimeout(total=10)) as response:
|
|
if response.status == 200:
|
|
logger.info("Admin notification sent successfully via direct API")
|
|
ok = True
|
|
else:
|
|
error_text = await response.text()
|
|
logger.error(f"Failed to send admin notification: {response.status} - {error_text}")
|
|
except Exception as e:
|
|
logger.error(f"Failed to send admin notification via API: {e}")
|
|
event('admin_notify', kind=kind, ok=ok)
|
|
return ok
|
|
|
|
async def _call_tts_service(self, text: str):
|
|
"""Call the optional TTS announcer (config.TTS_URL); no-op when it is not configured."""
|
|
if not TTS_URL:
|
|
logger.debug(f"TTS_URL not set, skipping TTS announcement: {text}")
|
|
return
|
|
try:
|
|
encoded_text = urllib.parse.quote(text)
|
|
tts_url = f"{TTS_URL.rstrip('/')}/TTS?text={encoded_text}"
|
|
async with aiohttp.ClientSession() as session:
|
|
async with session.get(tts_url, timeout=aiohttp.ClientTimeout(total=5)) as response:
|
|
if response.status == 200:
|
|
logger.info(f"TTS service called successfully: {text}")
|
|
else:
|
|
logger.warning(f"TTS service returned status {response.status}")
|
|
except Exception as e:
|
|
logger.error(f"Failed to call TTS service: {e}")
|
|
|
|
async def notify_new_user(self, user_id: int, username: Optional[str], first_name: Optional[str]):
|
|
"""Send notification about new Telegram user"""
|
|
username_text = f"@{username}" if username else "без username"
|
|
name_text = first_name if first_name else "без имени"
|
|
|
|
message = (
|
|
f"🆕 <b>Новый пользователь Telegram</b>\n\n"
|
|
f"ID: {user_id}\n"
|
|
f"Username: {username_text}\n"
|
|
f"Имя: {name_text}"
|
|
)
|
|
await self._send(message, kind='new_user')
|
|
|
|
# Call TTS service with user count
|
|
try:
|
|
total_users = self.db.get_counts()['users']
|
|
await self._call_tts_service(f"Появился новый пользователь {total_users}")
|
|
except Exception as e:
|
|
logger.error(f"Failed to call TTS for new user: {e}")
|
|
|
|
async def notify_new_player(self, player_username: str, added_by_user_id: int, added_by_username: Optional[str], is_new_gamer: bool = False):
|
|
"""Send notification about new tracked player"""
|
|
added_by_text = f"@{added_by_username}" if added_by_username else f"ID: {added_by_user_id}"
|
|
lichess_url = f"https://lichess.org/@/{player_username}"
|
|
|
|
message = (
|
|
f"🎮 <b>Добавлен новый игрок для отслеживания</b>\n\n"
|
|
f"Игрок: <a href=\"{lichess_url}\">{player_username}</a>\n"
|
|
f"Добавил: {added_by_text}"
|
|
)
|
|
await self._send(message, kind='new_player')
|
|
|
|
# Call TTS service if this is a new gamer
|
|
if is_new_gamer:
|
|
try:
|
|
total_gamers = self.db.get_counts()['gamers']
|
|
await self._call_tts_service(f"Добавлен новый игрок {total_gamers}")
|
|
except Exception as e:
|
|
logger.error(f"Failed to call TTS for new gamer: {e}")
|
|
|
|
@staticmethod
|
|
def _estimate_backoff_elapsed_hours(consecutive_errors: int) -> float:
|
|
"""Оценивает, сколько времени прошло при данном числе подряд идущих ошибок,
|
|
исходя из формулы бэкоффа periodic_check: min(300, 60 * n) секунд на попытку."""
|
|
total_seconds = sum(min(300, 60 * i) for i in range(1, consecutive_errors + 1))
|
|
return total_seconds / 3600
|
|
|
|
async def notify_periodic_check_failing(self, gamer_username: str, user_id: int, consecutive_errors: int):
|
|
"""Notify admin that periodic check for a gamer has been failing for a long time."""
|
|
hours = self._estimate_backoff_elapsed_hours(consecutive_errors)
|
|
message = (
|
|
f"⚠️ <b>Мониторинг игрока не работает</b>\n\n"
|
|
f"Игрок: {gamer_username}\n"
|
|
f"Владелец: user_id={user_id}\n"
|
|
f"Подряд идущих ошибок: {consecutive_errors} (~{hours:.1f} ч)\n\n"
|
|
f"Проверьте токен игрока или доступность Lichess API."
|
|
)
|
|
await self._send(message, kind='check_failing')
|