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

69 lines
3.9 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
# Пейсинг очереди запросов к НАШЕМУ ЖЕ локальному 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 = откат к строго последовательному режиму
# Джиттер чекпоинтов периодических проверок: не даёт парам (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"]