LichessStatTgWeb/LichessClientTG_bot/config.py
vrubelroman 028fd4d3e8 fix never-sent notifications for periods >= 3h, lower shared-token gap to 3s, handle both Lichess 429s
- 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>
2026-10-20 21:55:30 +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 (3 с между запросами, приоритет 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"]