The bot sends nothing on its own initiative except reports and the closed /
not-found account notices. Removes the periodic check, the sl: callbacks,
the silent_prompt_at column migration, the i18n keys and their tests.
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
- periodic report rebuilt in HTML: title with games count, mode lines, one <pre>
table (± · colour · accuracy · opponent rating · opponent accuracy), 10-row cap,
span note after catch-up; stats service returns tracked_rating_diff per game
- /getgamers shows player state from the DB (played today / N days quiet /
closed / not found, report period) without Lichess calls; ratings on a button
- "player silent 30 days — keep?" prompt with keep/delete buttons, repeat 90 days
- /today, /yesterday, /week: one message edited into the result, nav buttons
- /year localised; active-gamer leftovers and N/A removed; one period wording
- docker-compose.prod.yml: stats port 8002 bound to 127.0.0.1
- product review docs: user journeys, concepts, Mini App feasibility, proposal
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
- /status: verdict line (✅/⚠️, UTC time), 🩺 health (errors today/yesterday,
Lichess 429 per 24 h from /health, age of the last player-status refresh,
closed/not-found players, users who blocked the bot in 7 days), 📈 growth
table (users/gamers/subscriptions: total, +today, +yesterday, +7 days,
users without gamers), ⚡ activity today vs yesterday (commands, active
users, notifications, Lichess requests). Flags: errors >= 10, any 429,
status older than 30 min, no SUMMARY for yesterday, journal missing.
Blocks fail independently (only a DB failure breaks the whole message).
- /counters: all raw command counters sorted by total + last SUMMARY as is.
- Database.get_admin_overview replaces get_admin_stats.
- events.summarize_days (one pass over events.log.1 + events.log, extra
keys active_users/blocked/status_refresh_failed/cmd_by_name/lines),
last_summary(); last_summary_line reads the rotated backup too.
- LichessAPI.get_service_health(timeout).
- Designer spec in docs/design/admin_status.md; README, CURRENT_STATE,
CHANGELOG (Unreleased) updated; 25 new tests (61 bot tests total).
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
- players absent from two consecutive bulk answers (deleted/renamed on Lichess) are paused
like closed accounts with their own notice; ❓ mark; stats service answers 404 instead
of "0 games" for unknown users
- /getgamers table stays unmarked, a legend line under it lists closed / not-found players
- daily SUMMARY is computed from events.log (survives restarts); lichess_429 comes from the
stats service /health, which now exposes lichess_429_24h / lichess_429_total
- admin /status reads its numbers through Database.get_admin_stats
- tests/: 36 bot + 15 service unittest cases, run_tests.sh runs them inside the real images,
CI runs them after the build and before pushing/deploying
- docs: USER_GUIDE/about/API_DOCUMENTATION rewritten for the current code, ARCHITECTURE.md and
two sub-READMEs removed, 7 obsolete helper scripts removed, CURRENT_STATE updated
- .claude/agents/designer.md: Telegram-aware designer role
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
- stats service: POST /users/status proxies Lichess POST /api/users (up to 300 names,
through the shared-token gate) -> disabled / seen_at / games_total (sum of perfs.*.games)
- bot: PlayerStatusRefresher refreshes all tracked players every 15 min (2 bulk calls for
~500 players) into the new gamer_status table
- periodic_check: before the games request, _decide_skip() compares the player's
games_total with the pair's stored baseline (user_gamers.last_games_total); unchanged
and no token -> no HTTP call, checkpoint advances only to what the status proves
(status.checked_at - 60s), so games finished between a refresh and the window end
are still reported next time. Closed account -> skip + one notice to the owner,
auto-resume when reopened.
- /getgamers and /delgamer mark closed accounts with ⛔
Background load drops from ~445 games/user calls per hour to ~8 bulk calls plus one
games call per player who actually played.
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
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>
- log rotation (50m x 3) for all services in both compose files
- httpx logger -> WARNING: it logged every Telegram call with the bot token in the URL
- LOG_LEVEL env (INFO default); admin_bot no longer forces the level via import-time basicConfig
- periodic_check chatter (API dumps, timestamps, waits) moved to DEBUG
- error_handler logs the real traceback (exc_info) plus the offending user/update
- drop_pending_updates=False so /start during a restart isn't silently lost
- TTS announcer behind optional TTS_URL (unreachable from prod, was failing on every event)
- reject closed Lichess accounts on /addgamer (API answers 200 with disabled=true)
- store Lichess' canonical username spelling; merge case-duplicate gamers at startup,
case-insensitive unique index prevents new ones
- reply with a hint on text outside the /addgamer flow and on non-text messages;
one INFO line per incoming update for funnel visibility
- gamer_added counter for successful adds; /setperiod localized (ru hour plurals)
- drop hardcoded /home/vrubel path for help images
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
A gamer's periodic check would get permanently stuck if their stored token
was revoked/expired: our stats API collapsed both "Lichess rejected the
token" (401/403, permanent) and genuine transient errors into the same 502
response, so the bot treated an invalid token exactly like a network blip —
retrying the same window forever at a capped 300s backoff, never advancing
the checkpoint (observed in prod: Dor1zz stuck for 100+ consecutive errors
over 8+ hours, admin alerts firing every 25 failures).
Preserve the distinction that already existed one layer down (lichess_client.py
already tells 401/403 apart from other failures) instead of collapsing it in
stats_service.py: add PuzzleOfPeriodResponse.auth_failed, have main.py return
401 specifically for that case, and have the bot raise a distinct
InvalidTokenError instead of returning None. On InvalidTokenError, the bot now
clears the token for that pair, notifies the user to reconnect via /addtoken,
and continues tracking games normally instead of stalling forever.
- Добавлен метод remove_user_gamer в database.py
- Добавлена команда /delgamer с интерактивным списком игроков
- Добавлен callback handler для удаления игроков
- Если игрок удаляется у всех пользователей, он удаляется из gamers
- Игроки показываются с рейтингами и статусом
- Исправлен баг с двойным ответом в /getgamers (добавлена обработка ошибок)
- Добавлена автоматическая миграция токенов при инициализации БД
- Исправлен веб-интерфейс - теперь берет токены из user_gamers
- Улучшен start.sh - создает бэкап базы перед перезапуском
- Добавлен export_db.sh для экспорта базы данных
- start.sh безопасно обновляет проект и сохраняет все данные
- Добавлено поле token в таблицу user_gamers
- Токены теперь привязываются к паре пользователь-игрок, а не глобально
- Обновлены методы работы с токенами
- Теперь каждый пользователь может иметь свой токен для одного игрока
- Объединены три проекта в один репозиторий
- LichessWebServices - REST API для статистики
- LichessClientTG_bot - Telegram бот с поддержкой множества пользователей
- LichessWebView - Веб-интерфейс для просмотра пользователей и игроков
- Добавлен общий docker-compose.yml для запуска всех сервисов
- Добавлен скрипт start.sh для удобного запуска
- Добавлен README с полным описанием проекта