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>
Analysis: docs/analysis/onboarding_funnel.md (56% of users never add a player;
drop happens on the first screen; non-ru/en users convert at 25%).
Design: docs/design/onboarding.md.
- /start: one message. New user: promise + "send a Lichess username, e.g.
DrNykterstein" with [❓ Где взять имя] / [🇬🇧 English] (language switch edits
the message in place). Returning user: their players + /today /addgamer /help.
- /addgamer asks for the name directly (the two-button menu from 2025-12-03 is gone).
- Any non-command text in a private chat is a player-name attempt: no awaiting
flag, PicklePersistence removed. onboarding.normalise_username accepts
lichess.org URLs, @name, quotes, "add Name"; chess.com and non-name text get
their own hints; nothing is sent to Lichess for them.
- Every reply ends with the next step (success: hourly report is on, /today,
send another name). One no_players empty state for /today, /week, /getgamers,
/delgamer, /setperiod, /profile, /year.
- /help: 18 lines in three groups; /year and /lang aliases; command menu set
from code for en (default) and ru at startup (set_my_commands).
- /addtoken trap: non-lip_ text gets a hint instead of "invalid token"; any
other command inside the conversation ends it and runs; /cancel outside a
conversation answers "nothing to cancel".
- All echoed input html-escaped. Terminology unified: игрок / имя на Lichess /
отчёт (player / Lichess username / report).
- events: user_start screen=, addgamer_input kind= normalised=, addgamer_result
format|chesscom, lang_set via=, addtoken_result not_a_token; text in_flow= gone.
- i18n: 18 dead keys removed, 21 added; docs (README, USER_GUIDE, about,
CURRENT_STATE, CHANGELOG Unreleased) updated; 107 bot tests (was 61).
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>
- player status: initial bulk refresh retries 4x5s (bot and stats service start in the
same second on prod, the first attempt failed with connection reset); admin is
notified after 3 consecutive failed refreshes
- /today, /yesterday, /week: players whose bulk status shows they were not online since
the period start (or whose account is closed) are skipped without any Lichess call;
stats service paces user/activity at 8.5s (Lichess allows 15 per 2 min per IP), so a
user with 16+ tracked players no longer hits 429 mid-command
- unknown /commands in private chats get the usual hint and a cmd name=unknown event
- /addtoken -> /cancel used to crash (sync lambda awaited by PTB 20); now an async handler
- version 1.5.0, CHANGELOG entry for everything since 1.1.0 that shipped today
- docs: CURRENT_STATE.md rewritten for 30aaa34, README brought in line with the code
(port 8002, module list, commands, .env vars, DB tables, events.log section)
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
- events.py (bot): one grep-able line per event into data/events.log (10 MB x 5 rotation,
survives container recreation): user_start, cmd, text/callback/non_text, addgamer_input/
addgamer_result, addtoken_result, gamer_added, gamer_deleted, period_set, lang_set,
check (decision=request|skip_unchanged|skip_closed, games, notified, lag), check_error,
closed_notice, reopened_notice, blocked, token_rejected, status_refresh, admin_notify,
tg_error; a SUMMARY line at midnight, also shown by admin /status as "Вчера".
Service side: EVT lichess_429 (kind=concurrency|burst|unknown) and lichess_error in its log.
- /games/{username}/period?by_finish=true: query Lichess from since-3h and keep games with
since < lastMoveAt <= until. Periodic checks use it, so a game created 14:58 and finished
15:06 is reported in the 15:00-16:00 window instead of being lost on the boundary.
- reopened-account notice is sent as soon as the status flips, not after the next game.
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>
- periodic: stale-backlog suppression compared the window length with an absolute 2h,
so every pair with period 180/360/720/1440 min was suppressed on every check
(prod: 20 pairs of 16 users, 62 suppressions in 10 days). Now stale means the window
exceeds the configured period by more than 2h (PeriodicMonitor._is_stale_backlog).
- SharedTokenGate min_gap 6s -> 3s. Measured with a separate test account: the JSON
"Please only run N request(s) at a time" 429 is a concurrency limit (2 streams per
IP / per token, slot freed at stream end) that a sequential client cannot trip, so
the old 6s "cooldown" rationale was wrong; the HTML "Too many requests" 429 is an
edge burst limiter (~0.45-0.9 req/s sustained) that 2-3s spacing avoids.
- lichess_client: on 429 log the body prefix (so the two limiters are distinguishable)
and pause the gate 60s for the burst limiter only; re-raise exactly as before.
- /lastYear_or_1000games uses interactive priority (was waiting behind the backlog)
- /test_admin_notify only works from the admin chat
- stats service honours LOG_LEVEL and silences httpx INFO (bulk of its 808 MB log)
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>
/today, /yesterday, /week were queuing behind the entire periodic-check
backlog on the same rate-limited LICHESS_APP_TOKEN (observed ~2min wait on
prod for a single command). Add a two-tier priority queue to SharedTokenGate:
interactive on-demand requests jump ahead of background periodic checks,
which still drain normally when nothing interactive is waiting. Verified
locally end-to-end (isolated queue unit tests, live request with priority
correctly reaching Lichess, and a real successful accuracy fetch rendered
through StatsFormatter).
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
A bare mutex around games/user and user/activity wasn't enough: Lichess kept
rejecting the shared LICHESS_APP_TOKEN with 429 "Please only run 1
request(s) at a time" even when calls were strictly sequential with only
~100-300ms between one finishing and the next starting (confirmed live on
prod: near every request was getting 429'd right after the previous mutex
fix went out). Track the last release time and force a minimum 6s gap
before the next call is allowed to start.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
games/user and user/activity share one LICHESS_APP_TOKEN process-wide, and
Lichess allows only 1 concurrent request per token there (confirmed live:
429 "Please only run 1 request(s) at a time" under concurrent traffic).
The existing rate limiter only paced request starts 0.2s apart without
holding the lock through the request itself, so concurrent games/period
calls (periodic checks vs. on-demand /today etc.) could still collide and
get 429'd, silently dropping the accuracy shown in /today, /yesterday,
/week (that fetch is best-effort and swallows errors). Hold a dedicated
lock for the full request/response cycle on these two calls; puzzle
requests use per-user tokens and don't need it.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Lichess started rejecting anonymous requests to games/user and
user/activity with a 404 (confirmed live: the same request with a valid
bearer token got a normal 429 instead), which our code silently read as
"user has no games" for every single tracked player, making periodic
checks report zero activity across the board. Add LICHESS_APP_TOKEN and
send it as a Bearer token on these two calls; it just needs to be any
valid token; it does not need to belong to the tracked player.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Forbidden from send_message was falling into the generic error handler,
which resets consecutive_errors to 0 right before the send attempt — so
backoff never grew past 60s and the pair retried forever, wasting request
queue capacity needed by other users' real periodic checks.
Co-Authored-By: Claude Sonnet 5 <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.
The bot's request_queue.py 4s FIFO gate wasn't protecting against Lichess's
rate limiter — that's already handled downstream in LichessWebServices/
rate_limiter.py (0.2s, shared across all callers of our stats service). The
bot-side gate only paced calls to our own local service, and since it awaited
each request to full completion before dequeuing the next, real dispatch gaps
were max(4s, previous request's duration) — with 454 tracked gamer/user pairs,
any burst (e.g. after a restart) piled into the queue and took 10-20+ minutes
to drain.
Replace it with a paced-dispatch + bounded-concurrency design: a hard 2s floor
between dispatches (still never lets 2+ requests through in that window),
decoupled from completion time, with up to 10 requests actually in flight at
once via a semaphore. Doesn't touch the real Lichess-facing rate limit at all.
Also add deterministic per-(user,gamer) checkpoint jitter: previously every
pair sharing the same period_minutes re-locked onto the same wall-clock phase
on every restart (backlog collapse snaps period_end_approx to `now` for
everyone overdue at once), recreating the pileup each time. Jitter is stable
across restarts (crc32-based, not Python's salted hash()) and capped well
under the 2h stale-backlog threshold. Small startup stagger added too, purely
cosmetic smoothing on top of the jitter fix.
The backlog-collapse fix (previous commit) correctly stops the checkpoint
from falling further behind, but it was still sending the full per-game
notification for whatever it caught up on — meaning a gamer whose checkpoint
had drifted weeks behind now dumps a multi-week, game-by-game report on the
user in one message. That's not a "periodic update" anymore, just spam.
When the collapsed window exceeds 2 hours, catch the checkpoint up silently
(still fixes the drift) but skip sending the notification for it — only
report activity that's actually recent going forward.
Persist user_data (PicklePersistence) so an in-flight /addgamer username
prompt survives a bot restart instead of being silently swallowed by
handle_username when the in-memory awaiting flag is gone.
Collapse periodic-check backlog into a single request spanning the whole
missed gap instead of replaying it one period_minutes window at a time —
with enough tracked gamers sharing one RequestQueue, per-window replay
could never catch up and the checkpoint fell further behind indefinitely.
Notification period label now reflects the actual queried span (minutes/
hours/days) instead of the configured interval, so a weeks-old catch-up
no longer gets mislabeled as "for 15 minutes".
Column-align per-mode rows (games/rating change/rating/W-L-D/accuracy)
same as the other stats commands, instead of loose free-text lines.
Strip the invisible variation selector from bullet/classical emoji so
it doesn't throw off column padding.
- /getgamers: column-aligned monospace table (username, ratings, period).
- Per-mode stats (rating/wins/losses/draws): column-aligned block, dropped
the meaningless multi-game average accuracy row.
- format_stats_response/format_period_notification now wrap the whole
message in a single markdown code block instead of alternating
plain-text headers and separately-fenced tables.
- Rating row gets an emoji prefix to match the other three rows, so
Telegram's monospace rendering keeps all values in the same column.
Set awaiting_addgamer_username as soon as the menu is shown so typing a
username directly (without tapping the button) is handled instead of
being silently ignored. Also stop reporting a valid username as "not
found" when Lichess returns a non-404 error (rate limit/timeout), and
surface an error message if the addgamer menu itself fails to send.
Add a small circle (⚪/⚫) glued right after the tracked player's name
in the per-game table to show which color they played, since the
white/black split was no longer visible once the opponent's name was
dropped. Replace the '1-0'/'0-1'/'1/2-1/2' result text with a plain
'-' separator — the leading outcome circle already conveys win/loss/draw.
Reworked the per-game row layout to be relative to the tracked player
instead of white/black: the tracked player's name+accuracy+rating are
always shown first, the opponent's rating+accuracy (no name) always
second, regardless of which color each side played in a given game -
this keeps columns aligned across rows even as the tracked player
switches sides. Dropped the rating-change-per-game column added
earlier; it pushed the line past mobile width limits.
Games-of-period responses can now include a per-game breakdown
(include_games) with Lichess post-analysis accuracy, plus which side
the tracked player was on and their rating change for that game.
- lichess_client.py requests accuracy=true from Lichess; stats_service
computes per-mode average accuracy and builds GameRow entries
(tracked_is_white, tracked_rating_diff) for blitz/rapid/classical
- /games/{username}/period gained an include_games query param
- formatters.py renders a column-aligned monospace table per game:
outcome circle (win/loss/draw relative to the tracked player),
rating change, accuracy, names/ratings, result — for today/yesterday
and periodic notifications; week keeps an aggregate accuracy line
- usernames are Markdown-escaped before formatting since messages are
now sent with parse_mode='Markdown'
Errors from Lichess (timeouts/5xx/invalid tokens) were being disguised
as "no activity" (HTTP 200, games_count/puzzles_in_period=0), causing
the bot to silently advance its checkpoint past real, undetected
activity. Puzzle-fetch failures weren't counted as errors at all, and
the periodic task died permanently after 5 consecutive errors with no
way to recover short of a manual restart. /setperiod also unconditionally
reset the checkpoint, dropping the window between the last check and
the command.
- API now returns success=false/502 on real errors instead of masking
them as zero activity (models.py, stats_service.py, main.py)
- Puzzle-fetch errors are now treated the same as game-fetch errors:
retry the same window instead of reporting "no puzzles"
- Notification delivery failures no longer silently advance the
checkpoint
- Replaced the hard 5-error kill switch with capped backoff that keeps
retrying indefinitely, plus an admin-bot notification if a player's
monitoring has been failing for a prolonged period (~2h+)
- /setperiod only clears the checkpoint when disabling notifications,
preserving continuity when a period is just changed
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Unused component that also carried several security issues (default
admin credentials, hardcoded Flask secret key, debug mode, plaintext
passwords). Cleaned up compose files, CI/CD pipeline, and docs
accordingly; also dropped the stale IS_PROD config docs in favor of
the current .env-based setup.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
- Remove IS_PROD flag and hardcoded tokens from config.py
- Read TELEGRAM_BOT_TOKEN and ADMINPANEL_TELEGRAM_BOT_TOKEN from env
- Add env_file: .env to lichess-bot and admin-bot in docker-compose.yml
- Add .env to .gitignore (no longer tracked)
- Add .env.example with test tokens