From 7ef5875f581022dfddac29c4d2f18806d865356c Mon Sep 17 00:00:00 2001 From: vrubelroman Date: Sat, 25 Jul 2026 23:01:35 +0000 Subject: [PATCH] authenticate outgoing lichess.org requests to fix silent 404s on games/user 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 --- .env.example | 6 ++++++ LichessWebServices/lichess_client.py | 20 +++++++++++++++++--- docker-compose.prod.yml | 2 ++ docker-compose.yml | 2 ++ 4 files changed, 27 insertions(+), 3 deletions(-) diff --git a/.env.example b/.env.example index 048aca9..6eacaf2 100644 --- a/.env.example +++ b/.env.example @@ -4,3 +4,9 @@ COMPOSE_PROJECT_NAME=lichess # Telegram Bot Tokens (Test) TELEGRAM_BOT_TOKEN=7903295042:AAGBO2k8pfBDy4RoLRFsknwE7z0N-thAPI8 ADMINPANEL_TELEGRAM_BOT_TOKEN=8588876086:AAHoZncfhTCbul1BblpvnZMzvz7jAYVFmcw + +# Lichess personal API token used to authenticate outgoing requests to +# lichess.org (games/user, user/activity). Lichess started rejecting +# anonymous requests to these endpoints with a 404; any valid token works, +# it does not need to belong to a tracked player. +LICHESS_APP_TOKEN=lip_xxxxxxxxxxxxxxxxxxxx diff --git a/LichessWebServices/lichess_client.py b/LichessWebServices/lichess_client.py index 6d206ad..e8ddae8 100644 --- a/LichessWebServices/lichess_client.py +++ b/LichessWebServices/lichess_client.py @@ -14,6 +14,7 @@ Lichess Statistics API - Клиент для работы с Lichess API """ import httpx +import os from typing import List, Dict, Any, Optional from datetime import datetime, timedelta import logging @@ -44,6 +45,15 @@ class LichessClient: self.base_url = "https://lichess.org/api" # Базовый URL Lichess API self.client = httpx.AsyncClient(timeout=30.0) # HTTP клиент с таймаутом self.rate_limiter = get_rate_limiter() + # Lichess начал возвращать 404 (вместо честного 401/429) на анонимные + # запросы к games/user и user/activity — тот же валидный токен, отправленный + # для другого юзера, сразу превращает 404 в 429, то есть эндпоинт жив, просто + # больше не пускает анонимных. Токен не должен принадлежать конкретному + # отслеживаемому игроку — он только авторизует запрос, к его данным доступа + # не даёт (партии и так публичные). + self.app_token = os.getenv("LICHESS_APP_TOKEN") + if not self.app_token: + logger.warning("LICHESS_APP_TOKEN не задан — анонимные запросы к games/user и user/activity будут получать 404 от Lichess") async def get_user_activity(self, username: str) -> Optional[List[Dict[str, Any]]]: """ @@ -67,9 +77,11 @@ class LichessClient: # Формируем URL для получения активности пользователя url = f"{self.base_url}/user/{username}/activity" logger.info(f"🔍 Making request to Lichess API: {url}") - + + headers = {'Authorization': f'Bearer {self.app_token}'} if self.app_token else {} + # Выполняем HTTP GET запрос - response = await self.client.get(url) + response = await self.client.get(url, headers=headers) logger.info(f"🔍 Lichess API response status: {response.status_code} for {username}") response.raise_for_status() # Проверяем статус ответа @@ -135,7 +147,9 @@ class LichessClient: headers = { 'Accept': 'application/x-ndjson' # Запрашиваем NDJSON формат } - + if self.app_token: + headers['Authorization'] = f'Bearer {self.app_token}' + logger.info(f"Запрос игр для {username} с {since_ms} по {until_ms}") # Выполняем HTTP GET запрос diff --git a/docker-compose.prod.yml b/docker-compose.prod.yml index 3c170d9..d13e572 100644 --- a/docker-compose.prod.yml +++ b/docker-compose.prod.yml @@ -4,6 +4,8 @@ services: container_name: lichess-api ports: - "8002:8000" + env_file: + - .env environment: - PYTHONUNBUFFERED=1 restart: always diff --git a/docker-compose.yml b/docker-compose.yml index 0f25aac..1200f0d 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -6,6 +6,8 @@ services: container_name: lichess-api ports: - "8002:8000" + env_file: + - .env environment: - PYTHONUNBUFFERED=1 volumes: