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>
This commit is contained in:
vrubelroman 2026-10-20 21:46:48 +00:00
parent 6355cd917d
commit 7178b80854
14 changed files with 1141 additions and 1023 deletions

15
.claude/agents/analyst.md Normal file
View file

@ -0,0 +1,15 @@
---
name: analyst
description: System analyst for LichessStatTgWeb. Describes the current state of the system (architecture, data flows, DB schema, operational metrics), writes analytics and funnel reports into docs/, reads prod logs and DB strictly read-only. Use for "describe how X works now", "analyse user paths", "write a report on Y". Never edits code.
tools: Read, Grep, Glob, Bash, Write
---
You are the analyst of the LichessStatTgWeb project (Telegram bot + FastAPI stats service for Lichess players).
Your job: understand and describe, never change code. You produce Markdown documents under `docs/` (create the file with Write) and a short summary for the orchestrator. Facts come from the code, git history, the local test environment and read-only inspection of prod.
Ground rules:
- Prod is `ssh germany`, project in `~/services/LichessStatTgWeb`, containers `lichess-telegram-bot`, `lichess-admin-bot`, `lichess-api`. Prod is READ-ONLY for you: `docker logs`, `docker exec -i lichess-telegram-bot python - <<EOF ... EOF` for SELECT queries on `/app/data/lichess_bot.db`. Never write to the prod DB, never restart anything, never run curl against lichess.org with prod credentials.
- The prod bot log is multi-GB. Always use `docker logs --tail N` (reads from the end; 150k lines ≈ 1 day). Never run `docker logs --since` or read the raw json log file: a full pass takes minutes and loads the host.
- The local test environment runs via `./start.sh` with test tokens from `.env`; local DB is `LichessClientTG_bot/data/lichess_bot.db` (root-owned, read it with `docker exec -i`).
- Write in Russian for documents the owner will read, keep code identifiers in English. Lead with conclusions, give numbers in tables, cite file paths with line numbers for claims about code.
- Do not speculate silently: separate "measured" from "assumed", and say what you could not verify.

View file

@ -0,0 +1,20 @@
---
name: developer
description: Developer for LichessStatTgWeb. Implements a precisely scoped change in the bot (LichessClientTG_bot) or the stats service (LichessWebServices): refactors, features, bug fixes. Keeps behaviour identical unless the brief says otherwise, compiles and import-checks its work, reports the diff summary. Never commits or pushes.
tools: Read, Grep, Glob, Bash, Edit, Write
---
You are the developer of the LichessStatTgWeb project (python-telegram-bot 20.7 bot + FastAPI stats service, SQLite, Docker).
You implement exactly the change described in the brief. Finish the whole brief; if a part is impossible, say so explicitly in your report instead of silently narrowing.
Ground rules:
- Never `git commit`, never `git push`: pushing `main` deploys to production automatically. Leave changes in the working tree and report `git diff --stat`.
- Never touch production (`ssh germany`). Work locally only.
- Before finishing: `python3 -m py_compile` every changed module (set `PYTHONPYCACHEPREFIX` to a scratch dir, `__pycache__` in the repo is root-owned), and import-check inside the real image:
`docker run --rm -i --network none -v "$PWD/LichessClientTG_bot":/app:ro -w /app -e PYTHONDONTWRITEBYTECODE=1 -e TELEGRAM_BOT_TOKEN=123456:ABCDEF -e ADMINPANEL_TELEGRAM_BOT_TOKEN=123456:ABCDEF -e DATABASE_PATH=/tmp/t.db 192.168.8.174:3000/vrubel/lichess-bot:latest python - <<'EOF' ... EOF`
(build an Application with `Application.builder().token("123456:ABCDEF").build()` and call `setup_handlers` to validate handler wiring). For the stats service use the `lichess-api` image the same way.
- `python-dotenv` and `telegram` are not installed on the host; for host-side tests of pure modules (database.py, i18n.py) put a stub `dotenv.py` on `PYTHONPATH`.
- Preserve the existing logging format and the log lines other tooling greps for (`Checking activity for`, `Started periodic task for`, `New user`).
- Keep comments that explain non-obvious decisions (there are many, e.g. about Lichess rate limits and the checkpoint logic); move them with the code, do not drop them.
- Code style: match the surrounding code; English identifiers; comments may be Russian or English as the surrounding file does.
- Report: what changed (per file), what you verified and how, anything you were unsure about.

17
.claude/agents/tester.md Normal file
View file

@ -0,0 +1,17 @@
---
name: tester
description: Tester for LichessStatTgWeb. Verifies a change made by the developer - static checks, import in the real Docker images, DB migrations against a copy of the prod DB, restarting the local test containers and reading their logs, targeted scripts against the local stats API. Reports pass/fail with evidence. Never edits application code, never touches prod.
tools: Read, Grep, Glob, Bash, Write
---
You are the tester of the LichessStatTgWeb project (python-telegram-bot 20.7 bot + FastAPI stats service, SQLite, Docker).
You get a description of a change and what it must preserve. You verify it and report PASS/FAIL per check with the evidence (command + relevant output). You never modify application code; you may write throwaway scripts in the scratchpad directory.
What you can use:
- Static: `python3 -m py_compile` (set `PYTHONPYCACHEPREFIX` to a scratch dir), `git diff`, grep for removed log lines / renamed symbols still referenced.
- Real-image import and handler wiring: `docker run --rm -i --network none -v "$PWD/LichessClientTG_bot":/app:ro -w /app -e PYTHONDONTWRITEBYTECODE=1 -e TELEGRAM_BOT_TOKEN=123456:ABCDEF -e ADMINPANEL_TELEGRAM_BOT_TOKEN=123456:ABCDEF -e DATABASE_PATH=/tmp/t.db 192.168.8.174:3000/vrubel/lichess-bot:latest python - <<'EOF' ... EOF`.
- DB logic: a copy of the prod DB may exist in the scratchpad (`dbtest/prod_copy.db`); if not, ask the orchestrator, do not fetch it from prod yourself. Host-side tests of database.py need a stub `dotenv.py` on `PYTHONPATH`.
- Local test environment: `./start.sh` from the repo root rebuilds and restarts the three containers with test tokens; `docker logs --tail 200 lichess-telegram-bot` etc. The local stats API is at http://localhost:8002 (it uses a separate test Lichess token; keep calls to a handful).
- Never `ssh germany`, never commit or push.
Checklist mindset: does it compile, does it import in the real image, do all handlers still register, does the DB migrate (idempotently), do the containers come up healthy and reach "Application started", are there ERROR lines in the first minutes, did any expected log line disappear. Be specific about what you could NOT test (Telegram interaction needs a human).

View file

@ -15,9 +15,10 @@ from telegram.ext import (
ConversationHandler, MessageHandler, filters
)
from config import ADMINPANEL_TELEGRAM_BOT_TOKEN, DATABASE_PATH, TELEGRAM_BOT_TOKEN, LOG_LEVEL, TTS_URL
from config import ADMINPANEL_TELEGRAM_BOT_TOKEN, DATABASE_PATH, TELEGRAM_BOT_TOKEN, LOG_LEVEL
from database import Database
from message_counters import MessageCounters
from notifications import AdminNotifier
# NOTE: no logging.basicConfig() at import time. This module is imported by bot.py,
# and a module-level basicConfig here used to win over bot.py's own one, silently
@ -34,47 +35,10 @@ class AdminBot:
self.db = Database()
self.application = None
self.counters = MessageCounters()
async def send_notification(self, message: str):
"""Send notification to admin chat"""
admin_chat_id = self.get_admin_chat_id()
if not admin_chat_id:
logger.warning("Admin chat ID not set, cannot send notification")
return
# Try to use application if available (when running as separate service)
if self.application:
try:
await self.application.bot.send_message(
chat_id=admin_chat_id,
text=message,
parse_mode='HTML'
)
logger.debug(f"Notification sent via application to chat {admin_chat_id}")
return
except Exception as e:
logger.warning(f"Failed to send via application: {e}, trying direct API call")
# Fallback: use direct Telegram API call
try:
import aiohttp
url = f"https://api.telegram.org/bot{ADMINPANEL_TELEGRAM_BOT_TOKEN}/sendMessage"
async with aiohttp.ClientSession() as session:
async with session.post(url, json={
"chat_id": admin_chat_id,
"text": message,
"parse_mode": "HTML"
}) as response:
if response.status == 200:
logger.debug(f"Notification sent via direct API to chat {admin_chat_id}")
else:
error_text = await response.text()
logger.error(f"Failed to send notification: {response.status} - {error_text}")
except Exception as e:
logger.error(f"Failed to send admin notification via API: {e}")
import traceback
logger.error(traceback.format_exc())
# Same notifier the bot process uses (notifications.py): posts to the admin
# chat through the Bot API, so it works whether or not this Application runs.
self.notifier = AdminNotifier(self.db)
def get_admin_chat_id(self) -> Optional[int]:
"""Get admin chat ID from database"""
return self.db.get_admin_chat_id()
@ -83,74 +47,13 @@ class AdminBot:
"""Set admin chat ID in database"""
self.db.set_admin_chat_id(chat_id)
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:
import urllib.parse
import aiohttp
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_notification(message)
# Call TTS service with user count
try:
import sqlite3
with sqlite3.connect(self.db.db_path) as conn:
cursor = conn.cursor()
cursor.execute("SELECT COUNT(*) FROM telegram_users")
total_users = cursor.fetchone()[0]
tts_text = f"Появился новый пользователь {total_users}"
await self._call_tts_service(tts_text)
except Exception as e:
logger.error(f"Failed to call TTS for new user: {e}")
await self.notifier.notify_new_user(user_id, username, first_name)
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_notification(message)
# Call TTS service if this is a new gamer
if is_new_gamer:
try:
import sqlite3
with sqlite3.connect(self.db.db_path) as conn:
cursor = conn.cursor()
cursor.execute("SELECT COUNT(DISTINCT username) FROM gamers")
total_gamers = cursor.fetchone()[0]
tts_text = f"Добавлен новый игрок {total_gamers}"
await self._call_tts_service(tts_text)
except Exception as e:
logger.error(f"Failed to call TTS for new gamer: {e}")
await self.notifier.notify_new_player(player_username, added_by_user_id, added_by_username, is_new_gamer)
async def status(self, update: Update, context: ContextTypes.DEFAULT_TYPE):
"""Status command - show statistics"""
@ -472,23 +375,6 @@ class AdminBot:
application.add_handler(CommandHandler("status", self.status))
# Global admin bot instance
_admin_bot_instance: Optional[AdminBot] = None
def get_admin_bot() -> Optional[AdminBot]:
"""Get global admin bot instance"""
return _admin_bot_instance
def init_admin_bot():
"""Initialize admin bot"""
global _admin_bot_instance
if not _admin_bot_instance:
_admin_bot_instance = AdminBot()
return _admin_bot_instance
def main():
"""Main function"""
logging.basicConfig(
@ -499,7 +385,7 @@ def main():
# bot token in it: one line per getUpdates every 30s, token in plain text.
logging.getLogger("httpx").setLevel(logging.WARNING)
admin_bot = init_admin_bot()
admin_bot = AdminBot()
# Create application with Long Polling configuration
application = Application.builder().token(ADMINPANEL_TELEGRAM_BOT_TOKEN).build()

View file

@ -1,10 +1,7 @@
import asyncio
import logging
import sqlite3
import os
import zlib
from datetime import datetime, timedelta
from typing import Dict, Any, Optional
from pathlib import Path
from telegram import Update, InlineKeyboardButton, InlineKeyboardMarkup
@ -13,25 +10,22 @@ from telegram.ext import (
MessageHandler, filters, ContextTypes, ConversationHandler,
PicklePersistence, TypeHandler
)
from telegram.error import Forbidden
import config
from config import (
TELEGRAM_BOT_TOKEN, PERIOD_OPTIONS, POLL_INTERVAL,
POLL_TIMEOUT, DROP_PENDING_UPDATES, ALLOWED_UPDATES,
LICHESS_STATS_API_BASE_URL, ADMINPANEL_TELEGRAM_BOT_TOKEN,
DATABASE_PATH, LOG_LEVEL
)
from version import BOT_VERSION
from database import Database
from lichess_api import LichessAPI, InvalidTokenError
from lichess_api import LichessAPI
from formatters import StatsFormatter
from i18n import t, format_period
from admin_bot import get_admin_bot, init_admin_bot
from message_counters import MessageCounters
from request_queue import get_request_queue
from notifications import AdminNotifier
from onboarding import link_player
from periodic import PeriodicMonitor
import time
import aiohttp
# Configure logging (level from LOG_LEVEL env, INFO by default)
logging.basicConfig(
@ -50,146 +44,21 @@ class LichessBot:
def __init__(self):
self.db = Database()
self.lichess_api = LichessAPI()
self.periodic_tasks = {} # Store periodic tasks
self.period_start_times = {} # Store start times for each gamer
self.application = None # Will be set when application is created
self.counters = MessageCounters() # Message counters
self.request_queue = get_request_queue() # Request queue for rate limiting
async def stop_periodic_task(self, gamer_id: int, user_id: int):
"""Stop periodic task for a user-gamer pair."""
task_key = f"{gamer_id}_{user_id}"
task = self.periodic_tasks.pop(task_key, None)
if task:
task.cancel()
logger.info(f"Cancelled periodic task for gamer_id={gamer_id}, user_id={user_id}")
self.period_start_times.pop(task_key, None)
async def _notify_admin_new_player(self, player_username: str, added_by_user_id: int, added_by_username: Optional[str], is_new_gamer: bool = False):
"""Notify admin about newly linked player (always try to send)."""
try:
admin_bot = get_admin_bot()
if admin_bot:
logger.info("Sending admin notification via admin_bot instance")
await admin_bot.notify_new_player(
player_username=player_username,
added_by_user_id=added_by_user_id,
added_by_username=added_by_username,
is_new_gamer=is_new_gamer
)
return
except Exception as e:
logger.warning(f"notify_new_player via admin_bot failed: {e}")
# Fallback: direct API call using admin bot token and chat id from DB
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"
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}"
)
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": message,
"parse_mode": "HTML"
}) as response:
if response.status != 200:
error_text = await response.text()
logger.error(f"Failed to send admin notification (fallback): {response.status} - {error_text}")
else:
logger.info("Admin notification sent successfully via direct API")
except Exception as e:
logger.error(f"Fallback admin notification failed: {e}")
async def _notify_admin_new_user(self, user_id: int, username: Optional[str], first_name: Optional[str]):
"""Notify admin about new Telegram user (fallback method)."""
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"
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}"
)
logger.info(f"Sending admin notification via direct API to chat_id={admin_chat_id}")
import aiohttp
async with aiohttp.ClientSession() as session:
async with session.post(url, json={
"chat_id": admin_chat_id,
"text": message,
"parse_mode": "HTML"
}) as response:
if response.status == 200:
logger.info(f"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}")
import traceback
logger.error(traceback.format_exc())
@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_admin_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."""
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
hours = self._estimate_backoff_elapsed_hours(consecutive_errors)
url = f"https://api.telegram.org/bot{ADMINPANEL_TELEGRAM_BOT_TOKEN}/sendMessage"
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."
)
logger.info(f"Sending admin 'periodic check failing' 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": message,
"parse_mode": "HTML"
}) as response:
if response.status == 200:
logger.info("Admin 'periodic check failing' notification sent successfully")
else:
error_text = await response.text()
logger.error(f"Failed to send admin 'periodic check failing' notification: {response.status} - {error_text}")
except Exception as e:
logger.error(f"Failed to send admin 'periodic check failing' notification: {e}")
self.notifier = AdminNotifier(self.db)
self.monitor = PeriodicMonitor(self.db, self.lichess_api, self.counters, self.notifier)
self.application = None # Will be set when application is created
async def test_admin_notify(self, update: Update, context: ContextTypes.DEFAULT_TYPE):
"""Manual test to verify admin notifications delivery path."""
user = update.effective_user
try:
await self._notify_admin_new_player("test_player_notify", user.id, user.username if user else None)
await self.notifier.notify_new_player("test_player_notify", user.id, user.username if user else None)
await update.message.reply_text("✅ Admin notification test triggered.")
except Exception as e:
logger.error(f"test_admin_notify failed: {e}")
await update.message.reply_text(f"❌ Failed to trigger admin notification: {e}")
def get_user_language_from_update(self, update: Update) -> str:
"""Get user's selected bot language from database"""
user = update.effective_user
@ -206,83 +75,6 @@ class LichessBot:
return self.db.get_user_language(user.id)
return 'en'
async def start_existing_periodic_tasks(self):
"""Start periodic tasks for all user-gamer pairs that have periods set"""
try:
gamers_with_periods = self.db.get_all_gamers_with_periods()
# Get statistics
import sqlite3
with sqlite3.connect(self.db.db_path) as conn:
cursor = conn.cursor()
cursor.execute("SELECT COUNT(*) FROM telegram_users")
total_users = cursor.fetchone()[0]
cursor.execute("SELECT COUNT(DISTINCT username) FROM gamers")
total_gamers = cursor.fetchone()[0]
logger.info(f"📊 Statistics: {total_users} users, {total_gamers} tracked gamers")
logger.info(f"🔔 Found {len(gamers_with_periods)} user-gamer pairs with periodic notifications enabled")
if len(gamers_with_periods) == 0:
logger.warning("⚠️ No periodic notifications configured! Users need to set periods using /setperiod")
# Start request queue processor
self.request_queue._start_processor()
logger.info("✅ Request queue processor started")
active_gamers = [g for g in gamers_with_periods if g['period_minutes'] > 0]
# Stagger task creation across a short startup window instead of firing all
# ~N tasks' first (blocking) sqlite checkpoint read in the same event loop
# tick. Small and one-off — the real anti-lockstep fix is the per-pair
# checkpoint jitter in periodic_check, this just smooths process boot.
stagger_step = config.PERIODIC_STARTUP_STAGGER_MAX_SECONDS / max(1, len(active_gamers))
for gamer in active_gamers:
user_id = gamer['user_id']
username = gamer['username']
period = gamer['period_minutes']
# Start periodic task with user_id and gamer
await self.start_periodic_task(gamer, user_id, period)
logger.info(f"✅ Started periodic task for {username} (user {user_id}) with period {period} minutes")
if stagger_step > 0:
await asyncio.sleep(stagger_step)
logger.info(f"✅ All periodic tasks started. Total: {len(active_gamers)}")
# Start daily counter reset task
asyncio.create_task(self.daily_counter_reset_task())
logger.info("✅ Started daily counter reset task")
except Exception as e:
logger.error(f"❌ Error starting existing periodic tasks: {e}")
import traceback
logger.error(traceback.format_exc())
async def daily_counter_reset_task(self):
"""Background task to reset daily counters at midnight"""
while True:
try:
# Calculate seconds until next midnight
now = datetime.now()
next_midnight = (now + timedelta(days=1)).replace(hour=0, minute=0, second=0, microsecond=0)
seconds_until_midnight = (next_midnight - now).total_seconds()
logger.info(f"Daily counter reset task: waiting {seconds_until_midnight} seconds until next midnight")
await asyncio.sleep(seconds_until_midnight)
# Reset daily counters
self.counters._reset_daily_counters_if_needed()
logger.info("Daily counters reset at midnight")
except asyncio.CancelledError:
break
except Exception as e:
logger.error(f"Error in daily counter reset task: {e}")
import traceback
logger.error(traceback.format_exc())
# Wait 1 hour before retrying
await asyncio.sleep(3600)
async def start(self, update: Update, context: ContextTypes.DEFAULT_TYPE):
"""Start command handler"""
logger.info(f"📝 start() method called for user {update.effective_user.id}")
@ -300,25 +92,15 @@ class LichessBot:
# Notify admin bot about new user
if is_new_user:
try:
admin_bot = get_admin_bot()
if admin_bot:
await admin_bot.notify_new_user(
user_id=user.id,
username=user.username,
first_name=user.first_name
)
else:
# Fallback: direct API call
await self._notify_admin_new_user(user.id, user.username, user.first_name)
await self.notifier.notify_new_user(
user_id=user.id,
username=user.username,
first_name=user.first_name
)
except Exception as e:
logger.error(f"Failed to notify admin about new user: {e}")
import traceback
logger.error(traceback.format_exc())
# Try fallback
try:
await self._notify_admin_new_user(user.id, user.username, user.first_name)
except Exception as e2:
logger.error(f"Fallback notification also failed: {e2}")
lang = self.get_user_language_from_update(update)
start_msg = t('start_message', lang)
@ -522,9 +304,9 @@ class LichessBot:
"""Handle token input for /addtoken"""
token = update.message.text.strip()
user_id = update.effective_user.id
logger.info(f"Processing token for user {user_id}, token prefix: {token[:10]}...")
# Get username from token
profile = await self.lichess_api.get_user_profile(token)
logger.info(f"Profile response: {profile is not None}")
@ -533,8 +315,8 @@ class LichessBot:
if username:
# Check if this gamer is already tracked by this user
user_gamers = self.db.get_user_gamers(user_id)
existing_gamer = next((g for g in user_gamers if g['username'] == username), None)
existing_gamer = next((g for g in user_gamers if g['username'].lower() == username.lower()), None)
lang = self.get_user_language_from_update(update)
if existing_gamer:
# Update token for existing gamer
@ -545,58 +327,21 @@ class LichessBot:
# Always notify admin about link/added player
try:
user_obj = update.effective_user
await self._notify_admin_new_player(username, user_id, user_obj.username if user_obj else None)
await self.notifier.notify_new_player(username, user_id, user_obj.username if user_obj else None)
except Exception as e:
logger.error(f"Admin notify failed after token update: {e}")
else:
# Add new gamer and link with token
# Check if gamer already exists
import sqlite3
with sqlite3.connect(self.db.db_path) as conn:
cursor = conn.cursor()
cursor.execute("SELECT id FROM gamers WHERE username = ?", (username,))
existing_gamer = cursor.fetchone()
is_new_gamer = existing_gamer is None
gamer_id = self.db.add_gamer(username)
self.db.add_user_gamer(user_id, gamer_id, token)
# Set default period to 1 hour (60 minutes) for new gamer
self.db.set_user_gamer_period(user_id, gamer_id, 60)
self.counters.increment('gamer_added')
# If this is the first gamer for this user, make it active
user_gamers = self.db.get_user_gamers(user_id)
if len(user_gamers) == 1:
self.db.set_user_active_gamer(user_id, gamer_id)
# Start periodic task for this gamer (60 minutes period)
try:
gamer_data = {
'id': gamer_id,
'username': username,
'token': token,
'period_minutes': 60
}
await self.start_periodic_task(gamer_data, user_id, 60)
logger.info(f"Started periodic task for {username} (user {user_id}) with period 60 minutes")
except Exception as e:
logger.error(f"Failed to start periodic task for {username}: {e}")
import traceback
logger.error(traceback.format_exc())
# Notify admin bot about new player (always notify on link)
try:
user_obj = update.effective_user
await self._notify_admin_new_player(
username, user_id, user_obj.username if user_obj else None, is_new_gamer
# Add new gamer and link with token (shared with /addgamer, see onboarding.py)
result = await link_player(self, user_id, update.effective_user, username, token)
if not result.added:
# Pair appeared between the check above and the insert; the token is stored
await update.message.reply_text(
t('token_added', lang, username=username)
)
else:
await update.message.reply_text(
t('gamer_added_with_token', lang, username=username)
)
except Exception as e:
logger.error(f"Admin notify failed after adding gamer with token: {e}")
await update.message.reply_text(
t('gamer_added_with_token', lang, username=username)
)
return ConversationHandler.END
else:
lang = self.get_user_language_from_update(update)
@ -610,7 +355,7 @@ class LichessBot:
t('invalid_token', lang)
)
return WAITING_FOR_TOKEN
async def handle_username(self, update: Update, context: ContextTypes.DEFAULT_TYPE):
"""Handle username input for /addgamer"""
user_id = update.effective_user.id
@ -674,63 +419,19 @@ class LichessBot:
# Keep awaiting flag - don't clear it, so user can try again
return
# Add gamer to database (without token)
# Check if gamer already exists in global gamers table
import sqlite3
with sqlite3.connect(self.db.db_path) as conn:
cursor = conn.cursor()
cursor.execute("SELECT id FROM gamers WHERE lower(username) = lower(?)", (username,))
existing_gamer_row = cursor.fetchone()
is_new_gamer = existing_gamer_row is None
gamer_id = self.db.add_gamer(username)
# Link user to gamer (without token)
added = self.db.add_user_gamer(user_id, gamer_id, None)
# Add gamer to database (without token) and link it to this user
# (shared with /addtoken, see onboarding.py)
result = await link_player(self, user_id, update.effective_user, username, None)
# If add_user_gamer returned False, it means the pair already exists (shouldn't happen after our check, but just in case)
if not added:
if not result.added:
await update.message.reply_text(
t('gamer_already_added', lang, username=username) + '\n\n' + t('addgamer_prompt', lang),
parse_mode='HTML'
)
# Keep awaiting flag - don't clear it, so user can try again
return
# Set default period to 1 hour (60 minutes) for new gamer
self.db.set_user_gamer_period(user_id, gamer_id, 60)
self.counters.increment('gamer_added')
logger.info(f"addgamer: player {username} added for user {user_id} (new_gamer={is_new_gamer})")
# If this is the first gamer for this user, make it active
user_gamers = self.db.get_user_gamers(user_id)
if len(user_gamers) == 1:
self.db.set_user_active_gamer(user_id, gamer_id)
# Start periodic task for this gamer (60 minutes period)
try:
gamer_data = {
'id': gamer_id,
'username': username,
'token': None,
'period_minutes': 60
}
await self.start_periodic_task(gamer_data, user_id, 60)
logger.info(f"Started periodic task for {username} (user {user_id}) with period 60 minutes")
except Exception as e:
logger.error(f"Failed to start periodic task for {username}: {e}")
import traceback
logger.error(traceback.format_exc())
# Notify admin bot about player link (always notify)
try:
user_obj = update.effective_user
await self._notify_admin_new_player(
username, user_id, user_obj.username if user_obj else None, is_new_gamer
)
logger.info(f"Admin notification processed for player {username}")
except Exception as e:
logger.error(f"Failed to notify admin about new player link: {e}")
lang = self.get_user_language_from_update(update)
await update.message.reply_text(
t('gamer_added', lang, username=username),
@ -742,7 +443,7 @@ class LichessBot:
except Exception:
pass
return
async def getgamers(self, update: Update, context: ContextTypes.DEFAULT_TYPE):
"""Get all gamers for the current user and allow selection"""
user_id = update.effective_user.id
@ -1399,7 +1100,7 @@ class LichessBot:
# Отключаем мониторинг: чистим чекпоинт, чтобы при повторном включении
# не было catch-up на потенциально очень старое (устаревшее) окно.
self.db.clear_period_checkpoint(user_id, gamer_id)
await self.stop_periodic_task(gamer_id, user_id)
await self.monitor.stop_periodic_task(gamer_id, user_id)
await query.edit_message_text(
t('notifications_disabled', lang, username=selected_gamer['username'])
)
@ -1409,7 +1110,7 @@ class LichessBot:
)
# Start periodic task for this gamer (send to user's personal messages)
await self.start_periodic_task(selected_gamer, user_id, period)
await self.monitor.start_periodic_task(selected_gamer, user_id, period)
async def set_lang(self, update: Update, context: ContextTypes.DEFAULT_TYPE):
"""Show language selection menu"""
@ -1531,374 +1232,6 @@ class LichessBot:
parse_mode='HTML'
)
async def start_periodic_task(self, gamer: Dict[str, Any], user_id: int, period_minutes: int):
"""Start periodic task for a gamer"""
task_key = f"{gamer['id']}_{user_id}"
# Cancel existing task if any
if task_key in self.periodic_tasks:
self.periodic_tasks[task_key].cancel()
logger.info(f"Cancelled existing periodic task for {gamer['username']}")
# Remove old start time
if task_key in self.period_start_times:
del self.period_start_times[task_key]
# Create new periodic task
task = asyncio.create_task(
self.periodic_check(gamer, user_id, period_minutes)
)
self.periodic_tasks[task_key] = task
# Оповещать админ-бота о затяжной серии ошибок каждые ADMIN_NOTIFY_ERROR_THRESHOLD
# подряд идущих ошибок (~2 часа при капнутом бэкоффе в 300с на попытку)
ADMIN_NOTIFY_ERROR_THRESHOLD = 25
@staticmethod
def _checkpoint_jitter_seconds(user_id: int, gamer_id: int, period_minutes: int) -> float:
"""
Deterministic per-(user, gamer) jitter applied whenever a checkpoint gets
pinned to "now" (backlog collapse / first check). Without this, every pair
sharing the same period_minutes re-locks onto the exact same wall-clock
phase on every bot restart, causing them all to become "due" in the same
instant forever after. Stable across restarts (unlike Python's salted
hash()), and capped well below STALE_BACKLOG_THRESHOLD so it never
interacts with backlog-notification suppression.
"""
jitter_cap = min(period_minutes * 60 * config.PERIODIC_CHECKPOINT_JITTER_FRACTION,
config.PERIODIC_CHECKPOINT_JITTER_MAX_SECONDS)
if jitter_cap <= 0:
return 0.0
digest = zlib.crc32(f"{user_id}:{gamer_id}".encode())
return digest % jitter_cap
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}"
username = gamer['username']
checkpoint_ts = self.db.get_period_checkpoint(user_id, gamer['id'])
if checkpoint_ts is not None:
restored_time = datetime.fromtimestamp(checkpoint_ts)
self.period_start_times[task_key] = restored_time
logger.info(f"♻️ Restored periodic checkpoint for {username} (user {user_id}) at {restored_time}")
logger.info(f"🔄 Started periodic monitoring for {username} (user {user_id}) with {period_minutes} minute intervals")
consecutive_errors = 0
max_consecutive_errors = 5
is_first_check = True # Флаг для первой проверки
while True:
try:
# Проверяем, что период все еще установлен в БД
current_gamers = self.db.get_user_gamers(user_id)
gamer_still_exists = False
current_period = 0
for g in current_gamers:
if g['id'] == gamer['id']:
gamer_still_exists = True
current_period = g.get('period_minutes', 0)
break
# Если игрок удален или период отключен, прекращаем мониторинг
if not gamer_still_exists or current_period == 0:
logger.info(f"Periodic monitoring stopped for {gamer['username']}: gamer removed or period disabled")
if task_key in self.periodic_tasks:
del self.periodic_tasks[task_key]
if task_key in self.period_start_times:
del self.period_start_times[task_key]
break
# Обновляем период на случай, если он был изменен
if current_period != period_minutes:
logger.info(f"Period changed for {gamer['username']} from {period_minutes} to {current_period} minutes")
period_minutes = current_period
# Получаем сохраненное время последней проверки для расчета следующего периода
# Используем флаг is_first_check для первой проверки вместо проверки наличия ключа
last_check_time = self.period_start_times.get(task_key)
if is_first_check and checkpoint_ts is None:
last_check_time = None # Принудительно делаем первую проверку
is_first_check = False
if last_check_time:
# Уже была хотя бы одна проверка
# Рассчитываем, когда должен начаться следующий период
next_period_start = last_check_time + timedelta(minutes=period_minutes)
now = datetime.now()
# Если следующий период еще не наступил, ждем
if next_period_start > now:
wait_seconds = (next_period_start - now).total_seconds()
logger.debug(f"⏳ Waiting {wait_seconds:.1f} seconds until next period start ({next_period_start}) for {username}")
await asyncio.sleep(wait_seconds)
# Используем сохраненное время как начало периода
since_time = last_check_time
# Конец периода - это момент, когда должен был начаться следующий период
period_end_approx = next_period_start
logger.debug(f"📌 Using saved period: from {since_time} to {period_end_approx}")
else:
# Мы отстаём от расписания (бэклог): если догонять по period_minutes
# за раз, при большом отставании (недели простоя, много отслеживаемых
# игроков через один общий RequestQueue) чекпоинт никогда не догонит
# текущее время — отставание только растёт. Вместо этого закрываем
# весь пропущенный промежуток одним запросом и сразу прыгаем к "сейчас".
# Джиттер (см. _checkpoint_jitter_seconds) не даёт всем парам с
# одинаковым period_minutes зафиксироваться на один и тот же момент.
since_time = last_check_time
jitter = self._checkpoint_jitter_seconds(user_id, gamer['id'], period_minutes)
period_end_approx = now - timedelta(seconds=jitter)
if period_end_approx - next_period_start > timedelta(minutes=period_minutes):
logger.warning(
f"⏰ {username} is behind schedule by "
f"{(now - next_period_start).total_seconds():.0f}s; "
f"collapsing backlog into one request from {since_time} to {period_end_approx}"
)
logger.info(f"📌 Using saved period: from {since_time} to {period_end_approx}")
else:
# Первая проверка - ждем period_minutes минут от момента запуска
logger.info(f"⏳ First check: waiting {period_minutes} minutes before first check for {username}")
await asyncio.sleep(period_minutes * 60)
# Получаем текущее время (с джиттером, см. _checkpoint_jitter_seconds)
jitter = self._checkpoint_jitter_seconds(user_id, gamer['id'], period_minutes)
period_end_approx = datetime.now() - timedelta(seconds=jitter)
# Начало периода - текущее время минус period_minutes
since_time = period_end_approx - timedelta(minutes=period_minutes)
logger.info(f"📌 First check: period from {since_time} to {period_end_approx}")
# A collapsed backlog spanning way more than a normal check window isn't
# "recent activity" anymore — dumping a multi-week, game-by-game report
# on the user reads as spam, not a periodic update. Catch the checkpoint
# up silently in that case instead of sending the full notification.
STALE_BACKLOG_THRESHOLD = timedelta(hours=2)
is_stale_backlog = (period_end_approx - since_time) > STALE_BACKLOG_THRESHOLD
if is_stale_backlog:
logger.warning(
f"⏭️ {username}: collapsed window ({since_time} to {period_end_approx}) "
f"exceeds {STALE_BACKLOG_THRESHOLD}; catching up checkpoint silently, "
f"no notification will be sent for this stale backlog"
)
since_timestamp = int(since_time.timestamp() * 1000)
# Используем приблизительное время как until_timestamp
# После получения ответа пересчитаем фактическое время
until_timestamp_approx = int(period_end_approx.timestamp() * 1000)
logger.info(f"🔍 Checking activity for {username} (user {user_id}): period from {since_time} to {period_end_approx} (approx, last {period_minutes} minutes)")
logger.debug(f"📅 Unix timestamps: since={since_timestamp}, until_approx={until_timestamp_approx}")
# Делаем запросы к API через очередь с обработкой ошибок
games_data = None
puzzles_data = None
try:
# Добавляем запрос в очередь (будет выполнен с задержкой 7 секунд)
logger.debug(f"📥 Adding games request to queue for {gamer['username']}")
games_data = await self.request_queue.add_request(
self.lichess_api.get_games_period,
gamer['username'], since_timestamp, until_timestamp_approx,
include_games=True
)
if games_data is None:
raise RuntimeError("Games period API returned no data")
# Фиксируем фактическое время получения ответа
request_end_time = datetime.now()
logger.debug(f"✅ Games API response received for {gamer['username']} at {request_end_time}")
except Exception as e:
logger.error(f"❌ Error getting games data for {gamer['username']}: {e}")
consecutive_errors += 1
backoff_seconds = min(300, 60 * consecutive_errors)
if consecutive_errors >= max_consecutive_errors:
logger.error(f"⚠️ {consecutive_errors} consecutive errors for {gamer['username']}; still retrying the same period (backoff {backoff_seconds}s)")
else:
logger.warning(f"⚠️ Games data unavailable for {gamer['username']}; retrying the same period in {backoff_seconds}s")
if consecutive_errors == self.ADMIN_NOTIFY_ERROR_THRESHOLD or (
consecutive_errors > self.ADMIN_NOTIFY_ERROR_THRESHOLD
and consecutive_errors % self.ADMIN_NOTIFY_ERROR_THRESHOLD == 0
):
await self._notify_admin_periodic_check_failing(gamer['username'], user_id, consecutive_errors)
await asyncio.sleep(backoff_seconds)
continue
if gamer.get('token'):
# Транзитные ошибки получения пазлов обрабатываются так же, как ошибки игр:
# исключение всплывает во внешний обработчик, чекпоинт не продвигается,
# то же окно ретраится на следующей итерации (не считаем "пазлов не было").
# InvalidTokenError — отдельный случай: Lichess отклонил токен насовсем
# (401), ретраить бессмысленно — это раньше приводило к вечному циклу
# ретраев без продвижения чекпоинта (см. историю с Dor1zz). Вместо этого
# отключаем пазлы для этой пары и продолжаем отслеживать партии как обычно.
logger.debug(f"📥 Adding puzzles request to queue for {gamer['username']}")
try:
puzzles_data = await self.request_queue.add_request(
self.lichess_api.get_puzzles_period,
gamer['token'], since_timestamp, until_timestamp_approx, 150
)
except InvalidTokenError:
logger.warning(f"🔑 Token rejected by Lichess for {gamer['username']} (user {user_id}); disabling puzzle tracking for this pair")
self.db.clear_user_gamer_token(user_id, gamer['id'])
gamer['token'] = None
puzzles_data = None
try:
user_lang = self.db.get_user_language(user_id)
await self.application.bot.send_message(
chat_id=user_id,
text=t('token_rejected_notice', user_lang, username=gamer['username'])
)
except Exception as notify_err:
logger.error(f"Failed to notify user {user_id} about rejected token: {notify_err}")
else:
if puzzles_data is None:
raise RuntimeError("Puzzles period API returned no data")
# Обновляем фактическое время после получения ответа по пазлам
request_end_time = datetime.now()
logger.debug(f"✅ Puzzles API response received for {gamer['username']} at {request_end_time}")
# Сбрасываем счетчик ошибок при успешном запросе
consecutive_errors = 0
# Проверяем наличие реальной активности
has_games = False
total_games = 0
if games_data:
# Логируем структуру ответа для отладки
logger.debug(f"📊 Games data structure for {username}: {games_data}")
# Проверяем games_count на верхнем уровне (приоритет)
top_level_count = games_data.get('games_count', 0)
logger.debug(f"🔍 Top-level games_count: {top_level_count}")
if top_level_count > 0:
total_games = top_level_count
has_games = True
logger.debug(f"✅ Found {total_games} games via games_count field")
else:
# Также проверяем data.total.games_played
games_data_dict = games_data.get('data')
if games_data_dict:
data_total = games_data_dict.get('total', {})
total_games_played = data_total.get('games_played', 0) if data_total else 0
else:
total_games_played = 0
logger.debug(f"🔍 data.total.games_played: {total_games_played}")
if total_games_played > 0:
total_games = total_games_played
has_games = True
logger.debug(f"✅ Found {total_games} games via data.total.games_played field")
else:
logger.debug(f"⚠️ No games found: games_count={top_level_count}, data.total.games_played={total_games_played}")
else:
logger.warning(f"⚠️ No games_data returned for {username}")
has_puzzles = False
total_puzzles = 0
if puzzles_data:
logger.debug(f"📊 Puzzles data structure for {username}: {puzzles_data}")
# Проверяем puzzles_in_period на верхнем уровне (приоритет)
if puzzles_data.get('puzzles_in_period', 0) > 0:
total_puzzles = puzzles_data.get('puzzles_in_period', 0)
has_puzzles = True
logger.debug(f"✅ Found {total_puzzles} puzzles via puzzles_in_period field")
# Также проверяем data.total_attempts
elif puzzles_data.get('data') and puzzles_data.get('data', {}).get('total_attempts', 0) > 0:
total_puzzles = puzzles_data.get('data', {}).get('total_attempts', 0)
has_puzzles = True
logger.debug(f"✅ Found {total_puzzles} puzzles via data.total_attempts field")
logger.debug(f"🔍 Activity check result for {username}: has_games={has_games} (total={total_games}), has_puzzles={has_puzzles} (total={total_puzzles})")
# Отправляем уведомление только если есть реальная активность и это не
# молчаливый догон устаревшего бэклога (is_stale_backlog, см. выше).
# Ошибки форматирования/отправки НЕ перехватываются здесь: они должны
# всплыть во внешний обработчик, чтобы чекпоинт не продвинулся и уже
# обнаруженная активность была отправлена повторно на следующей попытке,
# а не потеряна молча.
if (has_games or has_puzzles) and not is_stale_backlog:
logger.info(f"📊 Activity detected for {gamer['username']}, preparing notification...")
user_lang = self.db.get_user_language(user_id)
# Label the notification with the actual queried window, not the
# configured period: after a backlog collapse (see above) they can
# differ by days/weeks, and showing "for 15 minutes" on activity
# that's actually from weeks ago is misleading.
actual_span_minutes = max(1, round((period_end_approx - since_time).total_seconds() / 60))
notification = StatsFormatter.format_period_notification(
gamer['username'], games_data, puzzles_data, actual_span_minutes, lang=user_lang
)
if not self.application:
raise RuntimeError(f"Application not initialized, cannot send notification for {gamer['username']} to user {user_id}")
# Forbidden (user blocked the bot) is permanent, not worth retrying:
# without this, consecutive_errors gets reset to 0 above right before
# this call succeeds/fails, so the outer handler's backoff never grows
# past 60s and this pair retries forever, wasting queue capacity that
# other users' real checks need.
try:
await self.application.bot.send_message(
chat_id=user_id,
text=notification,
parse_mode='Markdown'
)
except Forbidden:
logger.warning(f"🚫 User {user_id} blocked the bot; stopping periodic monitoring for {gamer['username']}")
self.db.set_user_gamer_period(user_id, gamer['id'], 0)
if task_key in self.periodic_tasks:
del self.periodic_tasks[task_key]
if task_key in self.period_start_times:
del self.period_start_times[task_key]
return
logger.info(f"✅ Sent periodic notification for {gamer['username']} to user {user_id}")
# Increment periodic notification counter
self.counters.increment('periodic_notification')
elif is_stale_backlog and (has_games or has_puzzles):
logger.info(f"⏭️ Suppressed stale backlog notification for {gamer['username']} (had activity, but window too old)")
else:
logger.debug(f"⏭️ No activity found for {gamer['username']} in the last {period_minutes} minutes")
# Обновляем время начала следующего периода на ПЛАНИРУЕМОЕ время окончания текущего периода
# (period_end_approx), а не на фактическое время завершения запроса (request_end_time).
# Это гарантирует непрерывность периодов без пропусков:
# - Проверяем период A-B
# - Следующая проверка будет периода B-C
# - Без пропусков между A-B и B-C
#
# Использование request_end_time приведет к пропуску диапазона между period_end_approx и request_end_time
#
# 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()))
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()
if delay > 0:
logger.debug(f"⏱️ Request completed with {delay:.1f}s delay after planned period end")
except asyncio.CancelledError:
logger.info(f"Periodic check cancelled for {gamer['username']}")
break
except Exception as e:
consecutive_errors += 1
logger.error(f"Error in periodic check for {gamer['username']}: {e}")
import traceback
logger.error(f"Full traceback: {traceback.format_exc()}")
# Не убиваем задачу навсегда: ретраим то же окно с растущим бэкоффом
# (капается на 300с), пока Lichess/Telegram не восстановятся.
backoff_seconds = min(300, 60 * consecutive_errors)
if consecutive_errors >= max_consecutive_errors:
logger.error(f"⚠️ {consecutive_errors} consecutive errors for {gamer['username']}; still retrying the same period (backoff {backoff_seconds}s)")
if consecutive_errors == self.ADMIN_NOTIFY_ERROR_THRESHOLD or (
consecutive_errors > self.ADMIN_NOTIFY_ERROR_THRESHOLD
and consecutive_errors % self.ADMIN_NOTIFY_ERROR_THRESHOLD == 0
):
await self._notify_admin_periodic_check_failing(gamer['username'], user_id, consecutive_errors)
await asyncio.sleep(backoff_seconds)
continue
async def log_incoming_update(self, update: Update, context: ContextTypes.DEFAULT_TYPE):
"""One INFO line per incoming update (runs before all other handlers, never blocks them)."""
user = update.effective_user
@ -1924,6 +1257,7 @@ class LichessBot:
def setup_handlers(self, application: Application):
"""Setup all handlers"""
self.application = application # Store application reference
self.monitor.application = application # periodic notifications go out via application.bot
# Group -1 runs before group 0 and does not stop it: a single log line per update
application.add_handler(TypeHandler(Update, self.log_incoming_update), group=-1)
@ -1980,9 +1314,6 @@ class LichessBot:
def main():
"""Main function"""
# Initialize admin bot for notifications (admin bot runs as separate service)
init_admin_bot()
bot = LichessBot()
# Persist user_data (e.g. awaiting_addgamer_username) to disk so an in-flight
@ -1999,10 +1330,11 @@ def main():
# Set application reference for periodic tasks
bot.application = application
bot.monitor.application = application
# Start periodic tasks for existing gamers (will be called after application starts)
async def post_init(app):
await bot.start_existing_periodic_tasks()
await bot.monitor.start_existing_periodic_tasks()
application.post_init = post_init

View file

@ -20,13 +20,19 @@ TTS_URL = os.getenv("TTS_URL") or None
LICHESS_API_BASE_URL = "https://lichess.org/api"
LICHESS_STATS_API_BASE_URL = "http://localhost:8002" # Host port for stats API when bot runs with host networking
# Пейсинг очереди запросов к НАШЕМУ ЖЕ локальному stats-сервису (LICHESS_STATS_API_BASE_URL).
# Это НЕ защита от рейт-лимитера Lichess — та уже есть ниже по стеку, в
# LichessWebServices/rate_limiter.py (0.2s, единственный process-wide инстанс,
# применяется перед каждым реальным вызовом lichess.org, общий для всех клиентов
# stats-сервиса). Эти числа можно свободно менять — они не увеличивают нагрузку на Lichess.
LICHESS_REQUEST_QUEUE_MIN_DISPATCH_INTERVAL = 2.0 # сек между диспетчами запросов (жёсткий пол)
LICHESS_REQUEST_QUEUE_MAX_CONCURRENT = 10 # макс. запросов к stats-сервису одновременно; 1 = откат к строго последовательному режиму
# Слои пейсинга запросов (чтобы не плодить лишние):
# - Настоящий лимитер общего Lichess-токена — SharedTokenGate в
# LichessWebServices/rate_limiter.py (6 с между запросами, приоритет interactive >
# background). Он один на весь stats-сервис и общий для всех его клиентов.
# - Бот запросы к НАШЕМУ ЖЕ локальному stats-сервису (LICHESS_STATS_API_BASE_URL)
# не притормаживает: любая задержка здесь только добавляла бы латентность перед
# той же очередью. Единственное ограничение — сколько периодических запросов
# может быть открыто одновременно (см. periodic.py), чтобы сотни пар не держали
# по idle-соединению, пока ждут в очереди сервиса. Это число не влияет на
# нагрузку на Lichess.
# - Бот-сайд RateLimiter (rate_limiter.py, 0.2 с) остаётся только для прямых
# вызовов lichess.org (check_user_exists, get_user_ratings, get_user_profile).
PERIODIC_MAX_CONCURRENT_REQUESTS = 10
# Джиттер чекпоинтов периодических проверок: не даёт парам (user, gamer) с одинаковым
# period_minutes синхронизироваться на один и тот же wall-clock момент при рестарте бота

View file

@ -282,6 +282,23 @@ class Database:
conn.commit()
return cursor.rowcount > 0
def gamer_exists(self, username: str) -> bool:
"""Whether this username (case-insensitive, like Lichess) is already in the global gamers table."""
with sqlite3.connect(self.db_path) as conn:
cursor = conn.cursor()
cursor.execute("SELECT 1 FROM gamers WHERE lower(username) = lower(?)", (username,))
return cursor.fetchone() is not None
def get_counts(self) -> Dict[str, int]:
"""Total Telegram users and distinct tracked gamers (startup statistics line, admin TTS announcements)."""
with sqlite3.connect(self.db_path) as conn:
cursor = conn.cursor()
cursor.execute("SELECT COUNT(*) FROM telegram_users")
users = cursor.fetchone()[0]
cursor.execute("SELECT COUNT(DISTINCT username) FROM gamers")
gamers = cursor.fetchone()[0]
return {'users': users, 'gamers': gamers}
def add_gamer(self, username: str) -> int:
"""Add a new gamer to the database (return gamer_id)"""
with sqlite3.connect(self.db_path) as conn:

View file

@ -16,6 +16,11 @@ class LichessAPI:
def __init__(self):
self.lichess_base_url = LICHESS_API_BASE_URL
self.stats_base_url = LICHESS_STATS_API_BASE_URL
# Only for calls that go to lichess.org directly (anonymous / user-token
# endpoints with their own Lichess limits). Calls to our local stats service
# are not paced here: its SharedTokenGate (LichessWebServices/rate_limiter.py)
# is the real limiter for the shared Lichess token, and a bot-side delay in
# front of it only added latency.
self.rate_limiter = get_rate_limiter()
async def get_user_profile(self, token: str) -> Optional[Dict[str, Any]]:
@ -44,7 +49,6 @@ class LichessAPI:
async def get_today_stats(self, username: str) -> Optional[Dict[str, Any]]:
"""Get today's statistics from our stats API"""
logger.info(f"🔍 LichessAPI.get_today_stats: username={username}, stats_base_url={self.stats_base_url}")
await self.rate_limiter.wait_if_needed()
url = f"{self.stats_base_url}/stats/{username}/today"
logger.info(f"🔍 Making request to: {url}")
try:
@ -72,7 +76,6 @@ class LichessAPI:
async def get_yesterday_stats(self, username: str) -> Optional[Dict[str, Any]]:
"""Get yesterday's statistics from our stats API"""
await self.rate_limiter.wait_if_needed()
try:
async with aiohttp.ClientSession() as session:
async with session.get(
@ -89,7 +92,6 @@ class LichessAPI:
async def get_week_stats(self, username: str) -> Optional[Dict[str, Any]]:
"""Get week's statistics from our stats API"""
await self.rate_limiter.wait_if_needed()
try:
async with aiohttp.ClientSession() as session:
async with session.get(
@ -113,7 +115,6 @@ class LichessAPI:
service's shared Lichess-token queue, so an on-demand command doesn't
wait behind the whole periodic-check backlog.
"""
await self.rate_limiter.wait_if_needed()
try:
url = f"{self.stats_base_url}/games/{username}/period"
params = {"since": since, "until": until, "priority": priority}
@ -146,7 +147,6 @@ class LichessAPI:
so callers can tell that apart from a transient failure (network error,
Lichess hiccup) where retrying the same window later makes sense.
"""
await self.rate_limiter.wait_if_needed()
headers = {"Authorization": f"Bearer {token}"}
try:

View file

@ -0,0 +1,122 @@
"""
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)

View file

@ -0,0 +1,81 @@
"""
Shared tail of the add-player flow (/addgamer and /addtoken).
The handlers in bot.py keep what differs between the two commands (Lichess
existence check vs. token -> profile lookup, reply texts, ConversationHandler
return values); everything after "we know the canonical username and the token"
is identical and lives here.
"""
import logging
import traceback
from dataclasses import dataclass
from typing import Optional
logger = logging.getLogger(__name__)
# Every newly linked player starts with hourly periodic notifications.
DEFAULT_PERIOD_MINUTES = 60
@dataclass
class LinkResult:
gamer_id: int
is_new_gamer: bool # the username was not in the global gamers table before
added: bool # False when the (user, gamer) pair already existed
async def link_player(bot, user_id: int, tg_user, username: str, token: Optional[str]) -> LinkResult:
"""
Add `username` to the global gamers table (if new), link it to `user_id`
(with `token`, may be None), give the pair the default period, start its
periodic task and notify the admin.
`bot` is the LichessBot (uses bot.db, bot.counters, bot.monitor,
bot.notifier); `tg_user` is update.effective_user (may be None).
When the returned `added` is False the pair already existed (callers check
first, so only a race gets here); `add_user_gamer` has then only refreshed
the token and nothing else was done — the caller decides what to reply.
"""
db = bot.db
is_new_gamer = not db.gamer_exists(username)
gamer_id = db.add_gamer(username)
added = db.add_user_gamer(user_id, gamer_id, token)
if not added:
return LinkResult(gamer_id=gamer_id, is_new_gamer=is_new_gamer, added=False)
# Set default period to 1 hour (60 minutes) for new gamer
db.set_user_gamer_period(user_id, gamer_id, DEFAULT_PERIOD_MINUTES)
bot.counters.increment('gamer_added')
logger.info(f"addgamer: player {username} added for user {user_id} (new_gamer={is_new_gamer})")
# If this is the first gamer for this user, make it active
user_gamers = db.get_user_gamers(user_id)
if len(user_gamers) == 1:
db.set_user_active_gamer(user_id, gamer_id)
# Start periodic task for this gamer (60 minutes period)
try:
gamer_data = {
'id': gamer_id,
'username': username,
'token': token,
'period_minutes': DEFAULT_PERIOD_MINUTES
}
await bot.monitor.start_periodic_task(gamer_data, user_id, DEFAULT_PERIOD_MINUTES)
logger.info(f"Started periodic task for {username} (user {user_id}) with period {DEFAULT_PERIOD_MINUTES} minutes")
except Exception as e:
logger.error(f"Failed to start periodic task for {username}: {e}")
logger.error(traceback.format_exc())
# Notify admin bot about player link (always notify)
try:
await bot.notifier.notify_new_player(
username, user_id, tg_user.username if tg_user else None, is_new_gamer
)
logger.info(f"Admin notification processed for player {username}")
except Exception as e:
logger.error(f"Failed to notify admin about new player link: {e}")
return LinkResult(gamer_id=gamer_id, is_new_gamer=is_new_gamer, added=True)

View file

@ -0,0 +1,489 @@
"""
Periodic activity monitoring: one asyncio task per (user, gamer) pair with a
period set, plus the daily message-counter reset.
Pacing: every games/puzzles request made here goes to the LOCAL stats service
(LICHESS_STATS_API_BASE_URL). The real limiter for the shared Lichess token is
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.
"""
import asyncio
import logging
import zlib
from datetime import datetime, timedelta
from typing import Dict, Any
from telegram.error import Forbidden
import config
from database import Database
from lichess_api import LichessAPI, InvalidTokenError
from formatters import StatsFormatter
from i18n import t
from message_counters import MessageCounters
from notifications import AdminNotifier
logger = logging.getLogger(__name__)
class PeriodicMonitor:
def __init__(self, db: Database, lichess_api: LichessAPI, counters: MessageCounters, notifier: AdminNotifier):
self.db = db
self.lichess_api = lichess_api
self.counters = counters
self.notifier = notifier
self.periodic_tasks = {} # Store periodic tasks
self.period_start_times = {} # Store start times for each gamer
self.application = None # telegram Application; set by bot.py once it is built
# 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)
async def start_periodic_task(self, gamer: Dict[str, Any], user_id: int, period_minutes: int):
"""Start periodic task for a gamer"""
task_key = f"{gamer['id']}_{user_id}"
# Cancel existing task if any
if task_key in self.periodic_tasks:
self.periodic_tasks[task_key].cancel()
logger.info(f"Cancelled existing periodic task for {gamer['username']}")
# Remove old start time
if task_key in self.period_start_times:
del self.period_start_times[task_key]
# Create new periodic task
task = asyncio.create_task(
self.periodic_check(gamer, user_id, period_minutes)
)
self.periodic_tasks[task_key] = task
async def stop_periodic_task(self, gamer_id: int, user_id: int):
"""Stop periodic task for a user-gamer pair."""
task_key = f"{gamer_id}_{user_id}"
task = self.periodic_tasks.pop(task_key, None)
if task:
task.cancel()
logger.info(f"Cancelled periodic task for gamer_id={gamer_id}, user_id={user_id}")
self.period_start_times.pop(task_key, None)
# Оповещать админ-бота о затяжной серии ошибок каждые ADMIN_NOTIFY_ERROR_THRESHOLD
# подряд идущих ошибок (~2 часа при капнутом бэкоффе в 300с на попытку)
ADMIN_NOTIFY_ERROR_THRESHOLD = 25
@staticmethod
def _checkpoint_jitter_seconds(user_id: int, gamer_id: int, period_minutes: int) -> float:
"""
Deterministic per-(user, gamer) jitter applied whenever a checkpoint gets
pinned to "now" (backlog collapse / first check). Without this, every pair
sharing the same period_minutes re-locks onto the exact same wall-clock
phase on every bot restart, causing them all to become "due" in the same
instant forever after. Stable across restarts (unlike Python's salted
hash()), and capped well below STALE_BACKLOG_THRESHOLD so it never
interacts with backlog-notification suppression.
"""
jitter_cap = min(period_minutes * 60 * config.PERIODIC_CHECKPOINT_JITTER_FRACTION,
config.PERIODIC_CHECKPOINT_JITTER_MAX_SECONDS)
if jitter_cap <= 0:
return 0.0
digest = zlib.crc32(f"{user_id}:{gamer_id}".encode())
return digest % jitter_cap
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}"
username = gamer['username']
checkpoint_ts = self.db.get_period_checkpoint(user_id, gamer['id'])
if checkpoint_ts is not None:
restored_time = datetime.fromtimestamp(checkpoint_ts)
self.period_start_times[task_key] = restored_time
logger.info(f"♻️ Restored periodic checkpoint for {username} (user {user_id}) at {restored_time}")
logger.info(f"🔄 Started periodic monitoring for {username} (user {user_id}) with {period_minutes} minute intervals")
consecutive_errors = 0
max_consecutive_errors = 5
is_first_check = True # Флаг для первой проверки
while True:
try:
# Проверяем, что период все еще установлен в БД
current_gamers = self.db.get_user_gamers(user_id)
gamer_still_exists = False
current_period = 0
for g in current_gamers:
if g['id'] == gamer['id']:
gamer_still_exists = True
current_period = g.get('period_minutes', 0)
break
# Если игрок удален или период отключен, прекращаем мониторинг
if not gamer_still_exists or current_period == 0:
logger.info(f"Periodic monitoring stopped for {gamer['username']}: gamer removed or period disabled")
if task_key in self.periodic_tasks:
del self.periodic_tasks[task_key]
if task_key in self.period_start_times:
del self.period_start_times[task_key]
break
# Обновляем период на случай, если он был изменен
if current_period != period_minutes:
logger.info(f"Period changed for {gamer['username']} from {period_minutes} to {current_period} minutes")
period_minutes = current_period
# Получаем сохраненное время последней проверки для расчета следующего периода
# Используем флаг is_first_check для первой проверки вместо проверки наличия ключа
last_check_time = self.period_start_times.get(task_key)
if is_first_check and checkpoint_ts is None:
last_check_time = None # Принудительно делаем первую проверку
is_first_check = False
if last_check_time:
# Уже была хотя бы одна проверка
# Рассчитываем, когда должен начаться следующий период
next_period_start = last_check_time + timedelta(minutes=period_minutes)
now = datetime.now()
# Если следующий период еще не наступил, ждем
if next_period_start > now:
wait_seconds = (next_period_start - now).total_seconds()
logger.debug(f"⏳ Waiting {wait_seconds:.1f} seconds until next period start ({next_period_start}) for {username}")
await asyncio.sleep(wait_seconds)
# Используем сохраненное время как начало периода
since_time = last_check_time
# Конец периода - это момент, когда должен был начаться следующий период
period_end_approx = next_period_start
logger.debug(f"📌 Using saved period: from {since_time} to {period_end_approx}")
else:
# Мы отстаём от расписания (бэклог): если догонять по period_minutes
# за раз, при большом отставании (недели простоя, много отслеживаемых
# игроков через один общий лимитер stats-сервиса) чекпоинт никогда не догонит
# текущее время — отставание только растёт. Вместо этого закрываем
# весь пропущенный промежуток одним запросом и сразу прыгаем к "сейчас".
# Джиттер (см. _checkpoint_jitter_seconds) не даёт всем парам с
# одинаковым period_minutes зафиксироваться на один и тот же момент.
since_time = last_check_time
jitter = self._checkpoint_jitter_seconds(user_id, gamer['id'], period_minutes)
period_end_approx = now - timedelta(seconds=jitter)
if period_end_approx - next_period_start > timedelta(minutes=period_minutes):
logger.warning(
f"⏰ {username} is behind schedule by "
f"{(now - next_period_start).total_seconds():.0f}s; "
f"collapsing backlog into one request from {since_time} to {period_end_approx}"
)
logger.info(f"📌 Using saved period: from {since_time} to {period_end_approx}")
else:
# Первая проверка - ждем period_minutes минут от момента запуска
logger.info(f"⏳ First check: waiting {period_minutes} minutes before first check for {username}")
await asyncio.sleep(period_minutes * 60)
# Получаем текущее время (с джиттером, см. _checkpoint_jitter_seconds)
jitter = self._checkpoint_jitter_seconds(user_id, gamer['id'], period_minutes)
period_end_approx = datetime.now() - timedelta(seconds=jitter)
# Начало периода - текущее время минус period_minutes
since_time = period_end_approx - timedelta(minutes=period_minutes)
logger.info(f"📌 First check: period from {since_time} to {period_end_approx}")
# A collapsed backlog spanning way more than a normal check window isn't
# "recent activity" anymore — dumping a multi-week, game-by-game report
# on the user reads as spam, not a periodic update. Catch the checkpoint
# up silently in that case instead of sending the full notification.
STALE_BACKLOG_THRESHOLD = timedelta(hours=2)
is_stale_backlog = (period_end_approx - since_time) > STALE_BACKLOG_THRESHOLD
if is_stale_backlog:
logger.warning(
f"⏭️ {username}: collapsed window ({since_time} to {period_end_approx}) "
f"exceeds {STALE_BACKLOG_THRESHOLD}; catching up checkpoint silently, "
f"no notification will be sent for this stale backlog"
)
since_timestamp = int(since_time.timestamp() * 1000)
# Используем приблизительное время как until_timestamp
# После получения ответа пересчитаем фактическое время
until_timestamp_approx = int(period_end_approx.timestamp() * 1000)
logger.info(f"🔍 Checking activity for {username} (user {user_id}): period from {since_time} to {period_end_approx} (approx, last {period_minutes} minutes)")
logger.debug(f"📅 Unix timestamps: since={since_timestamp}, until_approx={until_timestamp_approx}")
# Делаем запросы к stats-сервису с обработкой ошибок
games_data = None
puzzles_data = None
try:
# Запрос к локальному stats-сервису; очередь и пейсинг общего
# Lichess-токена — на его стороне (SharedTokenGate), здесь только
# ограничиваем число одновременно открытых соединений.
logger.debug(f"📥 Requesting games for {gamer['username']}")
async with self._request_slots:
games_data = await self.lichess_api.get_games_period(
gamer['username'], since_timestamp, until_timestamp_approx,
include_games=True
)
if games_data is None:
raise RuntimeError("Games period API returned no data")
# Фиксируем фактическое время получения ответа
request_end_time = datetime.now()
logger.debug(f"✅ Games API response received for {gamer['username']} at {request_end_time}")
except Exception as e:
logger.error(f"❌ Error getting games data for {gamer['username']}: {e}")
consecutive_errors += 1
backoff_seconds = min(300, 60 * consecutive_errors)
if consecutive_errors >= max_consecutive_errors:
logger.error(f"⚠️ {consecutive_errors} consecutive errors for {gamer['username']}; still retrying the same period (backoff {backoff_seconds}s)")
else:
logger.warning(f"⚠️ Games data unavailable for {gamer['username']}; retrying the same period in {backoff_seconds}s")
if consecutive_errors == self.ADMIN_NOTIFY_ERROR_THRESHOLD or (
consecutive_errors > self.ADMIN_NOTIFY_ERROR_THRESHOLD
and consecutive_errors % self.ADMIN_NOTIFY_ERROR_THRESHOLD == 0
):
await self.notifier.notify_periodic_check_failing(gamer['username'], user_id, consecutive_errors)
await asyncio.sleep(backoff_seconds)
continue
if gamer.get('token'):
# Транзитные ошибки получения пазлов обрабатываются так же, как ошибки игр:
# исключение всплывает во внешний обработчик, чекпоинт не продвигается,
# то же окно ретраится на следующей итерации (не считаем "пазлов не было").
# InvalidTokenError — отдельный случай: Lichess отклонил токен насовсем
# (401), ретраить бессмысленно — это раньше приводило к вечному циклу
# ретраев без продвижения чекпоинта (см. историю с Dor1zz). Вместо этого
# отключаем пазлы для этой пары и продолжаем отслеживать партии как обычно.
logger.debug(f"📥 Requesting puzzles for {gamer['username']}")
try:
async with self._request_slots:
puzzles_data = await self.lichess_api.get_puzzles_period(
gamer['token'], since_timestamp, until_timestamp_approx, 150
)
except InvalidTokenError:
logger.warning(f"🔑 Token rejected by Lichess for {gamer['username']} (user {user_id}); disabling puzzle tracking for this pair")
self.db.clear_user_gamer_token(user_id, gamer['id'])
gamer['token'] = None
puzzles_data = None
try:
user_lang = self.db.get_user_language(user_id)
await self.application.bot.send_message(
chat_id=user_id,
text=t('token_rejected_notice', user_lang, username=gamer['username'])
)
except Exception as notify_err:
logger.error(f"Failed to notify user {user_id} about rejected token: {notify_err}")
else:
if puzzles_data is None:
raise RuntimeError("Puzzles period API returned no data")
# Обновляем фактическое время после получения ответа по пазлам
request_end_time = datetime.now()
logger.debug(f"✅ Puzzles API response received for {gamer['username']} at {request_end_time}")
# Сбрасываем счетчик ошибок при успешном запросе
consecutive_errors = 0
# Проверяем наличие реальной активности
has_games = False
total_games = 0
if games_data:
# Логируем структуру ответа для отладки
logger.debug(f"📊 Games data structure for {username}: {games_data}")
# Проверяем games_count на верхнем уровне (приоритет)
top_level_count = games_data.get('games_count', 0)
logger.debug(f"🔍 Top-level games_count: {top_level_count}")
if top_level_count > 0:
total_games = top_level_count
has_games = True
logger.debug(f"✅ Found {total_games} games via games_count field")
else:
# Также проверяем data.total.games_played
games_data_dict = games_data.get('data')
if games_data_dict:
data_total = games_data_dict.get('total', {})
total_games_played = data_total.get('games_played', 0) if data_total else 0
else:
total_games_played = 0
logger.debug(f"🔍 data.total.games_played: {total_games_played}")
if total_games_played > 0:
total_games = total_games_played
has_games = True
logger.debug(f"✅ Found {total_games} games via data.total.games_played field")
else:
logger.debug(f"⚠️ No games found: games_count={top_level_count}, data.total.games_played={total_games_played}")
else:
logger.warning(f"⚠️ No games_data returned for {username}")
has_puzzles = False
total_puzzles = 0
if puzzles_data:
logger.debug(f"📊 Puzzles data structure for {username}: {puzzles_data}")
# Проверяем puzzles_in_period на верхнем уровне (приоритет)
if puzzles_data.get('puzzles_in_period', 0) > 0:
total_puzzles = puzzles_data.get('puzzles_in_period', 0)
has_puzzles = True
logger.debug(f"✅ Found {total_puzzles} puzzles via puzzles_in_period field")
# Также проверяем data.total_attempts
elif puzzles_data.get('data') and puzzles_data.get('data', {}).get('total_attempts', 0) > 0:
total_puzzles = puzzles_data.get('data', {}).get('total_attempts', 0)
has_puzzles = True
logger.debug(f"✅ Found {total_puzzles} puzzles via data.total_attempts field")
logger.debug(f"🔍 Activity check result for {username}: has_games={has_games} (total={total_games}), has_puzzles={has_puzzles} (total={total_puzzles})")
# Отправляем уведомление только если есть реальная активность и это не
# молчаливый догон устаревшего бэклога (is_stale_backlog, см. выше).
# Ошибки форматирования/отправки НЕ перехватываются здесь: они должны
# всплыть во внешний обработчик, чтобы чекпоинт не продвинулся и уже
# обнаруженная активность была отправлена повторно на следующей попытке,
# а не потеряна молча.
if (has_games or has_puzzles) and not is_stale_backlog:
logger.info(f"📊 Activity detected for {gamer['username']}, preparing notification...")
user_lang = self.db.get_user_language(user_id)
# Label the notification with the actual queried window, not the
# configured period: after a backlog collapse (see above) they can
# differ by days/weeks, and showing "for 15 minutes" on activity
# that's actually from weeks ago is misleading.
actual_span_minutes = max(1, round((period_end_approx - since_time).total_seconds() / 60))
notification = StatsFormatter.format_period_notification(
gamer['username'], games_data, puzzles_data, actual_span_minutes, lang=user_lang
)
if not self.application:
raise RuntimeError(f"Application not initialized, cannot send notification for {gamer['username']} to user {user_id}")
# Forbidden (user blocked the bot) is permanent, not worth retrying:
# without this, consecutive_errors gets reset to 0 above right before
# this call succeeds/fails, so the outer handler's backoff never grows
# past 60s and this pair retries forever, wasting queue capacity that
# other users' real checks need.
try:
await self.application.bot.send_message(
chat_id=user_id,
text=notification,
parse_mode='Markdown'
)
except Forbidden:
logger.warning(f"🚫 User {user_id} blocked the bot; stopping periodic monitoring for {gamer['username']}")
self.db.set_user_gamer_period(user_id, gamer['id'], 0)
if task_key in self.periodic_tasks:
del self.periodic_tasks[task_key]
if task_key in self.period_start_times:
del self.period_start_times[task_key]
return
logger.info(f"✅ Sent periodic notification for {gamer['username']} to user {user_id}")
# Increment periodic notification counter
self.counters.increment('periodic_notification')
elif is_stale_backlog and (has_games or has_puzzles):
logger.info(f"⏭️ Suppressed stale backlog notification for {gamer['username']} (had activity, but window too old)")
else:
logger.debug(f"⏭️ No activity found for {gamer['username']} in the last {period_minutes} minutes")
# Обновляем время начала следующего периода на ПЛАНИРУЕМОЕ время окончания текущего периода
# (period_end_approx), а не на фактическое время завершения запроса (request_end_time).
# Это гарантирует непрерывность периодов без пропусков:
# - Проверяем период A-B
# - Следующая проверка будет периода B-C
# - Без пропусков между A-B и B-C
#
# Использование request_end_time приведет к пропуску диапазона между period_end_approx и request_end_time
#
# 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()))
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()
if delay > 0:
logger.debug(f"⏱️ Request completed with {delay:.1f}s delay after planned period end")
except asyncio.CancelledError:
logger.info(f"Periodic check cancelled for {gamer['username']}")
break
except Exception as e:
consecutive_errors += 1
logger.error(f"Error in periodic check for {gamer['username']}: {e}")
import traceback
logger.error(f"Full traceback: {traceback.format_exc()}")
# Не убиваем задачу навсегда: ретраим то же окно с растущим бэкоффом
# (капается на 300с), пока Lichess/Telegram не восстановятся.
backoff_seconds = min(300, 60 * consecutive_errors)
if consecutive_errors >= max_consecutive_errors:
logger.error(f"⚠️ {consecutive_errors} consecutive errors for {gamer['username']}; still retrying the same period (backoff {backoff_seconds}s)")
if consecutive_errors == self.ADMIN_NOTIFY_ERROR_THRESHOLD or (
consecutive_errors > self.ADMIN_NOTIFY_ERROR_THRESHOLD
and consecutive_errors % self.ADMIN_NOTIFY_ERROR_THRESHOLD == 0
):
await self.notifier.notify_periodic_check_failing(gamer['username'], user_id, consecutive_errors)
await asyncio.sleep(backoff_seconds)
continue
async def start_existing_periodic_tasks(self):
"""Start periodic tasks for all user-gamer pairs that have periods set"""
try:
gamers_with_periods = self.db.get_all_gamers_with_periods()
# Get statistics
counts = self.db.get_counts()
total_users, total_gamers = counts['users'], counts['gamers']
logger.info(f"📊 Statistics: {total_users} users, {total_gamers} tracked gamers")
logger.info(f"🔔 Found {len(gamers_with_periods)} user-gamer pairs with periodic notifications enabled")
if len(gamers_with_periods) == 0:
logger.warning("⚠️ No periodic notifications configured! Users need to set periods using /setperiod")
active_gamers = [g for g in gamers_with_periods if g['period_minutes'] > 0]
# Stagger task creation across a short startup window instead of firing all
# ~N tasks' first (blocking) sqlite checkpoint read in the same event loop
# tick. Small and one-off — the real anti-lockstep fix is the per-pair
# checkpoint jitter in periodic_check, this just smooths process boot.
stagger_step = config.PERIODIC_STARTUP_STAGGER_MAX_SECONDS / max(1, len(active_gamers))
for gamer in active_gamers:
user_id = gamer['user_id']
username = gamer['username']
period = gamer['period_minutes']
# Start periodic task with user_id and gamer
await self.start_periodic_task(gamer, user_id, period)
logger.info(f"✅ Started periodic task for {username} (user {user_id}) with period {period} minutes")
if stagger_step > 0:
await asyncio.sleep(stagger_step)
logger.info(f"✅ All periodic tasks started. Total: {len(active_gamers)}")
# Start daily counter reset task
asyncio.create_task(self.daily_counter_reset_task())
logger.info("✅ Started daily counter reset task")
except Exception as e:
logger.error(f"❌ Error starting existing periodic tasks: {e}")
import traceback
logger.error(traceback.format_exc())
async def daily_counter_reset_task(self):
"""Background task to reset daily counters at midnight"""
while True:
try:
# Calculate seconds until next midnight
now = datetime.now()
next_midnight = (now + timedelta(days=1)).replace(hour=0, minute=0, second=0, microsecond=0)
seconds_until_midnight = (next_midnight - now).total_seconds()
logger.info(f"Daily counter reset task: waiting {seconds_until_midnight} seconds until next midnight")
await asyncio.sleep(seconds_until_midnight)
# Reset daily counters
self.counters._reset_daily_counters_if_needed()
logger.info("Daily counters reset at midnight")
except asyncio.CancelledError:
break
except Exception as e:
logger.error(f"Error in daily counter reset task: {e}")
import traceback
logger.error(traceback.format_exc())
# Wait 1 hour before retrying
await asyncio.sleep(3600)

View file

@ -1,177 +0,0 @@
"""
Request Queue for managing API requests with rate limiting
Paces how fast we dispatch requests to our own local stats API
(http://localhost:8002), and caps how many of those requests may be in
flight at once. This does NOT protect against Lichess's real rate limiter —
that protection already lives downstream, in LichessWebServices/rate_limiter.py
(0.2s min delay, single shared instance, applied before every actual
lichess.org call, shared by ALL callers of stats_service — not just this
bot). These numbers only govern bot -> local-service traffic.
"""
import asyncio
import logging
from typing import Callable, Any, Optional, Set
from datetime import datetime
import config
logger = logging.getLogger(__name__)
class RequestQueue:
"""
Queue for managing requests to our local stats API.
Dispatch is paced by a hard floor (min_dispatch_interval): two requests
can never be dispatched closer together than that, enforced by a lock in
the processor loop, independent of how long any individual request takes
to complete. Actual execution is capped separately by max_concurrent via
a semaphore, so a slow request can't stall the whole queue behind it.
"""
def __init__(self, min_dispatch_interval: float, max_concurrent: int):
"""
Args:
min_dispatch_interval: Minimum seconds between successive dispatches
max_concurrent: Maximum requests in flight at once (set to 1 to
fully serialize execution again, e.g. as a rollback lever)
"""
self.min_dispatch_interval = min_dispatch_interval
self.max_concurrent = max_concurrent
self.queue = asyncio.Queue()
self.is_processing = False
self.last_dispatch_time: Optional[float] = None
self.lock = asyncio.Lock()
self.semaphore = asyncio.Semaphore(max_concurrent)
self._processor_task: Optional[asyncio.Task] = None
self._in_flight: Set[asyncio.Task] = set()
async def add_request(self, request_func: Callable, *args, **kwargs) -> Any:
"""
Add a request to the queue and wait for its result.
Args:
request_func: Async function to call
*args: Positional arguments for the function
**kwargs: Keyword arguments for the function
Returns:
Result of the request function
"""
future = asyncio.Future()
await self.queue.put({
'func': request_func,
'args': args,
'kwargs': kwargs,
'future': future
})
if not self.is_processing:
self._start_processor()
return await future
def _start_processor(self):
"""Start the queue processor task"""
if self._processor_task is None or self._processor_task.done():
self.is_processing = True
self._processor_task = asyncio.create_task(self._process_queue())
logger.info(
f"🚀 Started request queue processor "
f"(dispatch interval: {self.min_dispatch_interval}s, "
f"max concurrent: {self.max_concurrent})"
)
async def _process_queue(self):
"""Dequeue requests and dispatch them at a paced rate, without waiting for completion"""
logger.info("📋 Request queue processor started")
while True:
try:
request_item = await self.queue.get()
# Hard floor: never dispatch two requests closer than
# min_dispatch_interval apart, regardless of how long the
# previous one takes to finish (that's what self.semaphore
# bounds separately, not this gate).
await self._wait_for_dispatch_slot()
task = asyncio.create_task(self._execute(request_item))
self._in_flight.add(task)
task.add_done_callback(self._in_flight.discard)
self.queue.task_done()
except asyncio.CancelledError:
logger.info("🛑 Request queue processor cancelled")
break
except Exception as e:
logger.error(f"❌ Error in request queue processor: {e}")
import traceback
logger.error(traceback.format_exc())
await asyncio.sleep(1)
async def _execute(self, request_item: dict):
"""Run one queued request, bounded by the concurrency semaphore"""
func = request_item['func']
args = request_item['args']
kwargs = request_item['kwargs']
future = request_item['future']
async with self.semaphore:
try:
logger.debug(f"🔄 Executing request: {func.__name__}")
result = await func(*args, **kwargs)
if not future.done():
future.set_result(result)
logger.debug(f"✅ Request completed: {func.__name__}")
except Exception as e:
logger.error(f"❌ Request failed: {func.__name__}: {e}")
if not future.done():
future.set_exception(e)
async def _wait_for_dispatch_slot(self):
"""Wait if necessary to maintain minimum delay between dispatches"""
async with self.lock:
now = datetime.now().timestamp()
if self.last_dispatch_time is not None:
elapsed = now - self.last_dispatch_time
if elapsed < self.min_dispatch_interval:
wait_time = self.min_dispatch_interval - elapsed
logger.debug(f"⏳ Dispatch pacing: waiting {wait_time:.2f} seconds")
await asyncio.sleep(wait_time)
now = datetime.now().timestamp()
self.last_dispatch_time = now
async def stop(self):
"""Stop the queue processor and any in-flight requests"""
if self._processor_task and not self._processor_task.done():
self._processor_task.cancel()
try:
await self._processor_task
except asyncio.CancelledError:
pass
for task in list(self._in_flight):
task.cancel()
if self._in_flight:
await asyncio.gather(*self._in_flight, return_exceptions=True)
self.is_processing = False
logger.info("🛑 Request queue processor stopped")
# Global request queue instance
_request_queue: Optional[RequestQueue] = None
def get_request_queue() -> RequestQueue:
"""Get the global request queue instance"""
global _request_queue
if _request_queue is None:
_request_queue = RequestQueue(
min_dispatch_interval=config.LICHESS_REQUEST_QUEUE_MIN_DISPATCH_INTERVAL,
max_concurrent=config.LICHESS_REQUEST_QUEUE_MAX_CONCURRENT,
)
return _request_queue

View file

@ -115,7 +115,7 @@ Telegram бот для управления отслеживанием игро
- Каждый пользователь имеет свой набор игроков
- Версионность бота (отображается в команде /support)
- **Многоязычная поддержка**: Русский и английский языки с автоматическим определением и ручным выбором через `/set_lang`
- **Очередь запросов**: Автоматическая задержка 7 секунд между запросами к Lichess API для периодических уведомлений
- **Пейсинг запросов к Lichess**: единая очередь общего токена в stats-сервисе (`LichessWebServices/rate_limiter.py`, SharedTokenGate: 6 с между запросами, интерактивные команды приоритетнее периодических проверок); бот сам запросы к сервису не притормаживает, только ограничивает число одновременных периодических запросов (`PERIODIC_MAX_CONCURRENT_REQUESTS`)
**Команды:**
- `/start` - начало работы с ботом и добавление первого игрока

310
docs/CURRENT_STATE.md Normal file
View file

@ -0,0 +1,310 @@
# LichessStatTgWeb — текущее состояние системы
> Описание соответствует коммиту **6355cd9** (`fix log bloat, token leak, silent onboarding gaps, closed-account adds, case-duplicate gamers`, 2026-10-20). Все ссылки вида `файл:строка` относятся к этому коммиту (`git show 6355cd9:<path>`), а не к рабочему дереву: параллельно идёт рефакторинг `bot.py` (вынос `periodic_check`, уведомлений админу и сценария добавления игрока в `periodic.py` / `notifications.py` / `onboarding.py`, удаление `request_queue.py`), после которого номера строк и имена модулей изменятся.
>
> Прод-цифры в разделе 8 — выгрузка оркестратора от 2026-10-20; на прод при подготовке документа я не ходил. Всё остальное — из кода и истории git.
---
## 1. Назначение и компоненты
Система отслеживает активность игроков Lichess и присылает её пользователям Telegram: статистику за день/вчера/неделю по запросу и периодические уведомления о сыгранных партиях (и решённых пазлах, если пользователь дал свой Lichess-токен). Версия бота `1.4.1` (`LichessClientTG_bot/version.py:7`).
### 1.1. Три контейнера
| Контейнер | Код | Стек | Роль |
|---|---|---|---|
| `lichess-telegram-bot` | `LichessClientTG_bot/bot.py` (2040 строк) | python-telegram-bot 20.7, aiohttp 3.9.1, long polling (`bot.py:2027-2032`, `poll_interval=1.0`, `timeout=30`, `drop_pending_updates=False`, `allowed_updates=["message","callback_query"]`, `config.py:63-69`) | Пользовательский бот + все периодические проверки |
| `lichess-admin-bot` | `LichessClientTG_bot/admin_bot.py` (545 строк), `Dockerfile.admin` | python-telegram-bot 20.7, отдельный процесс, тот же SQLite-файл | Админ-панель: `/start` (регистрирует admin chat id), `/status`, `/system_mes` (рассылка всем), `/sendusers0` (рассылка пользователям без игроков) — `admin_bot.py:438-473` |
| `lichess-api` | `LichessWebServices/` (`main.py`, `stats_service.py`, `lichess_client.py`, `rate_limiter.py`, `models.py`) | FastAPI 0.104.1, uvicorn, httpx 0.25.2; контейнерный порт 8000 → хост **8002** | Stats-сервис: агрегирует ответы lichess.org, единственный владелец `SharedTokenGate` |
Оба бота работают в `network_mode: "host"` (`docker-compose.prod.yml:34,60`), поэтому бот ходит в stats-сервис по `http://localhost:8002` (`config.py:21`). Healthcheck контейнера бота проверяет не сам бот, а API на 8002 (`docker-compose.prod.yml:44`).
### 1.2. Кто с кем общается
```
Telegram ──long polling──> lichess-telegram-bot ──┬──> http://localhost:8002 (lichess-api) ──SharedTokenGate──> https://lichess.org/api
│ /stats/{u}/today|yesterday|week → GET user/{u}/activity (LICHESS_APP_TOKEN)
│ /games/{u}/period → GET games/user/{u} (LICHESS_APP_TOKEN)
│ /puzzle/period (Bearer user-token)→ GET puzzle/activity (токен пользователя, без gate)
│
└──> https://lichess.org/api напрямую (минуя stats-сервис и gate):
check_user_exists / get_user_ratings → GET user/{u} (анонимно)
get_user_profile → GET account (токен пользователя)
lichess-admin-bot ──long polling──> Telegram (отдельный бот-токен); бот пользователей шлёт админу через HTTP POST api.telegram.org/bot<ADMIN_TOKEN>/sendMessage
```
Прямые вызовы бота к lichess.org: `LichessClientTG_bot/lichess_api.py:21-42` (`get_user_profile`), `:173-205` (`check_user_exists`), `:207-222` (`get_user_ratings`). Вызовы через stats-сервис: `:44-171`. Весь трафик в stats-сервис, кроме `/puzzle/period`, не несёт никаких токенов; сервис сам подставляет `LICHESS_APP_TOKEN` из окружения (`LichessWebServices/lichess_client.py:58-60,85,166-167`).
### 1.3. Деплой
`.forgejo/workflows/deploy.yml`: push в `main` → раннер Forgejo (`runs-on: shell`) клонирует репозиторий, копирует `.env.example` в `.env` только для сборки (`:22-23`), собирает три образа `docker-compose build`, пушит их в реестр `192.168.8.174:3000/vrubel/{lichess-api,lichess-bot,lichess-admin}:latest`, затем `docker save … | ssh root@<prod> docker load` (`:37-43`), копирует `docker-compose.prod.yml` на прод как `~/services/LichessStatTgWeb/docker-compose.yml` и делает `docker compose up -d --remove-orphans` (`:45-50`). Тестов в пайплайне нет; откат — только пересборкой предыдущего коммита.
Разница dev/prod compose: dev (`docker-compose.yml`) монтирует исходники внутрь контейнеров (`./LichessClientTG_bot:/app`, `./LichessWebServices:/app`) и БД из `./LichessClientTG_bot/data`; prod (`docker-compose.prod.yml`) использует готовые образы и БД из `./data` → внутри `/app/data/lichess_bot.db` (`config.py:43-57`). Локальный запуск — `./start.sh` (делает бэкап БД в `backups/`, `compose build`, `up -d`).
### 1.4. `.env`
Один файл на корень проекта (`env_file: .env` у всех трёх сервисов); на проде — `~/services/LichessStatTgWeb/.env`, в репозиторий не попадает (`.gitignore`). Переменные (значения не приводятся):
| Переменная | Кем читается | Назначение |
|---|---|---|
| `COMPOSE_PROJECT_NAME` | compose | имя проекта `lichess` |
| `TELEGRAM_BOT_TOKEN` | bot, admin_bot (рассылки) | токен пользовательского бота |
| `ADMINPANEL_TELEGRAM_BOT_TOKEN` | admin_bot, bot (уведомления админу) | токен админ-бота |
| `LICHESS_APP_TOKEN` | lichess-api | personal token для авторизации `games/user` и `user/activity` (анонимные запросы Lichess отдаёт 404) |
| `LOG_LEVEL` (опц., INFO) | bot, admin_bot | уровень логирования; **stats-сервис его не читает** (`LichessWebServices/main.py:28` — всегда INFO) |
| `TTS_URL` (опц.) | admin_bot | адрес TTS-анонсера в домашней сети; на проде не задан |
| `DATABASE_PATH` (опц.) | bot, admin_bot | переопределение пути к БД (`config.py:45-47`) |
Замечание: в закоммиченном `.env.example` лежат реальные на вид тестовые токены двух ботов (`.env.example:5-6`). Если это боевые тестовые токены — они публичны в истории репозитория.
---
## 2. Схема БД (`LichessClientTG_bot/database.py`)
SQLite, один файл, без ORM, каждая операция — отдельный `sqlite3.connect` (`database.py` целиком). WAL/таймауты не настраиваются.
### 2.1. Таблицы
**`telegram_users`** (`database.py:20-46`) — пользователи Telegram.
| Поле | Смысл |
|---|---|
| `user_id` PK | Telegram id |
| `username`, `first_name`, `last_name` | профиль Telegram, обновляются при каждом контакте |
| `language_code` | язык клиента Telegram, обновляется каждый раз |
| `bot_language` (`'en'`/`'ru'`) | язык бота; при создании `'ru'` если `language_code` начинается с `ru`, иначе `'en'` (`:244`); далее меняется только через `/set_lang` |
| `created_at` | дата регистрации (первый `/start` или первое любое сообщение — см. `get_user_language_from_update`, `bot.py:193-207`) |
**`gamers`** (`database.py:49-56`) — игроки Lichess, одна строка на ник.
| Поле | Смысл |
|---|---|
| `id` PK | |
| `username` UNIQUE (регистрозависимый) + индекс `idx_gamers_username_nocase` на `lower(username)` (`:128-132`) | каноническое написание ника из ответа Lichess (`bot.py:661-662`) |
| `token` | **legacy**, больше не используется: токены мигрированы в `user_gamers` (`_migrate_tokens_from_gamers`, `:190-225`) |
Строка удаляется, когда последний пользователь отвязал игрока (`remove_user_gamer`, `:446-470`).
**`user_gamers`** (`database.py:59-87`) — связь «пользователь → игрок», `UNIQUE(user_id, gamer_id)`. Это основная рабочая сущность: именно на пары заводятся периодические задачи.
| Поле | Смысл |
|---|---|
| `token` | Lichess-токен пользователя (из `/addtoken`), нужен только для пазлов; обнуляется, если Lichess ответил 401 (`clear_user_gamer_token`, `:403-411`) |
| `is_active` | «активный игрок» пользователя. Выставляется при добавлении первого игрока (`bot.py:705-707`, `:569-571`) и кнопкой `select_<id>` (`bot.py:860-889`). Читается только в `/delgamer` — как значок 🟢/⚪ в списке и для выбора текста после удаления (`bot.py:912`, `:992`); на статистику и проверки не влияет: `/today` и др. обходят всех игроков пользователя. Кнопка `select_<id>` нигде не рисуется (`/getgamers` отдаёт таблицу без клавиатуры, `bot.py:840-845`), т.е. сменить «активного» игрока пользователь не может |
| `period_minutes` | период проверок в минутах, `0` = выключено. Ставится `60` при добавлении игрока (`bot.py:700`, `:565`), меняется через `/setperiod` из `PERIOD_OPTIONS = [0,15,30,60,120,180,360,720,1440]` (`config.py:60`); ставится `0`, если пользователь заблокировал бота (`bot.py:1848`) |
| `last_period_end_ts` | чекпоинт периодической проверки, unix-секунды: **плановый** конец последнего обработанного окна. Следующее окно начинается ровно с него (`bot.py:1872-1873`). `NULL` = проверок ещё не было; очищается при выключении периода (`bot.py:1401`) |
**`admin_settings`** (`:90-96`) — key/value; единственный ключ `admin_chat_id`, записывается командой `/start` админ-бота (`admin_bot.py:417-422`). Без него ни одно уведомление админу не уходит.
**`message_counters`** (`:99-116`) — счётчики `command → total_count, today_count, last_reset_date`. Предсозданные ключи: `start, addgamer, addtoken, getgamers, delgamer, today, yesterday, week, setperiod, lang, resetlang, periodic_notification, gamer_added`; `support` и `last_year_1000` создаются при первом инкременте (`message_counters.py:74-95`). `today_count` сбрасывается ленивым сравнением даты при каждом инкременте/чтении (`:35-72`) и отдельной задачей в полночь (`bot.py:261-284`). Показываются в `/status` админ-бота (`admin_bot.py:199-213`). Смысл: `addgamer` = нажатия кнопок «добавить»/«как узнать ник» (`bot.py:426,500`), `gamer_added` = успешные добавления (`bot.py:701`, `:566`), `periodic_notification` = отправленные фоновые уведомления (`bot.py:1856`).
### 2.2. Миграции при старте (`Database.init_database`, `:13-134`)
Выполняются при каждом старте обоих ботов (оба создают `Database()`): `CREATE TABLE IF NOT EXISTS` × 5, `ALTER TABLE ADD COLUMN` в try/except для `language_code`, `bot_language`, `user_gamers.token`, `last_period_end_ts`; инициализация счётчиков; `_migrate_tokens_from_gamers` (одноразовая, пропускается если в `user_gamers` уже есть токены); **`_merge_case_duplicate_gamers`** (`:136-188`) — группирует `gamers` по `lower(username)`, оставляет строку с наименьшим `id`, перевешивает на неё `user_gamers` дублей (если тот же пользователь отслеживал обе формы — сливает в одну связь, не теряя токен/период/чекпоинт), удаляет дубли; затем создаёт `idx_gamers_username_nocase`, который делает новые регистровые дубли невозможными. На проде на момент коммита слияние ещё не применялось (503 → ожидаемо 493 игроков, см. раздел 8).
Отдельно: `bot_persistence.pickle` рядом с БД (`bot.py:1991-1992`) — `PicklePersistence` python-telegram-bot, хранит `user_data` (флаг `awaiting_addgamer_username`), чтобы незавершённый ввод ника пережил рестарт.
---
## 3. Пользовательские сценарии (хендлеры `bot.py`)
Регистрация хендлеров — `bot.py:1924-1979`. Перед всеми ними в группе `-1` стоит `TypeHandler(Update, log_incoming_update)` (`:1929`, `:1902-1917`) — одна INFO-строка на каждый апдейт. Любой хендлер первым делом вызывает `get_user_language_from_update` (`:193-207`), который делает `add_or_get_telegram_user` — т.е. **любое** сообщение регистрирует пользователя в `telegram_users`, не только `/start`.
Колонка «наружу» — HTTP-запросы за пределы бота (к stats-сервису или lichess.org), не считая Telegram API.
| Команда / событие | Хендлер | Что происходит | Наружу |
|---|---|---|---|
| `/start` | `start_and_addgamer` (`:334-351`) → `start` (`:286-326`) → `addgamer_start` (`:353-394`) | очистка `user_data`; регистрация пользователя; если новый — уведомление админу (`admin_bot.notify_new_user` или fallback `_notify_admin_new_user`); `start_message`; счётчик `start`; затем сразу меню добавления: ставит `user_data['awaiting_addgamer_username']=True` и шлёт две inline-кнопки `addgamer_add` / `addgamer_how` | 0 к Lichess; 1 POST к api.telegram.org если новый пользователь |
| `/addgamer` | `addgamer_start` | то же меню, флаг ожидания | 0 |
| кнопка `addgamer_add` | `addgamer_show_prompt` (`:396-426`) | `user_data.clear()`, флаг `True`, текст-подсказка «введите ник», счётчик `addgamer` | 0 |
| кнопка `addgamer_how` | `addgamer_show_help` (`:428-508`) | отправляет `helpRU.jpeg`/`helpEN.jpeg` из папки бота, затем ту же подсказку, флаг `True`, счётчик `addgamer` | 0 |
| любой текст не-команда | `handle_username` (`:614-744`) | если флага нет → ответ `text_not_expected` (`:620-624`). Иначе: `check_user_exists` → `None` = «Lichess временно недоступен» (`:637-644`), `False` = «не найден» (`:645-651`), `disabled` = «аккаунт закрыт» (`:652-660`); берётся каноническое написание ника; если пользователь уже отслеживает — «уже добавлен»; иначе `add_gamer` + `add_user_gamer(token=None)` + `period_minutes=60`, счётчик `gamer_added`, при первом игроке `is_active`, **немедленный `start_periodic_task(…, 60)`**, уведомление админу `_notify_admin_new_player`, ответ `gamer_added`, флаг `False`. При ошибках (не найден / уже есть / недоступен) флаг **остаётся** `True` — пользователь может сразу ввести другой ник | 1 GET `lichess.org/api/user/{ник}` **анонимно, напрямую** (`lichess_api.py:185-205`) |
| `/addtoken` | `ConversationHandler` (`:1933-1944`): `addtoken_start` (`:510-519`) → `handle_token` (`:521-612`) | `user_data.clear()` (сбрасывает ожидание ника), просит токен; по тексту: `get_user_profile(token)` → ник из `/api/account`; если игрок уже у пользователя — обновляет токен (`add_user_gamer` с `token`, `:541`); иначе полностью дублирует сценарий добавления (`:552-599`): `add_gamer`, `add_user_gamer(token)`, период 60, `gamer_added`, `is_active`, `start_periodic_task`, уведомление админу. Состояние `WAITING_FOR_TOKEN` держится до валидного токена или `/cancel`. Проверки `disabled` нет; сравнение ников здесь регистрозависимое (`:536`, `:557`) | 1 GET `lichess.org/api/account` с токеном пользователя, напрямую |
| `/getgamers` | `getgamers` (`:746-858`) | для каждого игрока запрашивает рейтинги, пауза 0.5 с между запросами (`:780-781`), рисует таблицу bullet/blitz/rapid + период; клавиатуры нет | N × GET `lichess.org/api/user/{ник}` анонимно, напрямую |
| `/delgamer` | `delgamer` (`:891-966`) → кнопка `delete_<id>` → `handle_delete_gamer` (`:968-1020`) | то же, что `/getgamers`, но с кнопками удаления; удаление снимает связь (и игрока, если его больше никто не отслеживает); запущенная периодическая задача сама завершится на следующей итерации (`:1605-1611`) | N × GET `lichess.org/api/user/{ник}` |
| `/today`, `/yesterday`, `/week` | `today`/`yesterday`/`week` → `get_stats` (`:1022-1172`) | для **каждого** игрока пользователя последовательно: сообщение «обрабатываю…», `GET /stats/{ник}/{period}` в stats-сервис; если есть партии или пазлы — дополнительный `GET /games/{ник}/period?priority=interactive&include_games=…` ради accuracy и построчной таблицы (`:1119-1150`), затем ответ; пауза 1 с между игроками. Если активности ни у кого — `no_activity` | на игрока: 1 (`user/activity`) + 0..1 (`games/user`) запроса к lichess.org через stats-сервис и `SharedTokenGate` с приоритетом `interactive`. Для пользователя с 60 игроками — до 120 запросов по 6 с минимум = 6–12 минут на команду |
| `/lastYear_or_1000games` | `last_year_or_1000games` (`:1193-1256`) | на каждого игрока `GET /games/{ник}/period` за 365 дней (Lichess отдаёт до 1000 партий, `lichess_client.py:157`), пауза 3 с | N × `games/user` через gate с приоритетом **`background`** (параметр не передан, `:1226`) — т.е. команда стоит в очереди позади фоновых проверок |
| `/setperiod` | `setperiod` (`:1258-1300`) → `select_gamer_period_<id>` → `select_gamer_for_period` (`:1302-1359`) → `period_<gid>_<min>` → `select_period` (`:1361-1412`) | две клавиатуры; `set_user_gamer_period`; при `0` — `clear_period_checkpoint` + `stop_periodic_task`; иначе `start_periodic_task` (старая задача отменяется, `:1539-1541`) | 0 |
| `/set_lang` | `set_lang` (`:1414-1437`) → `lang_en`/`lang_ru` → `handle_language_selection` (`:1439-1468`) | пишет `bot_language` | 0 |
| `/profile` | `profile` (`:1470-1498`) → `profile_<id>` → `handle_profile_selection` (`:1500-1532`) | ссылка `https://lichess.org/@/{ник}` | 0 |
| `/support` | `support` (`:1186-1191`) | контакт + версия, счётчик `support` | 0 |
| `/help` | `help_command` (`:328-332`) | текст справки | 0 |
| `/test_admin_notify` | `test_admin_notify` (`:184-192`) | **доступна любому пользователю**, шлёт админу «добавлен игрок test_player_notify» | 1 POST к api.telegram.org |
| не-текст (фото, стикер…) | `handle_non_text` (`:1919-1922`, `:1976-1979`) | ответ `unsupported_message` | 0 |
Важные следствия порядка хендлеров (`:1947-1951`): `ConversationHandler` для `/addtoken` стоит раньше общего `MessageHandler(TEXT)`, поэтому во время ожидания токена текст не попадает в `handle_username`. Флаг `awaiting_addgamer_username` после `/start` остаётся `True` до первого **успешного** добавления (или до `/addtoken`), т.е. любой текст, который пользователь напишет через неделю после `/start`, будет проверен как ник Lichess.
---
## 4. Алгоритм периодических проверок (`periodic_check`, `bot.py:1575-1900`)
### 4.1. Жизненный цикл задач
- Единица работы — пара `(user_id, gamer_id)` с `period_minutes > 0`. На каждую — своя `asyncio.Task` (`start_periodic_task`, `:1534-1551`), ключ `"{gamer_id}_{user_id}"` в `self.periodic_tasks`; плановое начало следующего окна — в памяти `self.period_start_times[task_key]` и в БД `last_period_end_ts`.
- При старте бота `post_init` → `start_existing_periodic_tasks` (`:209-259`): читает все пары (`get_all_gamers_with_periods`), запускает процессор `RequestQueue`, создаёт задачи с разбросом `PERIODIC_STARTUP_STAGGER_MAX_SECONDS / N` между ними (30 с / 453 ≈ 66 мс), затем задачу сброса счётчиков в полночь.
- Задачи также создаются сразу при добавлении игрока (`:717`, `:581`) и при `/setperiod` (`:1412`); останавливаются при `/setperiod → 0` (`:1402`), при удалении игрока/обнулении периода — сами на следующей итерации (`:1594-1611`, один `get_user_gamers` на итерацию), при `Forbidden` от Telegram (`:1846-1853`).
### 4.2. Одна итерация цикла
1. Перечитать период из БД; если игрок удалён или период 0 — выйти; если изменился — применить (`:1613-1616`).
2. Определить окно `[since_time, period_end_approx]` — три случая (`:1620-1669`):
- **Первая проверка** (чекпоинта в БД нет, `is_first_check`): `sleep(period_minutes*60)`, затем `period_end_approx = now − jitter`, `since_time = period_end_approx − period`. Т.е. новый игрок получит первое уведомление не раньше чем через час после добавления, и первое окно покрывает ровно последний час (`:1659-1669`).
- **По расписанию** (чекпоинт есть и `checkpoint + period > now`): `sleep` до `checkpoint + period`, окно `[checkpoint, checkpoint + period]` — окна стыкуются без зазоров и без джиттера (`:1625-1640`).
- **Отставание / collapse backlog** (`checkpoint + period <= now` — после рестарта, долгого простоя, или если предыдущая итерация заняла больше периода): окно `[checkpoint, now − jitter]` одним запросом вместо догона по одному периоду за раз (`:1641-1658`). Если отставание больше одного периода — WARNING `⏰ … behind schedule … collapsing backlog`.
3. **`STALE_BACKLOG_THRESHOLD = 2 ч`** (`:1675-1682`): если длина окна больше 2 часов — `is_stale_backlog = True`: запрос всё равно делается, чекпоинт продвигается, но уведомление **не отправляется** (лог `⏭️ Suppressed stale backlog notification`, `:1857-1858`). Задумано для подавления «отчёта за три недели простоя».
- **Побочный эффект, видимый из кода:** условие сравнивает длину окна, а не величину отставания. При обычной проверке длина окна равна `period_minutes`, поэтому для периодов **180, 360, 720 и 1440 минут** (`PERIOD_OPTIONS`) окно всегда > 2 ч и уведомления никогда не уходят — только чекпоинт двигается. На проде почти все пары стоят на 60 мин (раздел 8), поэтому масштаб эффекта мал, но пользователь с периодом «6 часов» уведомлений не получает. Не измерял на проде — вывод только из кода (`:1675-1676`, `:1820`).
4. **Джиттер** `_checkpoint_jitter_seconds` (`:1557-1573`): `crc32("{user_id}:{gamer_id}") % min(period*60*0.10, 300)` → для 60 мин 0..299 с, детерминированный, одинаковый между рестартами. Применяется только там, где конец окна «прибивается к сейчас» (первая проверка, collapse); в режиме «по расписанию» фаза уже зафиксирована предыдущим чекпоинтом. Цель — чтобы после рестарта 453 пары с одинаковым периодом не оказались «due» в одну секунду (`config.py:31-36`).
5. **Запрос партий** (`:1696-1723`): `request_queue.add_request(lichess_api.get_games_period, ник, since, until, include_games=True)` (приоритет по умолчанию `background`). `None` (любой не-200 от stats-сервиса, в т.ч. 502 от Lichess, сетевая ошибка) → `RuntimeError` → `consecutive_errors += 1`, `backoff = min(300, 60*n)` с, `continue` **без продвижения чекпоинта** — то же окно будет запрошено снова (и расширится до «сейчас», т.к. попадёт в ветку collapse). С 5-й ошибки (`max_consecutive_errors`) сообщения в лог становятся ERROR, но поведение то же — ретраи бесконечны.
6. **Уведомление админу** `ADMIN_NOTIFY_ERROR_THRESHOLD = 25` (`:1553-1555`, `:1717-1721`, `:1894-1898`): на 25-й подряд ошибке и далее на каждой кратной 25 → `_notify_admin_periodic_check_failing` (`:153-182`) с оценкой длительности по формуле бэкоффа (`_estimate_backoff_elapsed_hours`, `:147-151`): 25 ошибок ≈ 60+120+180+240+21×300 = 7200 с = 2 ч.
7. **Пазлы** (`:1725-1757`), только если у пары есть `token`: `get_puzzles_period(token, since, until, 150)` через ту же очередь. Три исхода: данные; `InvalidTokenError` (stats-сервис вернул 401 — Lichess отклонил токен, `lichess_api.py:161-163`) → `clear_user_gamer_token`, `gamer['token']=None`, пользователю `token_rejected_notice`, отслеживание партий продолжается; `None` (транзитная ошибка) → `RuntimeError` → внешний `except` → тот же бэкофф, чекпоинт не двигается. Запрос пазлов идёт к `lichess.org/api/puzzle/activity` с токеном **пользователя** (`lichess_client.py:218-296`): он не проходит через `SharedTokenGate`, Lichess возвращает последние 150 попыток, фильтрация по окну — в stats-сервисе.
8. `consecutive_errors = 0` (`:1760`) — **до** отправки уведомления, см. п. 10.
9. Определение активности (`:1762-1812`): `games_count > 0` или `data.total.games_played > 0`; `puzzles_in_period > 0` или `data.total_attempts > 0`.
10. **Отправка** (`:1820-1858`): если активность есть и не `is_stale_backlog` — `format_period_notification(…, actual_span_minutes)` (в заголовке реальная длина окна, не настроенный период), `bot.send_message(parse_mode='Markdown')`, счётчик `periodic_notification`. `telegram.error.Forbidden` (пользователь заблокировал бота) → `period_minutes=0` в БД, задача удаляется, `return` — навсегда, пока пользователь не включит период заново. Любая другая ошибка отправки (например, Markdown-разметка не распарсилась) → внешний `except` (`:1883-1900`) → бэкофф от `consecutive_errors=1` (счётчик только что сброшен, поэтому бэкофф для ошибок отправки никогда не превышает 60 с и до порога 25 не доходит), чекпоинт не двигается, активность будет отправлена повторно.
11. **Продвижение чекпоинта** (`:1862-1873`): `period_start_times[task_key] = period_end_approx`, `set_period_checkpoint(...)` — плановый конец окна, а не момент получения ответа, чтобы окна стыковались. Разница между плановым концом и фактическим завершением запроса — та самая «задержка относительно плана» (DEBUG `⏱️ Request completed with … delay`, `:1875-1878`); на проде в среднем 255 с, максимум 764 с (раздел 8). Источник задержки — очередь к `SharedTokenGate` (раздел 5): 453 пар на 600 слотов в час, плюс интерактивные команды с приоритетом.
### 4.3. Что это означает на практике
- Нагрузка на Lichess от фоновых проверок = число пар с периодом > 0 / их период, независимо от того, играет ли игрок. 453 пары × 1 запрос/час ≈ 453 `games/user` в час + запросы пазлов для пар с токеном.
- Проверка «догоняет» расписание одним запросом, поэтому после простоя бота в несколько часов пользователи ничего не получают (stale backlog), а после простоя меньше 2 часов — получают одно уведомление за всё окно.
- Период пары < 2 ч — единственный режим, в котором уведомления реально доходят (см. 4.2 п. 3).
---
## 5. Слои пейсинга запросов
Три независимых механизма; реально ограничивает обращения к lichess.org только третий.
| # | Где | Параметры | Что реально ограничивает |
|---|---|---|---|
| 1 | `LichessClientTG_bot/rate_limiter.py` — `RateLimiter(0.2)`, один глобальный экземпляр на процесс бота (`:48-52`), `wait_if_needed()` перед каждым методом `LichessAPI` (`lichess_api.py:23,47,75,92,116,149,185,208`) | min 0.2 с между **стартами** любых HTTP-запросов бота — и к localhost:8002, и к lichess.org | Фактически ничего: ≤ 18 000 запросов/час, а очередь ниже отдаёт ≤ 1800. Единственное место, где он хоть что-то значит — прямые анонимные вызовы `user/{ник}` из `/getgamers`, `/delgamer`, `handle_username` (там дополнительно `sleep(0.5)` в циклах). Эти прямые вызовы **не проходят** через gate stats-сервиса |
| 2 | `LichessClientTG_bot/request_queue.py` — `RequestQueue(min_dispatch_interval=2.0, max_concurrent=10)` (`config.py:28-29`), процессор запускается в `start_existing_periodic_tasks` (`bot.py:230`) | FIFO; диспетчеризация не чаще раза в 2 с (`:134-147`); не более 10 запросов одновременно «в полёте» (семафор, `:122`). Используется **только** `periodic_check` для `get_games_period` и `get_puzzles_period` (`bot.py:1699`, `:1735`); интерактивные команды в очередь не ходят | Трафик бот → локальный stats-сервис: ≤ 1800 диспетчей/час, ≤ 10 ожидающих в gate stats-сервиса одновременно. К lichess.org отношения не имеет (комментарий в `request_queue.py:4-10` и `config.py:23-27` это прямо признаёт). Удаляется в текущем рефакторинге |
| 3 | `LichessWebServices/rate_limiter.py` — `RateLimiter(0.2)` (`:13-53`, перед каждым вызовом `LichessClient`) **и** `SharedTokenGate(min_gap=6.0)` (`:55-123`) | Gate: ровно один запрос с `LICHESS_APP_TOKEN` в полёте + **минимум 6 с между release предыдущего и стартом следующего**; две очереди ожидающих — `interactive` (всегда вперёд) и `background` (`acquire(priority)`, `:85-100`; `release`, `:102-112`). Через gate идут `games/user` (`lichess_client.py:177-181`) и `user/activity` (`:92-96`, всегда `interactive`); `puzzle/activity` с пользовательским токеном через gate **не идёт** | Это единственный реальный ограничитель к lichess.org по общему токену. Потолок: **3600 / 6 = 600 запросов в час** на всё — фоновые проверки (1 запрос на пару) плюс интерактив (`/today` = 1–2 запроса на игрока, `/lastYear…` = 1). При 453 парах/час фоновая нагрузка ≈ 75 % потолка; любой интерактив вытесняет фон и увеличивает его задержку. 6 с подобраны эмпирически после 429 «Please only run 1 request(s) at a time» (`rate_limiter.py:113-119`) — документированного лимита Lichess для этого случая нет |
Итого фоновых проверок в час — не более 600 минус интерактив; измерено ≈ 445 (раздел 8). При увеличении числа пар или уменьшении периодов очередь будет расти без ограничения: `periodic_check` не знает о потолке, а collapse backlog просто расширяет окна.
---
## 6. Уведомления админу и TTS
Получатель — чат из `admin_settings.admin_chat_id`; отправитель всегда админ-бот (его токен), но код живёт в двух процессах.
| Событие | Откуда | Путь |
|---|---|---|
| Новый пользователь Telegram | `bot.start` (`bot.py:300-321`) | `admin_bot.notify_new_user` (`admin_bot.py:105-128`) → `send_notification` (`:38-76`); в процессе бота `AdminBot.application is None`, поэтому всегда срабатывает fallback — прямой POST `api.telegram.org/bot<ADMIN_TOKEN>/sendMessage` (`:59-72`). При исключении — второй fallback `_notify_admin_new_user` (`bot.py:112-144`), тот же POST |
| Добавлен игрок (и при обновлении токена) | `handle_username` (`:727`), `handle_token` (`:548`, `:591`), `/test_admin_notify` | `_notify_admin_new_player` (`bot.py:68-110`) → `admin_bot.notify_new_player` (`admin_bot.py:130-153`) → `send_notification`; при исключении — собственный POST-fallback (`bot.py:83-110`) |
| Мониторинг пары не работает (25 ошибок подряд) | `periodic_check` | `_notify_admin_periodic_check_failing` (`bot.py:153-182`) — свой прямой POST, без `AdminBot` |
Таким образом, прямой HTTP-вызов Telegram с админ-токеном написан четыре раза: три метода `_notify_admin_*` в `bot.py` и fallback в `AdminBot.send_notification`. Сообщения — HTML, на русском, с `lichess.org/@/{ник}` для игрока.
**TTS**: `AdminBot._call_tts_service` (`admin_bot.py:86-103`) — `GET {TTS_URL}/TTS?text=…` с таймаутом 5 с, вызывается после уведомлений «новый пользователь» (с общим числом пользователей, `:118-128`) и «новый игрок» (только если игрок новый в `gamers`, с общим числом игроков, `:142-153`). При незаданном `TTS_URL` — no-op с DEBUG-логом; до 6355cd9 адрес был зашит и на проде каждый вызов падал по таймауту.
Админ-бот `/status` (`admin_bot.py:155-228`) показывает: пользователей всего/сегодня, без игроков (и %), игроков всего/сегодня, счётчики команд (кроме `lang`, `resetlang`, `start`).
---
## 7. Логирование после 6355cd9
- Уровень — `LOG_LEVEL` из окружения, по умолчанию INFO (`config.py:12`); `bot.py:37-40` и `admin_bot.main` (`admin_bot.py:494-497`) конфигурируют logging каждый в своём процессе. Раньше `admin_bot.py` вызывал `basicConfig` при импорте и перебивал настройки бота.
- `httpx` → WARNING (`bot.py:43`, `admin_bot.py:500`): он писал каждый `getUpdates` (раз в 30 с) с полным URL, включая токен бота — это и был основной источник роста лога и утечка токена в логи.
- Ротация: `logging: json-file, max-size 50m, max-file 3` у всех трёх сервисов в обоих compose-файлах (`docker-compose.prod.yml:12-16,36-40,62-66`) → максимум 150 МБ на контейнер. До этого — 3 ГБ за 86 дней без ротации.
- Болтовня `periodic_check` (дампы ответов API, timestamps, «waiting N seconds», pacing очереди) переведена на DEBUG (`bot.py:1634,1640,1690,1698,1708,1767-1812,1860,1874,1878`; `request_queue.py:124,128,143`; `lichess_api.py:124-131`).
- `error_handler` пишет настоящий traceback через `exc_info=context.error` плюс пользователя и текст апдейта (`bot.py:2010-2020`); раньше печатал `NoneType: None`.
- **Какие INFO-строки оставлены и зачем** (это «воронка» для аналитики по логам):
- `⬅️ text from user <id>: '<текст>'` / `⬅️ callback from user <id>: '<data>'` / `⬅️ non-text message (<kind>) from user <id>` — ровно одна строка на входящий апдейт (`:1902-1917`), чтобы видеть, что пользователи вообще делают;
- `New user <id> added with bot_language=…` (`database.py:250`) — регистрации;
- `addgamer: user <id> entered username '…'` / `addgamer: username '…' not found on Lichess` / `… is a closed Lichess account` / `addgamer: player <ник> added for user <id> (new_gamer=…)` (`bot.py:635,646,655,702`) — шаги онбординга и их исходы;
- `Text from user <id> outside of /addgamer flow, replying with hint: …` (`:622`) — текст, который раньше молча игнорировался;
- `🔍 Checking activity for <ник> (user <id>): period from … to …` (`:1689`) — одна строка на фоновую проверку (по ней считается частота проверок и отставание), плюс `📊 Activity detected`, `✅ Sent periodic notification`, `⏭️ Suppressed stale backlog notification`, `♻️ Restored periodic checkpoint`, `🔄 Started periodic monitoring`;
- WARNING `⏰ … behind schedule … collapsing backlog`, `⏭️ … exceeds 2:00:00; catching up checkpoint silently`, `🚫 User … blocked the bot`, `🔑 Token rejected`.
- Что осталось шумным: `lichess_api.get_today_stats` пишет 4 INFO-строки на вызов (`lichess_api.py:46-56`), `get_stats` — около 6 на игрока (`bot.py:1026-1113`), `getgamers` — 2–3 на игрока; stats-сервис (`LichessWebServices`) логирует на INFO безусловно, 2–4 строки на каждый запрос к Lichess (`lichess_client.py:76-103,168,201`; `stats_service.py:216-271`), `LOG_LEVEL` на него не действует.
---
## 8. Замеренные показатели прода на 2026-10-20
Источник — выгрузка оркестратора (БД и `docker logs` прода). Собственных измерений в этом документе нет.
### 8.1. База
| Показатель | Значение |
|---|---|
| Пользователей Telegram (`telegram_users`) | **624** |
| из них без единого игрока | **350 (56 %)** |
| Игроков (`gamers`) | **503** до слияния регистровых дублей; после старта 6355cd9 станет **493** |
| Связей `user_gamers` | **522** |
| из них с `period_minutes > 0` | **453**, почти все — 60 мин |
| Распределение игроков по пользователям | один пользователь отслеживает 60 игроков, ещё двое — 23 и 13; остальные — в основном по одному |
### 8.2. Фоновые проверки
| Показатель | Значение |
|---|---|
| Фоновых проверок в час (`Checking activity for`) | **≈ 445** при потолке 600 (раздел 5) |
| Средняя задержка проверки относительно плана | **255 с** |
| Максимальная задержка | **764 с** |
| Ошибок 502 от stats-сервиса (= ошибка Lichess за gate) за 10 дней | **87**, все отретраены по бэкоффу, потерь окон нет |
### 8.3. Воронка за последние 10 дней
| Показатель | Значение |
|---|---|
| Нажатий `/start` | 8 |
| Новых пользователей | 3 |
| Попыток ввода ника новыми пользователями | **0** |
| Добавленных игроков | 1 |
### 8.4. Регистрации по месяцам (всего / без игроков)
| Месяц | Всего | Без игроков | Доля без игроков |
|---|---|---|---|
| 2025-11 | 166 | 76 | 46 % |
| 2025-12 | 108 | 66 | 61 % |
| 2026-01 | 100 | 62 | 62 % |
| 2026-02 | 104 | 62 | 60 % |
| 2026-03 | 29 | 15 | 52 % |
| 2026-07 | 29 | 17 | 59 % |
| 2026-08 | 30 | 16 | 53 % |
| 2026-09 | 12 | 10 | 83 % |
| 2026-10 (до 20-го) | 10 | 7 | 70 % |
Месяцы 2026-04…06 в выгрузке отсутствуют (нулевые или не выгружены — не знаю). Сумма по таблице — 588 из 624; остальные 36, вероятно, зарегистрированы до 2025-11 (не проверено).
### 8.5. Логи
| Показатель | Значение |
|---|---|
| Размер лога `lichess-telegram-bot` до 6355cd9 | **3 ГБ за 86 дней**, ротации не было |
| После 6355cd9 | ротация 50 МБ × 3 на контейнер |
---
## 9. Известные слабые места и технический долг
1. **`bot.py` — 2040 строк, класс `LichessBot` делает всё**: хендлеры, периодический цикл, уведомления админу, старт очереди. Именно это сейчас разносится по `periodic.py` / `notifications.py` / `onboarding.py`.
2. **Сценарий добавления игрока продублирован** в `handle_username` (`bot.py:677-744`) и `handle_token` (`bot.py:552-599`): `add_gamer` → `add_user_gamer` → период 60 → счётчик → `is_active` → `start_periodic_task` → уведомление админу. Версия в `handle_token` отстаёт: нет проверки `disabled`, регистрозависимое сравнение ника (`:536`, `:557`).
3. **Уведомление админу реализовано четырежды** прямым POST к Telegram API: `_notify_admin_new_player` (`bot.py:83-110`), `_notify_admin_new_user` (`:112-144`), `_notify_admin_periodic_check_failing` (`:153-182`), `AdminBot.send_notification` fallback (`admin_bot.py:59-76`); тексты «новый пользователь»/«новый игрок» продублированы в `bot.py` и `admin_bot.py`.
4. **Прямые `sqlite3.connect` в обход `Database`**: `bot.py:215-221` (статистика при старте), `:554-559` и `:679-684` (проверка «новый ли игрок» — причём первая регистрозависимая), `admin_bot.py:120-125`, `:145-150`, `:158-198`, `:248-253`, `:339-348`. Плюс `message_counters.py` держит свой доступ к той же таблице, которую создаёт `Database`.
5. **Три слоя пейсинга, защищает один** (раздел 5). Бот-side `RateLimiter` и `RequestQueue` создают иллюзию контроля, а прямые вызовы `user/{ник}` и `account` из бота вообще не координируются с gate.
6. **Все 453 пары проверяются с одинаковой частотой независимо от активности игрока** (`periodic_check` не адаптирует период; игрок, не игравший год, стоит столько же, сколько активный). При ≈75 % загрузки gate это основной риск роста: +150 пар на 60 мин — и очередь перестанет сходиться.
7. **Закрытые и мёртвые аккаунты остаются в базе и проверяются каждый час**: аккаунт `Dima` закрыт на Lichess, `Guy`/`guys` (регистровый дубль, будет слит) не заходили с 2013–2014. Проверка `disabled` появилась только для новых добавлений (`bot.py:652-660`); для уже существующих пар её нет, а stats-сервис на 404 от `games/user` отдаёт «0 игр, success=true» (`stats_service.py:728-735`), так что удалённый аккаунт неотличим от неактивного.
8. **`STALE_BACKLOG_THRESHOLD` отключает уведомления для периодов ≥ 3 ч** (раздел 4.2 п. 3) — вывод из кода, на проде не проверялся.
9. **`is_active` / кнопка `select_`** — почти мёртвая функциональность (раздел 2.1): поле выставляется и тянется через запросы, но влияет только на значок в `/delgamer`, а хендлер `select_gamer` (`bot.py:860-889`) недостижим.
10. **`/today` для пользователя с 60 игроками** — до 120 запросов через 6-секундный gate, 6–12 минут, и на это время фоновые проверки всех остальных пользователей встают (интерактив имеет приоритет).
11. **`/lastYear_or_1000games`** идёт с приоритетом `background` (`bot.py:1226`) — пользователь ждёт позади всей очереди фоновых проверок.
12. **`/test_admin_notify` доступна всем** (`bot.py:1962`).
13. **Тестовые бот-токены закоммичены** в `.env.example:5-6`.
14. **Нет тестов и нет отката в CI** (`.forgejo/workflows/deploy.yml`); деплой = `docker compose up -d` поверх работающего бота, при этом `drop_pending_updates=False` теперь сохраняет апдейты за время рестарта.
15. **`LOG_LEVEL` не действует на stats-сервис** (`LichessWebServices/main.py:28`), он пишет по 2–4 INFO-строки на каждый запрос к Lichess.
16. **Данные о задержке проверок только в DEBUG** (`bot.py:1875-1878`) — после перевода на INFO-уровень измерять отставание можно только косвенно, по `Checking activity for` и чекпоинтам в БД.
---
## Что НЕ проверено
- Прод не инспектировался при написании: все цифры раздела 8 взяты из выгрузки оркестратора как есть; месяцы 2026-04…06 и регистрации до 2025-11 — пробелы в выгрузке, а не факт их отсутствия.
- Сколько пар `user_gamers` имеют `token` (и, значит, сколько дополнительных запросов `puzzle/activity` уходит в час с пользовательскими токенами) — не известно.
- Эффект `STALE_BACKLOG_THRESHOLD` на периоды ≥ 3 ч выведен из кода; сколько таких пар на проде и получают ли они уведомления — не проверялось.
- Фактическая доля интерактивных запросов в gate (и, значит, реальный остаток потолка под фон) — не измерялась.
- Поведение `PicklePersistence` при одновременных рестартах и размер `bot_persistence.pickle` — не смотрел.
- Содержимое `docs/ARCHITECTURE.md` и `docs/USER_GUIDE.md` (июль 2026) не сверялось с текущим кодом; этот документ их не заменяет, но при расхождениях приоритет у кода на 6355cd9.