LichessStatTgWeb/LichessClientTG_bot/config.py
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

75 lines
4.3 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import os
from dotenv import load_dotenv
load_dotenv()
TELEGRAM_BOT_TOKEN = os.getenv("TELEGRAM_BOT_TOKEN")
ADMINPANEL_TELEGRAM_BOT_TOKEN = os.getenv("ADMINPANEL_TELEGRAM_BOT_TOKEN")
# Python logging level for the bot processes (DEBUG/INFO/WARNING). INFO by default:
# the old code asked for DEBUG but never actually got it (admin_bot's basicConfig
# ran first at import time), and DEBUG would multiply an already multi-GB log.
LOG_LEVEL = os.getenv("LOG_LEVEL", "INFO").upper()
# Optional text-to-speech announcer for admin events ("new user", "new player").
# Only reachable from the home LAN, so it is unset on prod and skipped there.
TTS_URL = os.getenv("TTS_URL") or None
# Lichess API Configuration
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
# Слои пейсинга запросов (чтобы не плодить лишние):
# - Настоящий лимитер общего 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 момент при рестарте бота
# (см. periodic_check в bot.py). Потолок держим далеко ниже STALE_BACKLOG_THRESHOLD (2ч),
# чтобы не задевать логику подавления уведомлений по устаревшему бэклогу.
PERIODIC_CHECKPOINT_JITTER_FRACTION = 0.10
PERIODIC_CHECKPOINT_JITTER_MAX_SECONDS = 300
# Разброс старта периодических задач при запуске бота, чтобы не бить по SQLite
# синхронно за один тик event loop при большом числе отслеживаемых игроков.
PERIODIC_STARTUP_STAGGER_MAX_SECONDS = 30
# Database Configuration
def _resolve_database_path() -> str:
# 1) Explicit env var has highest priority
db_from_env = os.getenv("DATABASE_PATH")
if db_from_env:
return db_from_env
# 2) Docker default if volume is mounted
docker_data_dir = "/app/data"
if os.path.isdir(docker_data_dir):
return os.path.join(docker_data_dir, "lichess_bot.db")
# 3) Local development fallback (repo data dir)
repo_data_dir = os.path.join(os.path.dirname(__file__), "data")
os.makedirs(repo_data_dir, exist_ok=True)
return os.path.join(repo_data_dir, "lichess_bot.db")
DATABASE_PATH = _resolve_database_path()
# Period options for /setperiod command
PERIOD_OPTIONS = [0, 15, 30, 60, 120, 180, 360, 720, 1440] # minutes (0=disable, then: 15min, 30min, 1h, 2h, 3h, 6h, 12h, 24h)
# Telegram Bot Long Polling Configuration
POLL_INTERVAL = 1.0 # seconds
POLL_TIMEOUT = 30 # seconds
# Keep updates that arrived while the bot was down (deploy, host reboot): with
# True, a /start or a typed username sent during a restart was silently lost and
# the user never got any reply. Telegram keeps them for 24h.
DROP_PENDING_UPDATES = False
ALLOWED_UPDATES = ["message", "callback_query"]