LichessStatTgWeb/LichessClientTG_bot/notifications.py
vrubelroman 7178b80854 split bot.py into periodic/notifications/onboarding modules, drop redundant request queue
Behaviour-preserving refactor:
- periodic.py: PeriodicMonitor (periodic_check & friends, moved verbatim with comments)
- notifications.py: one AdminNotifier for both processes (was 4 copies of the same
  direct-API code), with a 10 s HTTP timeout and the TTS announcer
- onboarding.py: link_player(), the add-player flow shared by /addgamer and /addtoken
- bot.py 2040 -> 1372 lines; no inline sqlite3 left (Database.gamer_exists/get_counts)
- request_queue.py removed: periodic checks call the local stats service under a
  10-slot semaphore; the only real Lichess limiter is SharedTokenGate in the service.
  Bot-side RateLimiter kept only for direct lichess.org calls.
- /addtoken "already tracked" check is now case-insensitive like /addgamer
- docs/CURRENT_STATE.md: system map as of 6355cd9 (analyst)
- .claude/agents: analyst / developer / tester definitions

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-20 21:46:48 +00:00

122 lines
5.8 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
logger = logging.getLogger(__name__)
class AdminNotifier:
def __init__(self, db: Database):
self.db = db
async def _send(self, text_html: str) -> None:
"""Post one HTML message to the admin chat via the Telegram Bot API. Never raises."""
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.")
return
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")
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}")
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)
# 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)
# 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)