All checks were successful
CI/CD Pipeline / build-and-deploy (push) Successful in 16s
- player status: initial bulk refresh retries 4x5s (bot and stats service start in the
same second on prod, the first attempt failed with connection reset); admin is
notified after 3 consecutive failed refreshes
- /today, /yesterday, /week: players whose bulk status shows they were not online since
the period start (or whose account is closed) are skipped without any Lichess call;
stats service paces user/activity at 8.5s (Lichess allows 15 per 2 min per IP), so a
user with 16+ tracked players no longer hits 429 mid-command
- unknown /commands in private chats get the usual hint and a cmd name=unknown event
- /addtoken -> /cancel used to crash (sync lambda awaited by PTB 20); now an async handler
- version 1.5.0, CHANGELOG entry for everything since 1.1.0 that shipped today
- docs: CURRENT_STATE.md rewritten for 30aaa34, README brought in line with the code
(port 8002, module list, commands, .env vars, DB tables, events.log section)
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
145 lines
7.2 KiB
Python
145 lines
7.2 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
|
|
|
|
import config
|
|
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')
|
|
|
|
async def notify_status_refresh_failing(self, consecutive: int, last_error: str):
|
|
"""Notify admin that the bulk player status refresh (player_status.py) keeps failing."""
|
|
minutes = consecutive * config.PLAYER_STATUS_REFRESH_MINUTES
|
|
message = (
|
|
f"⚠️ <b>Обновление статуса игроков не работает</b>\n\n"
|
|
f"Подряд идущих ошибок: {consecutive} (~{minutes} мин без статуса)\n"
|
|
f"Последняя ошибка: {last_error[:200]}\n\n"
|
|
f"Периодические проверки идут без пропусков по bulk-статусу (запрос на каждое окно). "
|
|
f"Проверьте stats-сервис (POST /users/status) и доступность Lichess API."
|
|
)
|
|
await self._send(message, kind='status_refresh_failing')
|