From 27e76b23992bf4a259a672d6c3dafec4029db318 Mon Sep 17 00:00:00 2001 From: vrubelroman Date: Tue, 20 Oct 2026 22:31:33 +0000 Subject: [PATCH] bulk player status: skip periodic checks for players who did not play, pause closed accounts MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - stats service: POST /users/status proxies Lichess POST /api/users (up to 300 names, through the shared-token gate) -> disabled / seen_at / games_total (sum of perfs.*.games) - bot: PlayerStatusRefresher refreshes all tracked players every 15 min (2 bulk calls for ~500 players) into the new gamer_status table - periodic_check: before the games request, _decide_skip() compares the player's games_total with the pair's stored baseline (user_gamers.last_games_total); unchanged and no token -> no HTTP call, checkpoint advances only to what the status proves (status.checked_at - 60s), so games finished between a refresh and the window end are still reported next time. Closed account -> skip + one notice to the owner, auto-resume when reopened. - /getgamers and /delgamer mark closed accounts with ⛔ Background load drops from ~445 games/user calls per hour to ~8 bulk calls plus one games call per player who actually played. Co-Authored-By: Claude Fable 5.1 --- LichessClientTG_bot/bot.py | 11 +- LichessClientTG_bot/config.py | 13 ++ LichessClientTG_bot/database.py | 130 ++++++++++++++++++++ LichessClientTG_bot/i18n.py | 4 + LichessClientTG_bot/lichess_api.py | 28 +++++ LichessClientTG_bot/periodic.py | 171 +++++++++++++++++++++++++++ LichessClientTG_bot/player_status.py | 97 +++++++++++++++ LichessWebServices/lichess_client.py | 71 +++++++++++ LichessWebServices/main.py | 58 ++++++++- LichessWebServices/models.py | 32 +++++ LichessWebServices/stats_service.py | 45 ++++++- README.md | 3 +- 12 files changed, 656 insertions(+), 7 deletions(-) create mode 100644 LichessClientTG_bot/player_status.py diff --git a/LichessClientTG_bot/bot.py b/LichessClientTG_bot/bot.py index 908e33d..28cc24f 100644 --- a/LichessClientTG_bot/bot.py +++ b/LichessClientTG_bot/bot.py @@ -62,6 +62,11 @@ class LichessBot: logger.error(f"test_admin_notify failed: {e}") await update.message.reply_text(f"❌ Failed to trigger admin notification: {e}") + def _closed_prefix(self, gamer_id: int) -> str: + """'⛔' for a player whose Lichess account the last bulk status refresh saw as closed, else ''.""" + status = self.db.get_gamer_status(gamer_id) + return "⛔" if status and status.get('disabled') else "" + def get_user_language_from_update(self, update: Update) -> str: """Get user's selected bot language from database""" user = update.effective_user @@ -499,7 +504,7 @@ class LichessBot: gamers_data.append({ 'id': gamer['id'], - 'username': username, + 'username': self._closed_prefix(gamer['id']) + username, 'bullet': bullet_rating, 'blitz': blitz_rating, 'rapid': rapid_rating, @@ -516,7 +521,7 @@ class LichessBot: period_text = f" · {period_minutes}{period_suffix}" if period_minutes > 0 else "" gamers_data.append({ 'id': gamer['id'], - 'username': gamer['username'], + 'username': self._closed_prefix(gamer['id']) + gamer['username'], 'bullet': 'N/A', 'blitz': 'N/A', 'rapid': 'N/A', @@ -636,7 +641,7 @@ class LichessBot: period_text = f" · {period_minutes}{period_suffix}" if period_minutes > 0 else "" text_lines.append( - f"{status} {username} " + f"{status} {self._closed_prefix(gamer['id'])}{username} " f"⚡ {bullet_rating} 🔥 {blitz_rating} 🐇 {rapid_rating}{period_text}" ) diff --git a/LichessClientTG_bot/config.py b/LichessClientTG_bot/config.py index abaf151..b36475e 100644 --- a/LichessClientTG_bot/config.py +++ b/LichessClientTG_bot/config.py @@ -34,6 +34,19 @@ LICHESS_STATS_API_BASE_URL = "http://localhost:8002" # Host port for stats API # вызовов lichess.org (check_user_exists, get_user_ratings, get_user_profile). PERIODIC_MAX_CONCURRENT_REQUESTS = 10 +# Bulk-статус игроков (player_status.py): раз в столько минут бот одним POST +# /api/users (через stats-сервис, до 300 имён за запрос) получает по всем +# отслеживаемым игрокам флаг disabled и число сыгранных партий. periodic_check +# перед запросом games/user сравнивает это число с сохранённым у пары +# (user_gamers.last_games_total): если оно не изменилось — игрок ничего не +# доиграл, запрос за это окно пропускается, чекпоинт двигается; если аккаунт +# закрыт — проверка тоже пропускается, владельцу один раз уходит уведомление. +# Цена: 500 игроков = 2 bulk-запроса на обновление (8 в час при 15 мин) вместо +# ~450 индивидуальных games/user в час, из которых ~95 % находят 0 партий. +# Статус старше 3 × этого интервала считается устаревшим — тогда проверка идёт +# как раньше (запрос всегда), так что сбой обновления ничего не ломает. +PLAYER_STATUS_REFRESH_MINUTES = 15 + # Джиттер чекпоинтов периодических проверок: не даёт парам (user, gamer) с одинаковым # period_minutes синхронизироваться на один и тот же wall-clock момент при рестарте бота # (см. periodic_check в bot.py). Потолок держим далеко ниже STALE_BACKLOG_THRESHOLD (2ч), diff --git a/LichessClientTG_bot/database.py b/LichessClientTG_bot/database.py index 0255958..9b90dcf 100644 --- a/LichessClientTG_bot/database.py +++ b/LichessClientTG_bot/database.py @@ -85,6 +85,38 @@ class Database: except sqlite3.OperationalError: # Column already exists pass + + # Bulk player status (see player_status.py): games_total of the player as + # of the pair's last successful games request. If the refreshed total is + # the same, no game was finished since, and the periodic games request for + # that window is skipped. + try: + cursor.execute("ALTER TABLE user_gamers ADD COLUMN last_games_total INTEGER") + except sqlite3.OperationalError: + # Column already exists + pass + + # Whether the owner was already told that this player's Lichess account is + # closed (sent once; cleared when the account is seen active again). + try: + cursor.execute("ALTER TABLE user_gamers ADD COLUMN closed_notice_sent INTEGER NOT NULL DEFAULT 0") + except sqlite3.OperationalError: + # Column already exists + pass + + # Latest bulk status of each tracked player from POST /api/users + # (player_status.py refreshes it every PLAYER_STATUS_REFRESH_MINUTES). + # One row per gamer, not per pair: the status is a property of the + # Lichess account, shared by everyone who tracks it. + cursor.execute(''' + CREATE TABLE IF NOT EXISTS gamer_status ( + gamer_id INTEGER PRIMARY KEY REFERENCES gamers(id), + disabled INTEGER NOT NULL DEFAULT 0, + seen_at INTEGER, + games_total INTEGER, + checked_at INTEGER NOT NULL + ) + ''') # Create admin_settings table for admin bot configuration cursor.execute(''' @@ -480,7 +512,9 @@ class Database: other_users_count = cursor.fetchone()[0] # If no other users track this gamer, remove from gamers table + # (and its bulk-status row, which references it) if other_users_count == 0: + cursor.execute("DELETE FROM gamer_status WHERE gamer_id = ?", (gamer_id,)) cursor.execute("DELETE FROM gamers WHERE id = ?", (gamer_id,)) conn.commit() @@ -531,6 +565,102 @@ class Database: return gamers + # ------------------------------------------------------------------ + # Bulk player status (gamer_status) and per-pair skip state + # ------------------------------------------------------------------ + + def get_all_tracked_gamers(self) -> List[Dict[str, Any]]: + """Distinct gamers that at least one user tracks with a period set (the set the bulk status refresh asks Lichess about).""" + with sqlite3.connect(self.db_path) as conn: + cursor = conn.cursor() + cursor.execute(''' + SELECT DISTINCT g.id, g.username + FROM gamers g + JOIN user_gamers ug ON ug.gamer_id = g.id + WHERE ug.period_minutes > 0 + ORDER BY g.id + ''') + return [{'id': row[0], 'username': row[1]} for row in cursor.fetchall()] + + def upsert_gamer_statuses(self, rows: List[Dict[str, Any]]): + """ + Insert or replace gamer_status rows. Each row: {'gamer_id', 'disabled', + 'seen_at', 'games_total', 'checked_at'} (seen_at / games_total may be None). + """ + if not rows: + return + with sqlite3.connect(self.db_path) as conn: + cursor = conn.cursor() + cursor.executemany( + "INSERT OR REPLACE INTO gamer_status (gamer_id, disabled, seen_at, games_total, checked_at) " + "VALUES (?, ?, ?, ?, ?)", + [ + ( + int(r['gamer_id']), + 1 if r.get('disabled') else 0, + r.get('seen_at'), + r.get('games_total'), + int(r['checked_at']), + ) + for r in rows + ] + ) + conn.commit() + + def get_gamer_status(self, gamer_id: int) -> Optional[Dict[str, Any]]: + """Latest bulk status of a gamer, or None if it was never refreshed.""" + with sqlite3.connect(self.db_path) as conn: + cursor = conn.cursor() + cursor.execute( + "SELECT disabled, seen_at, games_total, checked_at FROM gamer_status WHERE gamer_id = ?", + (gamer_id,) + ) + row = cursor.fetchone() + if not row: + return None + return { + 'disabled': bool(row[0]), + 'seen_at': row[1], + 'games_total': row[2], + 'checked_at': int(row[3]), + } + + def get_pair_check_state(self, user_id: int, gamer_id: int) -> Dict[str, Any]: + """Per-pair skip state: games_total baseline from the last games request and whether the closed-account notice went out.""" + with sqlite3.connect(self.db_path) as conn: + cursor = conn.cursor() + cursor.execute( + "SELECT last_games_total, closed_notice_sent FROM user_gamers WHERE user_id = ? AND gamer_id = ?", + (user_id, gamer_id) + ) + row = cursor.fetchone() + if not row: + return {'last_games_total': None, 'closed_notice_sent': False} + return { + 'last_games_total': int(row[0]) if row[0] is not None else None, + 'closed_notice_sent': bool(row[1]), + } + + def set_pair_last_games_total(self, user_id: int, gamer_id: int, games_total: Optional[int]): + """Remember the player's games_total as of this pair's last successful games request.""" + with sqlite3.connect(self.db_path) as conn: + cursor = conn.cursor() + cursor.execute( + "UPDATE user_gamers SET last_games_total = ? WHERE user_id = ? AND gamer_id = ?", + (games_total, user_id, gamer_id) + ) + conn.commit() + + def set_pair_closed_notice_sent(self, user_id: int, gamer_id: int, flag: bool): + """Mark whether the owner has been told that this player's account is closed.""" + with sqlite3.connect(self.db_path) as conn: + cursor = conn.cursor() + cursor.execute( + "UPDATE user_gamers SET closed_notice_sent = ? WHERE user_id = ? AND gamer_id = ?", + (1 if flag else 0, user_id, gamer_id) + ) + conn.commit() + def get_admin_chat_id(self) -> Optional[int]: """Get admin chat ID from database""" with sqlite3.connect(self.db_path) as conn: diff --git a/LichessClientTG_bot/i18n.py b/LichessClientTG_bot/i18n.py index 9a9e695..684ff7f 100644 --- a/LichessClientTG_bot/i18n.py +++ b/LichessClientTG_bot/i18n.py @@ -73,6 +73,8 @@ TRANSLATIONS = { 'lichess_temporarily_unavailable': "⚠️ Lichess is temporarily unavailable. Please try again in a minute.", 'gamer_already_added': "ℹ️ Player {username} is already being tracked.\n\nTo add another player, use /addgamer", 'token_rejected_notice': "⚠️ Lichess rejected the saved token for {username} — puzzle stats have been turned off for this player, game tracking continues as normal. Use /addtoken to reconnect a fresh token if you want puzzle stats back.", + 'gamer_account_closed': "⛔ Lichess account {username} is closed. Notifications for it are paused; if it is reopened, they will resume automatically.", + 'gamer_account_reopened': "✅ Lichess account {username} is active again, notifications resumed.", # Get gamers 'no_gamers': "📭 No players in database. Use /addgamer to add.", @@ -225,6 +227,8 @@ TRANSLATIONS = { 'lichess_temporarily_unavailable': "⚠️ Lichess временно недоступен. Попробуйте, пожалуйста, через минуту.", 'gamer_already_added': "ℹ️ Игрок {username} уже отслеживается.\n\nДля добавления следующего игрока воспользуйтесь /addgamer", 'token_rejected_notice': "⚠️ Lichess отклонил сохранённый токен для {username} — статистика по пазлам для этого игрока отключена, отслеживание партий продолжается как обычно. Используйте /addtoken, чтобы подключить новый токен и вернуть статистику по пазлам.", + 'gamer_account_closed': "⛔ Аккаунт {username} на Lichess закрыт. Уведомления по нему приостановлены; если его откроют, они возобновятся автоматически.", + 'gamer_account_reopened': "✅ Аккаунт {username} на Lichess снова активен, уведомления возобновлены.", # Get gamers 'no_gamers': "📭 Нет игроков в базе данных. Используйте /addgamer для добавления.", diff --git a/LichessClientTG_bot/lichess_api.py b/LichessClientTG_bot/lichess_api.py index 3d69ae3..cf8e0d9 100644 --- a/LichessClientTG_bot/lichess_api.py +++ b/LichessClientTG_bot/lichess_api.py @@ -170,6 +170,34 @@ class LichessAPI: logger.error(f"Error getting puzzles period: {e}") return None + async def get_users_status(self, usernames) -> Optional[list]: + """ + Bulk status of up to 300 players from our stats API (POST /users/status, + one Lichess request behind it). Returns the list of + {'username', 'id', 'disabled', 'seen_at', 'games_total'} dicts for the + names Lichess knows (unknown names are simply absent), or None on any + failure. Local-service call: not paced by the bot-side rate limiter. + """ + usernames = list(usernames) + if not usernames: + return [] + try: + async with aiohttp.ClientSession() as session: + async with session.post( + f"{self.stats_base_url}/users/status", + json={"usernames": usernames} + ) as response: + if response.status == 200: + result = await response.json() + return result.get('players') or [] + else: + error_text = await response.text() + logger.error(f"Failed to get users status: {response.status} - {error_text[:200]}") + return None + except Exception as e: + logger.error(f"Error getting users status: {e}") + return None + async def check_user_exists(self, username: str) -> Optional[Dict[str, Any]]: """ Check if user exists on Lichess. diff --git a/LichessClientTG_bot/periodic.py b/LichessClientTG_bot/periodic.py index 28fb07b..88ef2b4 100644 --- a/LichessClientTG_bot/periodic.py +++ b/LichessClientTG_bot/periodic.py @@ -8,9 +8,16 @@ that service's SharedTokenGate (LichessWebServices/rate_limiter.py); the only bot-side cap is `_request_slots` (config.PERIODIC_MAX_CONCURRENT_REQUESTS), which bounds how many periodic HTTP requests are open at once so hundreds of pairs don't each hold an idle connection while queued in the service. + +Skipping: before each games request the pair consults the player's bulk status +(gamer_status, refreshed by player_status.py). If the player's total games count +has not changed since the pair's last request, nothing was played and the +window is skipped without any HTTP call; a closed account pauses the pair. See +_decide_skip / _skip_window_end for the exact rules and their safety argument. """ import asyncio import logging +import time import zlib from datetime import datetime, timedelta from typing import Dict, Any @@ -24,6 +31,7 @@ from formatters import StatsFormatter from i18n import t from message_counters import MessageCounters from notifications import AdminNotifier +from player_status import PlayerStatusRefresher logger = logging.getLogger(__name__) @@ -40,6 +48,10 @@ class PeriodicMonitor: # At most this many periodic games/puzzles requests in flight to the local # stats service at once (see module docstring). self._request_slots = asyncio.Semaphore(config.PERIODIC_MAX_CONCURRENT_REQUESTS) + # Bulk player status refresh (player_status.py); run once before the periodic + # tasks start and then forever alongside them. None disables it (tests). + self.status_refresher = PlayerStatusRefresher(db, lichess_api) + self._status_refresh_task = None async def start_periodic_task(self, gamer: Dict[str, Any], user_id: int, period_minutes: int): """Start periodic task for a gamer""" @@ -106,6 +118,68 @@ class PeriodicMonitor: digest = zlib.crc32(f"{user_id}:{gamer_id}".encode()) return digest % jitter_cap + # A bulk status older than this is ignored (the refresh loop is probably + # down); the check then runs exactly as it did before status existed. + STATUS_MAX_AGE_SECONDS = 3 * config.PLAYER_STATUS_REFRESH_MINUTES * 60 + + # Safety margin subtracted from a status's checked_at when it is used as a + # window end: checked_at is taken after the bulk answer arrived, while the + # counts are as of the moment Lichess read them (a round trip earlier), plus + # clock skew between this host and Lichess. 60 s costs nothing. + STATUS_SAFETY_MARGIN_SECONDS = 60 + + @classmethod + def _decide_skip(cls, status, pair_state, now_ts: float, has_token: bool, since_ts: float = None) -> str: + """ + Decide what to do with the window [since_ts, ...] of a pair, given the + player's latest bulk status (db.get_gamer_status) and the pair's skip state + (db.get_pair_check_state). Returns 'request', 'skip_unchanged' or + 'skip_closed'. Pure function, so it is unit-testable. + + Why an unchanged total is proof of "no games": perfs.*.games counts every + finished game, rated or casual, and never decreases — a rated game cannot + leave it unchanged (a casual one only inflates it, which errs towards + requesting). What the proof covers is the interval between the baseline's + refresh (<= the checkpoint, see the store rule in periodic_check) and the + current status's refresh — NOT the whole window, which is why + _skip_window_end caps the checkpoint advance at that refresh moment, and + why a status that does not reach past since_ts cannot justify a skip. + """ + if not status: + return 'request' + checked_at = status.get('checked_at') + if checked_at is None or now_ts - checked_at > cls.STATUS_MAX_AGE_SECONDS: + return 'request' # stale: fall back to today's behaviour + if since_ts is not None and checked_at - cls.STATUS_SAFETY_MARGIN_SECONDS <= since_ts: + return 'request' # status predates the window: proves nothing about it + if status.get('disabled'): + return 'skip_closed' + if has_token: + # Puzzle activity is not visible in perfs.*.games; a token pair must + # still request every window to notice puzzles. + return 'request' + last_total = pair_state.get('last_games_total') if pair_state else None + if last_total is None or status.get('games_total') is None: + return 'request' # first time: learn the baseline + if status['games_total'] == last_total: + return 'skip_unchanged' + return 'request' + + @classmethod + def _skip_window_end(cls, period_end_approx: datetime, status: Dict[str, Any]) -> datetime: + """ + Where the checkpoint may advance to when a window is skipped on the + strength of `status`: the planned window end, but never past the moment + the status was refreshed (minus the safety margin). A game finished after + that refresh is not in the status's total yet; if the checkpoint jumped + past it, the next (requested) window would start after the game and it + would never be reported. Capping here keeps the loss profile identical to + a real request: only a game still in progress at the moment the window is + closed can be missed, exactly as today. + """ + covered_until = datetime.fromtimestamp(status['checked_at'] - cls.STATUS_SAFETY_MARGIN_SECONDS) + return min(period_end_approx, covered_until) + async def periodic_check(self, gamer: Dict[str, Any], user_id: int, period_minutes: int): """Periodic check for gamer activity""" task_key = f"{gamer['id']}_{user_id}" @@ -218,6 +292,81 @@ class PeriodicMonitor: f"no notification will be sent for this stale backlog" ) + # Bulk-status shortcut (see module docstring, _decide_skip, player_status.py): + # most windows on prod find 0 games, and an unchanged games total + # proves that without a games request. + status = self.db.get_gamer_status(gamer['id']) + pair_state = self.db.get_pair_check_state(user_id, gamer['id']) + decision = self._decide_skip( + status, pair_state, time.time(), has_token=bool(gamer.get('token')), + since_ts=since_time.timestamp() + ) + # Baseline candidate for this iteration, snapshotted NOW (before the + # games request) and stored only together with the checkpoint below. + # It is only valid if the status was refreshed no later than the + # checkpoint it will be stored with: a status refreshed after + # period_end_approx already counts games of the NEXT window, and an + # equal total at the next check would hide them. In that case the + # previous baseline is kept (it stays valid: checkpoints only grow). + games_total_snapshot = None + if status and status.get('games_total') is not None \ + and status['checked_at'] <= period_end_approx.timestamp(): + games_total_snapshot = status['games_total'] + + if decision in ('skip_unchanged', 'skip_closed'): + skip_end = self._skip_window_end(period_end_approx, status) + # Advance the checkpoint like a zero-activity check does (see the + # comment block at the end of the loop), but only as far as the + # status covers (_skip_window_end). Not counted as a notification. + self.period_start_times[task_key] = skip_end + self.db.set_period_checkpoint(user_id, gamer['id'], int(skip_end.timestamp())) + consecutive_errors = 0 + if decision == 'skip_unchanged': + logger.info(f"⏭️ Skipped check for {username} (user {user_id}): no new games since last check (total={status['games_total']})") + continue + logger.info(f"⛔ {username} is a closed Lichess account; check skipped for user {user_id}") + if not pair_state['closed_notice_sent']: + try: + user_lang = self.db.get_user_language(user_id) + await self.application.bot.send_message( + chat_id=user_id, + text=t('gamer_account_closed', user_lang, username=username) + ) + except Forbidden: + # Same handling as the notification path below: permanent, stop the pair. + logger.warning(f"🚫 User {user_id} blocked the bot; stopping periodic monitoring for {username}") + self.db.set_user_gamer_period(user_id, gamer['id'], 0) + self.periodic_tasks.pop(task_key, None) + self.period_start_times.pop(task_key, None) + return + except Exception as notify_err: + # Not marked as sent: try again at the next skipped check. + logger.error(f"Failed to notify user {user_id} that {username} is closed: {notify_err}") + else: + self.db.set_pair_closed_notice_sent(user_id, gamer['id'], True) + continue + + # 'request' path. An account that was reported closed and now shows + # as active again: tell the owner once and clear the flag. + if pair_state['closed_notice_sent'] and status and not status.get('disabled'): + try: + user_lang = self.db.get_user_language(user_id) + await self.application.bot.send_message( + chat_id=user_id, + text=t('gamer_account_reopened', user_lang, username=username) + ) + except Forbidden: + logger.warning(f"🚫 User {user_id} blocked the bot; stopping periodic monitoring for {username}") + self.db.set_user_gamer_period(user_id, gamer['id'], 0) + self.periodic_tasks.pop(task_key, None) + self.period_start_times.pop(task_key, None) + return + except Exception as notify_err: + logger.error(f"Failed to notify user {user_id} that {username} is active again: {notify_err}") + else: + logger.info(f"✅ {username} is active again on Lichess; notifications resumed for user {user_id}") + self.db.set_pair_closed_notice_sent(user_id, gamer['id'], False) + since_timestamp = int(since_time.timestamp() * 1000) # Используем приблизительное время как until_timestamp # После получения ответа пересчитаем фактическое время @@ -410,6 +559,15 @@ class PeriodicMonitor: # period_end_approx уже установлено в начале итерации self.period_start_times[task_key] = period_end_approx self.db.set_period_checkpoint(user_id, gamer['id'], int(period_end_approx.timestamp())) + # Baseline for the skip decision (see _decide_skip): the player's games + # total as snapshotted at decision time, i.e. BEFORE this request — a game + # finished in between shows up as a higher total at the next refresh and + # triggers a request. Stored here, together with the checkpoint, and not + # right after the games request: if the notification send had failed, + # this window is retried, and a baseline stored early would have turned + # that retry into a skip, losing the activity for good. + if games_total_snapshot is not None: + self.db.set_pair_last_games_total(user_id, gamer['id'], games_total_snapshot) logger.debug(f"📌 Updated period_start_time for {username} to {period_end_approx} (planned period end, next period will start from here)") if 'request_end_time' in locals(): delay = (request_end_time - period_end_approx).total_seconds() @@ -441,6 +599,15 @@ class PeriodicMonitor: async def start_existing_periodic_tasks(self): """Start periodic tasks for all user-gamer pairs that have periods set""" try: + # First bulk status refresh before any check runs, so the checks after a + # restart can already skip. Failure is fine: periodic checks work without + # status (they fall back to requesting every window). + if self.status_refresher is not None: + try: + await self.status_refresher.refresh_once() + except Exception as e: + logger.error(f"❌ Initial player status refresh failed; periodic checks will run without status until the next refresh: {e}") + gamers_with_periods = self.db.get_all_gamers_with_periods() # Get statistics @@ -475,6 +642,10 @@ class PeriodicMonitor: # Start daily counter reset task asyncio.create_task(self.daily_counter_reset_task()) logger.info("✅ Started daily counter reset task") + + if self.status_refresher is not None: + self._status_refresh_task = asyncio.create_task(self.status_refresher.run_forever()) + logger.info(f"✅ Started player status refresh task (every {config.PLAYER_STATUS_REFRESH_MINUTES} min)") except Exception as e: logger.error(f"❌ Error starting existing periodic tasks: {e}") diff --git a/LichessClientTG_bot/player_status.py b/LichessClientTG_bot/player_status.py new file mode 100644 index 0000000..a43213a --- /dev/null +++ b/LichessClientTG_bot/player_status.py @@ -0,0 +1,97 @@ +""" +Bulk player status refresh. + +Every config.PLAYER_STATUS_REFRESH_MINUTES this asks the stats service +(POST /users/status -> one Lichess POST /api/users per 300 names) for every +player that at least one user tracks with a period set, and stores the answer +in gamer_status: whether the account is closed and how many games the player +has played in total (sum of perfs.*.games, puzzle excluded). + +periodic_check (periodic.py) reads that table before each games request: an +unchanged games_total means no game was finished since the pair's last check, +so the games/user call for that window is skipped and the checkpoint is +advanced; a closed account pauses the pair's checks (and tells the owner once). +This turns ~450 individual games/user calls per hour, ~95 % of which found 0 +games, into a couple of bulk calls per refresh. + +The refresh must never be a hard dependency: if it fails (or has never run), +periodic_check falls back to today's behaviour and requests every window. +""" +import asyncio +import logging +import time + +import config +from database import Database +from lichess_api import LichessAPI + +logger = logging.getLogger(__name__) + +# Lichess accepts at most this many names per POST /api/users. +BULK_CHUNK_SIZE = 300 + + +class PlayerStatusRefresher: + def __init__(self, db: Database, lichess_api: LichessAPI): + self.db = db + self.lichess_api = lichess_api + + async def refresh_once(self) -> dict: + """ + One refresh pass over all tracked players. Returns a summary dict + {'tracked', 'answered', 'closed', 'seconds'}; raises on failure (the + caller decides whether that is fatal — run_forever just retries). + """ + started = time.monotonic() + tracked = self.db.get_all_tracked_gamers() + if not tracked: + logger.info("🩺 Player status refresh: 0 tracked, nothing to do") + return {'tracked': 0, 'answered': 0, 'closed': 0, 'seconds': 0.0} + + # Lichess answers with the canonical spelling; match on the lowercase id, + # which is exactly username.lower() (usernames are case-insensitive there). + by_lower = {g['username'].lower(): g['id'] for g in tracked} + rows = [] + closed = 0 + for start in range(0, len(tracked), BULK_CHUNK_SIZE): + chunk = tracked[start:start + BULK_CHUNK_SIZE] + players = await self.lichess_api.get_users_status([g['username'] for g in chunk]) + if players is None: + raise RuntimeError(f"users/status returned no data for chunk {start // BULK_CHUNK_SIZE + 1}") + # checked_at is taken after the answer arrives, per chunk: it must not be + # newer than the data it describes. + checked_at = int(time.time()) + for p in players: + gamer_id = by_lower.get(str(p.get('id') or '').lower()) + if gamer_id is None: + continue + disabled = bool(p.get('disabled', False)) + closed += 1 if disabled else 0 + rows.append({ + 'gamer_id': gamer_id, + 'disabled': disabled, + 'seen_at': p.get('seen_at'), + 'games_total': p.get('games_total'), + 'checked_at': checked_at, + }) + self.db.upsert_gamer_statuses(rows) + seconds = time.monotonic() - started + logger.info( + f"🩺 Player status refresh: {len(tracked)} tracked, {len(rows)} answered, " + f"{closed} closed, took {seconds:.1f}s" + ) + return {'tracked': len(tracked), 'answered': len(rows), 'closed': closed, 'seconds': seconds} + + async def run_forever(self): + """Refresh every PLAYER_STATUS_REFRESH_MINUTES; log and retry at the next tick on any error.""" + interval = config.PLAYER_STATUS_REFRESH_MINUTES * 60 + while True: + try: + await asyncio.sleep(interval) + await self.refresh_once() + except asyncio.CancelledError: + break + except Exception as e: + logger.error(f"❌ Player status refresh failed, will retry in {config.PLAYER_STATUS_REFRESH_MINUTES} min: {e}") + import traceback + logger.error(traceback.format_exc()) diff --git a/LichessWebServices/lichess_client.py b/LichessWebServices/lichess_client.py index fa1e246..7efcc2b 100644 --- a/LichessWebServices/lichess_client.py +++ b/LichessWebServices/lichess_client.py @@ -247,6 +247,77 @@ class LichessClient: logger.error(f"Ошибка при получении игр пользователя {username}: {e}") raise + # Lichess принимает до 300 имён за один POST /api/users. + USERS_BULK_MAX = 300 + + async def get_users_bulk(self, usernames: List[str]) -> Optional[List[Dict[str, Any]]]: + """ + Получает публичные профили до 300 пользователей одним запросом + (POST /api/users, тело — имена через запятую, text/plain). + + Для каждого известного Lichess имени в ответе есть объект с `id`, + `username`, `disabled` (true для закрытых аккаунтов — те же, что отвечают + 200 на /api/user/{u}), `seenAt` (мс, может отсутствовать) и `perfs` + ({"blitz": {"games": N, ...}, ...}; `games` — число партий в этом перфе, + рейтинговых и нет; поля `count` в bulk-ответе НЕТ). Неизвестные имена + просто отсутствуют в ответе. + + Бот использует это для периодических проверок: если сумма `perfs.*.games` + игрока не изменилась с прошлой проверки, он не сыграл ни одной партии и + запрос games/user за это окно можно пропустить — один bulk-запрос вместо + сотен индивидуальных. + + Args: + usernames: Список имён (не более USERS_BULK_MAX) + + Returns: + Список объектов пользователей (как отдаёт Lichess) + + Raises: + ValueError: Если имён больше USERS_BULK_MAX + httpx.HTTPStatusError: При ошибках HTTP (включая 429 — см. _handle_429) + Exception: При других ошибках + """ + if len(usernames) > self.USERS_BULK_MAX: + raise ValueError(f"get_users_bulk: не более {self.USERS_BULK_MAX} имён за запрос, получено {len(usernames)}") + try: + # Rate limiting: ждем если нужно + await self.rate_limiter.wait_if_needed() + + url = f"{self.base_url}/users" + headers = {'Content-Type': 'text/plain'} + if self.app_token: + headers['Authorization'] = f'Bearer {self.app_token}' + body = ",".join(usernames) + + logger.info(f"Bulk-запрос статуса {len(usernames)} пользователей") + + # Тот же общий LICHESS_APP_TOKEN, что и у games/user — проходим через + # shared_token_gate (один запрос в полёте + пауза), приоритет фоновый: + # это обслуживание периодических проверок, интерактив важнее. + await self.shared_token_gate.acquire(priority="background") + try: + response = await self.client.post(url, content=body, headers=headers) + finally: + self.shared_token_gate.release() + response.raise_for_status() + + result = response.json() + if not isinstance(result, list): + raise RuntimeError(f"Неожиданный ответ /api/users: {type(result).__name__}") + logger.info(f"Bulk-статус: запрошено {len(usernames)}, получено {len(result)}") + return result + + except httpx.HTTPStatusError as e: + if e.response.status_code == 429: + # Гейт уже отпущен (finally выше) — pause() здесь безопасен + self._handle_429("", e.response) + logger.error(f"HTTP ошибка при bulk-запросе статуса пользователей: {e}") + raise + except Exception as e: + logger.error(f"Ошибка при bulk-запросе статуса пользователей: {e}") + raise + async def get_puzzle_activity(self, token: str, max_puzzles: int = 50) -> Optional[List[Dict[str, Any]]]: """ Получает активность пользователя по решению задач (пазлов). diff --git a/LichessWebServices/main.py b/LichessWebServices/main.py index 571cd6c..e2b58c3 100644 --- a/LichessWebServices/main.py +++ b/LichessWebServices/main.py @@ -19,7 +19,7 @@ import logging import os from datetime import datetime from stats_service import StatsService -from models import ActivityResponse, ErrorResponse, HealthResponse, GamesOfPeriodResponse, PuzzleOfPeriodResponse +from models import ActivityResponse, ErrorResponse, HealthResponse, GamesOfPeriodResponse, PuzzleOfPeriodResponse, UsersStatusRequest, UsersStatusResponse # ============================================================================= # НАСТРОЙКА ЛОГИРОВАНИЯ @@ -162,7 +162,8 @@ async def root(): "yesterday": "/stats/{username}/yesterday", # Статистика за вчера "week": "/stats/{username}/week", # Статистика за неделю "games_period": "/games/{username}/period?since={timestamp}&until={timestamp}", # Статистика игр за период - "puzzle_period": "/puzzle/period?since={timestamp}&until={timestamp}&max={max}" # Статистика задач за период + "puzzle_period": "/puzzle/period?since={timestamp}&until={timestamp}&max={max}", # Статистика задач за период + "users_status": "POST /users/status {\"usernames\": [...]}" # Bulk-статус игроков (закрыт ли аккаунт, число партий) }, "documentation": "/docs", # Swagger UI документация "openapi_schema": "/openapi.json" # OpenAPI схема @@ -726,6 +727,59 @@ async def get_puzzle_of_period( logger.error(f"Ошибка в endpoint get_puzzle_of_period: {e}") raise HTTPException(status_code=500, detail=f"Внутренняя ошибка сервера: {str(e)}") +@app.post("/users/status", + response_model=UsersStatusResponse, + tags=["statistics"], + summary="Bulk-статус игроков", + description="Один запрос к Lichess (POST /api/users) на до 300 игроков: закрыт ли аккаунт, когда был онлайн, сколько всего партий сыграно", + responses={ + 200: { + "description": "Статус получен", + "content": { + "application/json": { + "example": { + "success": True, + "message": "Статус игроков", + "players": [ + {"username": "Magnus", "id": "magnus", "disabled": False, "seen_at": 1640995200000, "games_total": 12345} + ] + } + } + } + }, + 422: {"description": "Некорректное тело запроса (нужно 1–300 имён)"}, + 502: { + "description": "Ошибка при обращении к Lichess", + "content": {"application/json": {"example": {"detail": "Ошибка при получении статуса игроков: ..."}}} + } + }) +async def get_users_status(body: UsersStatusRequest): + """ + ## Bulk-статус игроков + + Используется ботом перед периодическими проверками: если `games_total` + игрока не изменился с прошлой проверки, запрос партий за окно можно + пропустить; `disabled` — аккаунт закрыт, уведомления по нему ставятся на + паузу. Имена, неизвестные Lichess, в `players` отсутствуют. + + ### Возможные ошибки: + - **422**: Некорректное тело (пустой список или больше 300 имён) + - **502**: Ошибка при обращении к Lichess + """ + if not stats_service: + raise HTTPException(status_code=500, detail="Сервис не инициализирован") + try: + result = await stats_service.get_users_status(body.usernames) + if not result.success: + # Реальная ошибка при обращении к Lichess — не маскируем её под "никого не нашли" + raise HTTPException(status_code=502, detail=result.message) + return result + except HTTPException: + raise + except Exception as e: + logger.error(f"Ошибка в endpoint get_users_status: {e}") + raise HTTPException(status_code=500, detail=f"Внутренняя ошибка сервера: {str(e)}") + if __name__ == "__main__": import uvicorn uvicorn.run(app, host="0.0.0.0", port=8000) diff --git a/LichessWebServices/models.py b/LichessWebServices/models.py index 870fd6e..4ce9ab6 100644 --- a/LichessWebServices/models.py +++ b/LichessWebServices/models.py @@ -259,3 +259,35 @@ class PuzzleOfPeriodResponse(BaseModel): max_puzzles: int = Field(..., description="Максимальное количество задач для получения", example=50) puzzles_in_period: int = Field(..., description="Количество задач в указанном периоде", example=15) data: Optional[PuzzleStats] = Field(None, description="Данные статистики решения задач") + +# ============================================================================= +# МОДЕЛИ ДЛЯ ЭНДПОИНТА BULK-СТАТУСА ИГРОКОВ +# ============================================================================= + +class UsersStatusRequest(BaseModel): + """ + Тело запроса POST /users/status: список имён Lichess (1–300). + """ + usernames: List[str] = Field(..., description="Имена пользователей Lichess (1–300)", min_length=1, max_length=300, example=["magnus", "hikaru"]) + +class PlayerStatus(BaseModel): + """ + Статус одного игрока из bulk-ответа Lichess (POST /api/users). + + games_total — сумма perfs.*.games без puzzle: число сыгранных партий + (рейтинговых и нет). Используется ботом как "счётчик активности": если он + не изменился, игрок не доиграл ни одной партии с прошлой проверки. + """ + username: str = Field(..., description="Каноническое написание имени (как у Lichess)", example="Magnus") + id: str = Field(..., description="ID пользователя (имя в нижнем регистре)", example="magnus") + disabled: bool = Field(False, description="True, если аккаунт закрыт", example=False) + seen_at: Optional[int] = Field(None, description="Когда пользователь был онлайн в последний раз (Unix timestamp в миллисекундах), если известно", example=1640995200000) + games_total: int = Field(..., description="Сумма perfs.*.games без puzzle", example=12345) + +class UsersStatusResponse(BaseModel): + """ + Ответ POST /users/status. Имена, неизвестные Lichess, в players отсутствуют. + """ + success: bool = Field(True, description="False, если запрос к Lichess завершился ошибкой", example=True) + message: str = Field("", description="Сообщение о результате запроса", example="Статус игроков") + players: List[PlayerStatus] = Field(default_factory=list, description="Статусы найденных игроков") diff --git a/LichessWebServices/stats_service.py b/LichessWebServices/stats_service.py index 3889b52..59b6fc3 100644 --- a/LichessWebServices/stats_service.py +++ b/LichessWebServices/stats_service.py @@ -16,7 +16,7 @@ Lichess Statistics API - Сервис обработки статистики from typing import List, Dict, Any, Optional from datetime import datetime, timedelta, date from lichess_client import LichessClient -from models import UserStats, TaskStats, GameModeStats, GamesStats, ActivityResponse, GameStats, GameRow, GamesOfPeriodStats, GamesOfPeriodResponse, PuzzleStats, PuzzleOfPeriodResponse +from models import UserStats, TaskStats, GameModeStats, GamesStats, ActivityResponse, GameStats, GameRow, GamesOfPeriodStats, GamesOfPeriodResponse, PuzzleStats, PuzzleOfPeriodResponse, PlayerStatus, UsersStatusResponse import logging # Настройка логирования для модуля @@ -880,6 +880,49 @@ class StatsService: puzzles_in_period=0 ) + @staticmethod + def _games_total_from_perfs(perfs: Dict[str, Any]) -> int: + """ + Сумма perfs.*.games без puzzle (и прочих не-партийных перфов, у которых + поля games нет — storm/racer/streak отдают runs/score). В bulk-ответе + /api/users поля `count` нет, поэтому считаем сами. + """ + total = 0 + for name, perf in (perfs or {}).items(): + if name == 'puzzle' or not isinstance(perf, dict): + continue + games = perf.get('games') + if isinstance(games, int): + total += games + return total + + async def get_users_status(self, usernames: List[str]) -> UsersStatusResponse: + """ + Bulk-статус игроков (POST /api/users): закрыт ли аккаунт, когда был + онлайн, сколько всего партий сыграно. Имена, неизвестные Lichess, в + ответе отсутствуют — не выдумываем для них записи. + """ + try: + raw = await self.lichess_client.get_users_bulk(usernames) + players = [] + for u in raw or []: + if not isinstance(u, dict) or not u.get('id'): + continue + players.append(PlayerStatus( + username=u.get('username') or u['id'], + id=str(u['id']).lower(), + disabled=bool(u.get('disabled', False)), + seen_at=u.get('seenAt') if isinstance(u.get('seenAt'), int) else None, + games_total=self._games_total_from_perfs(u.get('perfs') or {}), + )) + return UsersStatusResponse(message="Статус игроков", players=players) + except Exception as e: + logger.error(f"Ошибка при получении bulk-статуса игроков: {e}") + return UsersStatusResponse( + message=f"Ошибка при получении статуса игроков: {str(e)}", + success=False, + ) + async def close(self): """ Закрывает сервис статистики. diff --git a/README.md b/README.md index 205310b..9813486 100644 --- a/README.md +++ b/README.md @@ -115,7 +115,8 @@ Telegram бот для управления отслеживанием игро - Каждый пользователь имеет свой набор игроков - Версионность бота (отображается в команде /support) - **Многоязычная поддержка**: Русский и английский языки с автоматическим определением и ручным выбором через `/set_lang` -- **Пейсинг запросов к Lichess**: единая очередь общего токена в stats-сервисе (`LichessWebServices/rate_limiter.py`, SharedTokenGate: 3 с между запросами, интерактивные команды приоритетнее периодических проверок); бот сам запросы к сервису не притормаживает, только ограничивает число одновременных периодических запросов (`PERIODIC_MAX_CONCURRENT_REQUESTS`) +- **Пейсинг запросов к Lichess**: единая очередь общего токена в stats-сервисе (`LichessWebServices/rate_limiter.py`, SharedTokenGate: 3 с между запросами, интерактивные команды приоритетнее периодических проверок); бот сам запросы к сервису не притормаживает, только ограничивает число одновременных периодических запросов (`PERIODIC_MAX_CONCURRENT_REQUESTS`). Через ту же очередь идут и bulk-запросы статуса игроков (см. ниже) +- **Bulk-статус игроков вместо «пустых» проверок**: раз в `PLAYER_STATUS_REFRESH_MINUTES` (15 мин) бот одним `POST /api/users` (до 300 имён за запрос, через `POST /users/status` stats-сервиса) получает по всем отслеживаемым игрокам число сыгранных партий и флаг закрытого аккаунта (`gamer_status`). Если число партий игрока не изменилось с прошлой проверки, периодическая проверка пропускает запрос партий за это окно и просто двигает чекпоинт (не дальше момента обновления статуса); закрытый аккаунт (⛔ в `/getgamers` и `/delgamer`) ставит уведомления по нему на паузу с одним сообщением владельцу, при повторном открытии они возобновляются сами. Пары с токеном (пазлы) не пропускаются; без свежего статуса проверки работают как раньше **Команды:** - `/start` - начало работы с ботом и добавление первого игрока