Commit graph

19 commits

Author SHA1 Message Date
vrubelroman
b4c63aa79a v1.8.0: Uzbek, Turkish, Persian and Arabic locales, auto-detected for new users
Some checks failed
CI/CD Pipeline / build-and-deploy (push) Failing after 2s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-23 21:36:05 +00:00
vrubelroman
58bf8b7381 drop the 'player quiet for 30 days' prompt (owner decision)
All checks were successful
CI/CD Pipeline / build-and-deploy (push) Successful in 29s
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>
2026-10-21 11:58:51 +00:00
vrubelroman
df6b582376 iteration 1: report with game table, /getgamers state screen, silent-30-days prompt, /today as one message, stats port bound to localhost
- 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>
2026-10-21 11:26:20 +00:00
vrubelroman
6351e18795 admin bot: /status redesigned around health, growth and activity; raw counters moved to /counters
- /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>
2026-10-21 06:16:53 +00:00
vrubelroman
a7571f13c1 v1.5.1: not-found players paused, tests in repo + CI, log-based daily summary, docs pruned
All checks were successful
CI/CD Pipeline / build-and-deploy (push) Successful in 16s
- 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>
2026-10-21 02:48:00 +00:00
vrubelroman
27e76b2399 bulk player status: skip periodic checks for players who did not play, pause closed accounts
- 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>
2026-10-20 22:31:33 +00:00
vrubelroman
7178b80854 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>
2026-10-20 21:46:48 +00:00
vrubelroman
6355cd917d fix log bloat, token leak, silent onboarding gaps, closed-account adds, case-duplicate gamers
- 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>
2026-10-20 21:21:19 +00:00
vrubelroman
619c00aa06 stop infinite retry loop on rejected Lichess tokens
All checks were successful
CI/CD Pipeline / build-and-deploy (push) Successful in 12s
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.
2026-07-05 07:37:14 +00:00
vrubelroman
63e28c279c fix by codex 2026-03-21 22:58:47 +03:00
vrubelroman
123749415a switch ru/en 2025-11-20 12:43:00 +03:00
vrubel
1d485fc100 bug fixed /addplayer 2025-11-16 13:38:25 +03:00
vrubelroman
ceb62b408a add statistics 2025-11-13 13:32:46 +03:00
vrubelroman
23de80f94d admin panel 2025-11-13 01:00:48 +03:00
vrubelroman
3362bf89e2 EN language only 2025-11-12 23:20:01 +03:00
vrubelroman
e59bbb7d0e Добавлена команда /delgamer для удаления игроков
- Добавлен метод remove_user_gamer в database.py
- Добавлена команда /delgamer с интерактивным списком игроков
- Добавлен callback handler для удаления игроков
- Если игрок удаляется у всех пользователей, он удаляется из gamers
- Игроки показываются с рейтингами и статусом
2025-10-28 21:59:16 +03:00
vrubelroman
6cb5a9b99f Исправление двойного ответа и улучшение системы
- Исправлен баг с двойным ответом в /getgamers (добавлена обработка ошибок)
- Добавлена автоматическая миграция токенов при инициализации БД
- Исправлен веб-интерфейс - теперь берет токены из user_gamers
- Улучшен start.sh - создает бэкап базы перед перезапуском
- Добавлен export_db.sh для экспорта базы данных
- start.sh безопасно обновляет проект и сохраняет все данные
2025-10-28 21:34:35 +03:00
vrubelroman
2c87dc60f7 Исправление хранения токенов: токены теперь в user_gamers, а не в gamers
- Добавлено поле token в таблицу user_gamers
- Токены теперь привязываются к паре пользователь-игрок, а не глобально
- Обновлены методы работы с токенами
- Теперь каждый пользователь может иметь свой токен для одного игрока
2025-10-26 20:35:23 +03:00
vrubelroman
a08fc8c962 Создание единого проекта Lichess Statistics Ecosystem
- Объединены три проекта в один репозиторий
- LichessWebServices - REST API для статистики
- LichessClientTG_bot - Telegram бот с поддержкой множества пользователей
- LichessWebView - Веб-интерфейс для просмотра пользователей и игроков
- Добавлен общий docker-compose.yml для запуска всех сервисов
- Добавлен скрипт start.sh для удобного запуска
- Добавлен README с полным описанием проекта
2025-10-26 20:23:26 +03:00