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

1377 lines
61 KiB
Python
Raw Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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 asyncio
import logging
import os
from datetime import datetime, timedelta
from pathlib import Path
from telegram import Update, InlineKeyboardButton, InlineKeyboardMarkup
from telegram.ext import (
Application, CommandHandler, CallbackQueryHandler,
MessageHandler, filters, ContextTypes, ConversationHandler,
PicklePersistence, TypeHandler
)
from config import (
TELEGRAM_BOT_TOKEN, PERIOD_OPTIONS, POLL_INTERVAL,
POLL_TIMEOUT, DROP_PENDING_UPDATES, ALLOWED_UPDATES,
DATABASE_PATH, LOG_LEVEL
)
from version import BOT_VERSION
from database import Database
from lichess_api import LichessAPI
from formatters import StatsFormatter
from i18n import t, format_period
from message_counters import MessageCounters
from notifications import AdminNotifier
from onboarding import link_player
from periodic import PeriodicMonitor
import time
# Configure logging (level from LOG_LEVEL env, INFO by default)
logging.basicConfig(
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
level=getattr(logging, LOG_LEVEL, logging.INFO)
)
# httpx logs every Telegram API call at INFO with the full URL, i.e. the bot
# token in plain text, one line per getUpdates every 30s. Keep only its warnings.
logging.getLogger("httpx").setLevel(logging.WARNING)
logger = logging.getLogger(__name__)
# Conversation states
WAITING_FOR_TOKEN, WAITING_FOR_USERNAME = range(2)
class LichessBot:
def __init__(self):
self.db = Database()
self.lichess_api = LichessAPI()
self.counters = MessageCounters() # Message counters
self.notifier = AdminNotifier(self.db)
self.monitor = PeriodicMonitor(self.db, self.lichess_api, self.counters, self.notifier)
self.application = None # Will be set when application is created
async def test_admin_notify(self, update: Update, context: ContextTypes.DEFAULT_TYPE):
"""Manual test to verify admin notifications delivery path. Admin-only: anyone else gets no reply."""
user = update.effective_user
admin_chat_id = self.db.get_admin_chat_id()
if admin_chat_id is None or update.effective_chat is None or update.effective_chat.id != admin_chat_id:
return
try:
await self.notifier.notify_new_player("test_player_notify", user.id, user.username if user else None)
await update.message.reply_text("✅ Admin notification test triggered.")
except Exception as e:
logger.error(f"test_admin_notify failed: {e}")
await update.message.reply_text(f"❌ Failed to trigger admin notification: {e}")
def get_user_language_from_update(self, update: Update) -> str:
"""Get user's selected bot language from database"""
user = update.effective_user
if user:
# Update user info in database (this will auto-detect language for new users)
self.db.add_or_get_telegram_user(
user_id=user.id,
username=user.username,
first_name=user.first_name,
last_name=user.last_name,
language_code=user.language_code
)
# Get user's selected bot language from database
return self.db.get_user_language(user.id)
return 'en'
async def start(self, update: Update, context: ContextTypes.DEFAULT_TYPE):
"""Start command handler"""
logger.info(f"📝 start() method called for user {update.effective_user.id}")
# Register user in database
user = update.effective_user
lang_code = user.language_code if user else None
logger.info(f"User info: id={user.id}, username={user.username}, lang_code={lang_code}")
is_new_user = self.db.add_or_get_telegram_user(
user_id=user.id,
username=user.username,
first_name=user.first_name,
last_name=user.last_name,
language_code=lang_code
)
# Notify admin bot about new user
if is_new_user:
try:
await self.notifier.notify_new_user(
user_id=user.id,
username=user.username,
first_name=user.first_name
)
except Exception as e:
logger.error(f"Failed to notify admin about new user: {e}")
import traceback
logger.error(traceback.format_exc())
lang = self.get_user_language_from_update(update)
start_msg = t('start_message', lang)
await update.message.reply_text(start_msg)
self.counters.increment('start')
async def help_command(self, update: Update, context: ContextTypes.DEFAULT_TYPE):
"""Help command handler"""
lang = self.get_user_language_from_update(update)
help_msg = t('help_message', lang)
await update.message.reply_text(help_msg)
async def start_and_addgamer(self, update: Update, context: ContextTypes.DEFAULT_TYPE):
"""Start command that shows welcome message and starts addgamer conversation"""
try:
# Clear any existing conversation state
if context and hasattr(context, "user_data"):
context.user_data.clear()
# Run the regular start command
await self.start(update, context)
# Start addgamer conversation
await self.addgamer_start(update, context)
except Exception as e:
logger.error(f"Error in start_and_addgamer: {e}")
import traceback
logger.error(traceback.format_exc())
try:
await update.message.reply_text(f"Error: {e}")
except:
pass
async def addgamer_start(self, update: Update, context: ContextTypes.DEFAULT_TYPE):
"""Start addgamer command - show menu with options"""
user_id = update.effective_user.id
logger.info(f"addgamer_start called for user {user_id}")
lang = self.get_user_language_from_update(update)
# Mark that we're awaiting a username right away: the menu below is shown
# so a user typing the name directly (without tapping a button) is handled
# too, instead of being silently ignored by handle_username.
if context and hasattr(context, "user_data"):
context.user_data['awaiting_addgamer_username'] = True
try:
keyboard = [
[
InlineKeyboardButton(
text=t('addgamer_btn_add', lang),
callback_data="addgamer_add"
)
],
[
InlineKeyboardButton(
text=t('addgamer_btn_how', lang),
callback_data="addgamer_how"
)
],
]
reply_markup = InlineKeyboardMarkup(keyboard)
await update.message.reply_text(
t('addgamer_menu', lang),
reply_markup=reply_markup
)
logger.info(f"Addgamer menu sent to user {user_id}")
except Exception as e:
logger.error(f"Error sending addgamer menu: {e}")
import traceback
logger.error(traceback.format_exc())
try:
await update.message.reply_text(t('addgamer_menu_error', lang))
except Exception as e2:
logger.error(f"Failed to send addgamer menu error message: {e2}")
# No conversation state returned; handler-based flow
return
async def addgamer_show_prompt(self, update: Update, context: ContextTypes.DEFAULT_TYPE):
"""Callback: show username prompt after user presses 'Add player'"""
query = update.callback_query
await query.answer()
user_id = query.from_user.id
logger.info(f"addgamer_show_prompt called for user {user_id}")
# Clear previous state and mark that we're waiting for username
if context and hasattr(context, "user_data"):
context.user_data.clear()
context.user_data['awaiting_addgamer_username'] = True
# Language from DB (for callbacks)
if update.effective_user:
self.db.add_or_get_telegram_user(
user_id=update.effective_user.id,
username=update.effective_user.username,
first_name=update.effective_user.first_name,
last_name=update.effective_user.last_name,
language_code=update.effective_user.language_code
)
lang = self.db.get_user_language(user_id)
await query.message.reply_text(
t('addgamer_prompt', lang),
parse_mode='HTML'
)
logger.info(f"Addgamer prompt (from button) sent to user {user_id}")
# Count real start of username input flow
self.counters.increment('addgamer')
async def addgamer_show_help(self, update: Update, context: ContextTypes.DEFAULT_TYPE):
"""Callback: show how to find username on Lichess (with images)"""
query = update.callback_query
if not query or not query.message:
logger.error("addgamer_show_help: Invalid query or message")
return
await query.answer()
user_id = query.from_user.id
logger.info(f"addgamer_show_help called for user {user_id}")
# Language from DB (for callbacks)
if update.effective_user:
self.db.add_or_get_telegram_user(
user_id=update.effective_user.id,
username=update.effective_user.username,
first_name=update.effective_user.first_name,
last_name=update.effective_user.last_name,
language_code=update.effective_user.language_code
)
lang = self.db.get_user_language(user_id)
# Определяем имя файла картинки в зависимости от языка
# Для русской локализации - helpRU.jpeg, для английской - helpEN.jpeg
image_filename = "helpRU.jpeg" if lang == 'ru' else "helpEN.jpeg"
# Определяем путь к картинке (она находится в той же папке, что и bot.py)
bot_dir = Path(__file__).resolve().parent
image_path = bot_dir / image_filename
# Пробуем альтернативные пути, если основной не найден
possible_paths = [
image_path, # В папке бота
bot_dir.parent / image_filename, # В корне проекта
]
# Ищем существующий файл
found_path = None
for candidate in possible_paths:
if candidate and candidate.exists():
found_path = candidate
logger.info(f"✅ Found {image_filename} at: {found_path}")
break
if not found_path or not found_path.exists():
error_msg = f"❌ Error: Could not find {image_filename}\n\nChecked paths:\n"
for path in possible_paths:
exists = path.exists() if path else False
error_msg += f" • {path} (exists: {exists})\n"
logger.error(error_msg)
await query.message.reply_text(f"❌ Error: Could not find image file. Please check bot logs.")
return
try:
logger.info(f"Sending help image: {found_path} (language: {lang})")
with open(found_path, "rb") as img:
await query.message.reply_photo(photo=img)
logger.info(f"Successfully sent help image to user {user_id}")
# Устанавливаем флаг ожидания username, чтобы пользователь мог ввести его после просмотра картинки
if context and hasattr(context, "user_data"):
context.user_data['awaiting_addgamer_username'] = True
# Отправляем текст с запросом username
await query.message.reply_text(
t('addgamer_prompt', lang),
parse_mode='HTML'
)
# Считаем это началом процесса добавления игрока
self.counters.increment('addgamer')
except Exception as e:
logger.error(f"Error sending lichess help images: {e}")
import traceback
logger.error(traceback.format_exc())
try:
await query.message.reply_text(f"❌ Error sending images: {e}")
except Exception as e2:
logger.error(f"Failed to send error message: {e2}")
async def addtoken_start(self, update: Update, context: ContextTypes.DEFAULT_TYPE):
"""Start addtoken command - token required"""
# Reset any existing conversation state
if context and hasattr(context, "user_data"):
context.user_data.clear()
lang = self.get_user_language_from_update(update)
await update.message.reply_text(t('addtoken_prompt', lang))
self.counters.increment('addtoken')
return WAITING_FOR_TOKEN
async def handle_token(self, update: Update, context: ContextTypes.DEFAULT_TYPE):
"""Handle token input for /addtoken"""
token = update.message.text.strip()
user_id = update.effective_user.id
logger.info(f"Processing token for user {user_id}, token prefix: {token[:10]}...")
# Get username from token
profile = await self.lichess_api.get_user_profile(token)
logger.info(f"Profile response: {profile is not None}")
if profile:
username = profile.get('username')
if username:
# Check if this gamer is already tracked by this user
user_gamers = self.db.get_user_gamers(user_id)
existing_gamer = next((g for g in user_gamers if g['username'].lower() == username.lower()), None)
lang = self.get_user_language_from_update(update)
if existing_gamer:
# Update token for existing gamer
self.db.add_user_gamer(user_id, existing_gamer['id'], token)
await update.message.reply_text(
t('token_added', lang, username=username)
)
# Always notify admin about link/added player
try:
user_obj = update.effective_user
await self.notifier.notify_new_player(username, user_id, user_obj.username if user_obj else None)
except Exception as e:
logger.error(f"Admin notify failed after token update: {e}")
else:
# Add new gamer and link with token (shared with /addgamer, see onboarding.py)
result = await link_player(self, user_id, update.effective_user, username, token)
if not result.added:
# Pair appeared between the check above and the insert; the token is stored
await update.message.reply_text(
t('token_added', lang, username=username)
)
else:
await update.message.reply_text(
t('gamer_added_with_token', lang, username=username)
)
return ConversationHandler.END
else:
lang = self.get_user_language_from_update(update)
await update.message.reply_text(
t('token_username_error', lang)
)
return WAITING_FOR_TOKEN
else:
lang = self.get_user_language_from_update(update)
await update.message.reply_text(
t('invalid_token', lang)
)
return WAITING_FOR_TOKEN
async def handle_username(self, update: Update, context: ContextTypes.DEFAULT_TYPE):
"""Handle username input for /addgamer"""
user_id = update.effective_user.id
# Only treat the text as a username if we are awaiting one. Otherwise don't
# stay silent (that read as "the bot is broken" and hid the whole onboarding
# drop-off from the logs): say what to do instead.
if not (context and hasattr(context, "user_data") and context.user_data.get('awaiting_addgamer_username')):
lang = self.get_user_language_from_update(update)
logger.info(f"Text from user {user_id} outside of /addgamer flow, replying with hint: {update.message.text[:60]!r}")
await update.message.reply_text(t('text_not_expected', lang))
return
username = update.message.text.strip()
lang = self.get_user_language_from_update(update)
if not username:
await update.message.reply_text(
t('empty_username', lang)
)
return
# Check if user exists on Lichess
logger.info(f"addgamer: user {user_id} entered username {username!r}")
lichess_user = await self.lichess_api.check_user_exists(username)
if lichess_user is None:
# Transient API failure (rate limit, network error, unexpected status) —
# don't tell the user the name is wrong, it may well be valid.
await update.message.reply_text(
t('lichess_temporarily_unavailable', lang) + '\n\n' + t('addgamer_prompt', lang),
parse_mode='HTML'
)
return
if not lichess_user:
logger.info(f"addgamer: username {username!r} not found on Lichess (user {user_id})")
await update.message.reply_text(
t('user_not_found', lang, username=username) + '\n\n' + t('addgamer_prompt', lang),
parse_mode='HTML'
)
return
if lichess_user.get('disabled'):
# Lichess answers 200 for closed accounts too; they never have new games,
# tracking one is just a wasted request every period.
logger.info(f"addgamer: username {username!r} is a closed Lichess account (user {user_id})")
await update.message.reply_text(
t('user_closed', lang, username=username) + '\n\n' + t('addgamer_prompt', lang),
parse_mode='HTML'
)
return
# Store the canonical spelling Lichess uses, not whatever case the user typed
username = lichess_user['username']
# Check if this gamer is already tracked by this user
user_gamers = self.db.get_user_gamers(user_id)
existing_gamer = next((g for g in user_gamers if g['username'].lower() == username.lower()), None)
if existing_gamer:
# Player is already being tracked by this user
await update.message.reply_text(
t('gamer_already_added', lang, username=username) + '\n\n' + t('addgamer_prompt', lang),
parse_mode='HTML'
)
# Keep awaiting flag - don't clear it, so user can try again
return
# Add gamer to database (without token) and link it to this user
# (shared with /addtoken, see onboarding.py)
result = await link_player(self, user_id, update.effective_user, username, None)
# If add_user_gamer returned False, it means the pair already exists (shouldn't happen after our check, but just in case)
if not result.added:
await update.message.reply_text(
t('gamer_already_added', lang, username=username) + '\n\n' + t('addgamer_prompt', lang),
parse_mode='HTML'
)
# Keep awaiting flag - don't clear it, so user can try again
return
lang = self.get_user_language_from_update(update)
await update.message.reply_text(
t('gamer_added', lang, username=username),
parse_mode='HTML'
)
# Clear awaiting flag
try:
context.user_data['awaiting_addgamer_username'] = False
except Exception:
pass
return
async def getgamers(self, update: Update, context: ContextTypes.DEFAULT_TYPE):
"""Get all gamers for the current user and allow selection"""
user_id = update.effective_user.id
gamers = self.db.get_user_gamers(user_id)
logger.info(f"getgamers: user_id={user_id}, found {len(gamers)} gamers")
lang = self.get_user_language_from_update(update)
if not gamers:
logger.info(f"getgamers: No gamers found for user {user_id}, sending no_gamers message")
await update.message.reply_text(t('no_gamers', lang))
self.counters.increment('getgamers')
return
logger.info(f"getgamers: Proceeding with {len(gamers)} gamers for user {user_id}")
self.counters.increment('getgamers')
# Show loading message
loading_msg = await update.message.reply_text(t('loading_ratings', lang))
# Prepare data for each gamer
gamers_data = []
for i, gamer in enumerate(gamers):
try:
logger.info(f"Processing gamer {i+1}/{len(gamers)}: {gamer['username']} (ID: {gamer['id']})")
username = gamer['username']
# Get user ratings from Lichess API
logger.debug(f"Requesting ratings for {username}")
ratings_data = await self.lichess_api.get_user_ratings(username)
logger.debug(f"Received ratings for {username}: {ratings_data is not None}")
# Add delay between requests to avoid rate limiting
if i < len(gamers) - 1: # Don't sleep after the last one
await asyncio.sleep(0.5) # 500ms delay between requests
if ratings_data and 'perfs' in ratings_data:
perfs = ratings_data['perfs']
bullet_rating = perfs.get('bullet', {}).get('rating', 'N/A')
blitz_rating = perfs.get('blitz', {}).get('rating', 'N/A')
rapid_rating = perfs.get('rapid', {}).get('rating', 'N/A')
else:
bullet_rating = blitz_rating = rapid_rating = 'N/A'
# Add period information if period > 0
period_minutes = gamer.get('period_minutes', 0)
period_suffix = t('period_minutes_suffix', lang)
period_text = f" · {period_minutes}{period_suffix}" if period_minutes > 0 else ""
gamers_data.append({
'id': gamer['id'],
'username': username,
'bullet': bullet_rating,
'blitz': blitz_rating,
'rapid': rapid_rating,
'period': period_text
})
logger.info(f"Successfully added gamer {username} to gamers_data (total: {len(gamers_data)})")
except Exception as e:
logger.error(f"Error processing gamer {gamer.get('username', 'unknown')}: {e}")
import traceback
logger.error(f"Traceback: {traceback.format_exc()}")
# Still add the gamer with N/A ratings
period_minutes = gamer.get('period_minutes', 0)
period_suffix = t('period_minutes_suffix', lang)
period_text = f" · {period_minutes}{period_suffix}" if period_minutes > 0 else ""
gamers_data.append({
'id': gamer['id'],
'username': gamer['username'],
'bullet': 'N/A',
'blitz': 'N/A',
'rapid': 'N/A',
'period': period_text
})
logger.info(f"Added gamer {gamer['username']} with N/A ratings due to error")
logger.info(f"getgamers: prepared {len(gamers_data)} gamers for display")
# Check if we have any gamers to display
if not gamers_data:
logger.warning(f"getgamers: No gamers data prepared, but gamers list was not empty. This should not happen.")
try:
await loading_msg.delete()
except:
pass
await update.message.reply_text(t('no_gamers', lang))
return
gamers_table = StatsFormatter.format_gamers_table(gamers_data)
gamers_text = t('select_active_gamer', lang) + "<pre>" + gamers_table + "</pre>"
logger.info(f"getgamers: message length: {len(gamers_text)} characters")
# Edit the loading message with the results (no keyboard)
try:
await loading_msg.edit_text(
gamers_text,
parse_mode='HTML'
)
except Exception as e:
logger.error(f"Error editing message: {e}")
# If edit fails, delete the loading message and send a new one
try:
await loading_msg.delete()
except:
pass
await update.message.reply_text(
gamers_text,
parse_mode='HTML'
)
logger.info(f"getgamers: Completed successfully for user {user_id}, displayed {len(gamers_data)} gamers")
async def select_gamer(self, update: Update, context: ContextTypes.DEFAULT_TYPE):
"""Handle gamer selection"""
query = update.callback_query
await query.answer()
user_id = query.from_user.id
gamer_id = int(query.data.split('_')[1])
# Get user gamers to find the selected one
gamers = self.db.get_user_gamers(user_id)
selected_gamer = next((g for g in gamers if g['id'] == gamer_id), None)
# Для callback query обновляем язык пользователя если есть в update
if update.effective_user:
self.db.add_or_get_telegram_user(
user_id=update.effective_user.id,
username=update.effective_user.username,
first_name=update.effective_user.first_name,
last_name=update.effective_user.last_name,
language_code=update.effective_user.language_code
)
lang = self.db.get_user_language(user_id)
if selected_gamer:
# Set active gamer for this user
self.db.set_user_active_gamer(user_id, gamer_id)
await query.edit_message_text(
t('active_gamer_set', lang, username=selected_gamer['username'])
)
else:
await query.edit_message_text(t('gamer_not_found', lang))
async def delgamer(self, update: Update, context: ContextTypes.DEFAULT_TYPE):
"""Show gamers list for deletion"""
user_id = update.effective_user.id
gamers = self.db.get_user_gamers(user_id)
lang = self.get_user_language_from_update(update)
if not gamers:
await update.message.reply_text(t('no_gamers_to_delete', lang))
self.counters.increment('delgamer')
return
self.counters.increment('delgamer')
# Show loading message
loading_msg = await update.message.reply_text(t('loading_gamers', lang))
# Create text message with stats
text_lines = []
keyboard = []
for i, gamer in enumerate(gamers):
status = "🟢" if gamer['is_active'] else "⚪"
username = gamer['username']
# Get user ratings from Lichess API
ratings_data = await self.lichess_api.get_user_ratings(username)
# Add delay between requests to avoid rate limiting
if i < len(gamers) - 1: # Don't sleep after the last one
await asyncio.sleep(0.5) # 500ms delay between requests
if ratings_data and 'perfs' in ratings_data:
perfs = ratings_data['perfs']
bullet_rating = perfs.get('bullet', {}).get('rating', 'N/A')
blitz_rating = perfs.get('blitz', {}).get('rating', 'N/A')
rapid_rating = perfs.get('rapid', {}).get('rating', 'N/A')
else:
bullet_rating = blitz_rating = rapid_rating = 'N/A'
period_minutes = gamer.get('period_minutes', 0)
period_suffix = t('period_minutes_suffix', lang)
period_text = f" · {period_minutes}{period_suffix}" if period_minutes > 0 else ""
text_lines.append(
f"{status} <b>{username}</b> "
f"⚡ {bullet_rating} 🔥 {blitz_rating} 🐇 {rapid_rating}{period_text}"
)
# Add delete button
keyboard.append([InlineKeyboardButton(
text=f"🗑️ {username}",
callback_data=f"delete_{gamer['id']}"
)])
gamers_text = t('select_gamer_to_delete', lang) + "\n".join(text_lines)
reply_markup = InlineKeyboardMarkup(keyboard)
# Edit the loading message with the results
try:
await loading_msg.edit_text(
gamers_text,
parse_mode='HTML',
reply_markup=reply_markup
)
except Exception as e:
logger.error(f"Error editing message: {e}")
try:
await loading_msg.delete()
except:
pass
await update.message.reply_text(
gamers_text,
parse_mode='HTML',
reply_markup=reply_markup
)
async def handle_delete_gamer(self, update: Update, context: ContextTypes.DEFAULT_TYPE):
"""Handle gamer deletion"""
query = update.callback_query
await query.answer()
user_id = query.from_user.id
gamer_id = int(query.data.split('_')[1])
# Get gamer info before deletion
gamers = self.db.get_user_gamers(user_id)
gamer_to_delete = next((g for g in gamers if g['id'] == gamer_id), None)
# Для callback query получаем язык из БД
if update.effective_user:
self.db.add_or_get_telegram_user(
user_id=update.effective_user.id,
username=update.effective_user.username,
first_name=update.effective_user.first_name,
last_name=update.effective_user.last_name,
language_code=update.effective_user.language_code
)
lang = self.db.get_user_language(user_id)
if gamer_to_delete:
username = gamer_to_delete['username']
was_active = gamer_to_delete.get('is_active', False)
total_gamers_before = len(gamers)
deleted = self.db.remove_user_gamer(user_id, gamer_id)
if deleted:
# Check how many gamers remain after deletion
remaining_gamers = self.db.get_user_gamers(user_id)
remaining_count = len(remaining_gamers)
# Determine which message to show
if remaining_count == 0:
# Last gamer deleted
message = t('last_gamer_deleted', lang, username=username)
elif was_active:
# Active gamer deleted but there are other gamers
message = t('active_gamer_deleted', lang, username=username)
else:
# Regular deletion
message = t('gamer_deleted', lang, username=username)
await query.edit_message_text(
message,
parse_mode='HTML'
)
else:
await query.edit_message_text(t('delete_failed', lang))
else:
await query.edit_message_text(t('gamer_not_found', lang))
async def get_stats(self, update: Update, context: ContextTypes.DEFAULT_TYPE, period: str):
"""Get statistics for a period - shows stats for all players with activity"""
user_id = update.effective_user.id
logger.info(f"🔍 get_stats called: user_id={user_id}, period={period}")
# Get all gamers for this user
gamers = self.db.get_user_gamers(user_id)
logger.info(f"🔍 Found {len(gamers)} gamers for user {user_id}: {[g['username'] for g in gamers]}")
lang = self.get_user_language_from_update(update)
if not gamers:
await update.message.reply_text(
t('no_gamers', lang)
)
return
# Process each gamer
has_any_activity = False
for i, gamer in enumerate(gamers):
username = gamer['username']
logger.info(f"🔍 Processing gamer {i+1}/{len(gamers)}: {username} for period {period}")
# Send message about processing this player
processing_msg = None
try:
processing_msg = await update.message.reply_text(t('stats_player_processing', lang, username=username), parse_mode='HTML')
except Exception:
pass
# Get stats based on period
try:
logger.info(f"🔍 Making API request for {username}, period={period}")
if period == "today":
data = await self.lichess_api.get_today_stats(username)
elif period == "yesterday":
data = await self.lichess_api.get_yesterday_stats(username)
elif period == "week":
data = await self.lichess_api.get_week_stats(username)
else:
await update.message.reply_text(t('unknown_period', lang))
return
logger.info(f"🔍 API response for {username}: data={data is not None}, type={type(data)}")
if data:
logger.info(f"🔍 API response keys: {data.keys() if isinstance(data, dict) else 'not a dict'}")
if isinstance(data, dict) and 'message' in data:
logger.info(f"🔍 API message: {data.get('message')}")
except Exception as e:
logger.error(f"❌ Error getting stats for {username}: {e}")
import traceback
logger.error(traceback.format_exc())
data = None
# Delete processing message
if processing_msg:
try:
await processing_msg.delete()
except Exception:
pass
# Check if there's activity
has_activity = False
if data:
if data.get('data'):
api_data = data.get('data', {})
tasks = api_data.get('tasks', {})
games = api_data.get('games', {})
logger.info(f"🔍 Activity check for {username}: tasks={tasks}, games={games}")
# Check for puzzles activity
if tasks and tasks.get('total', 0) > 0:
has_activity = True
logger.info(f"✅ {username} has puzzles activity: {tasks.get('total')}")
# Check for games activity
if games:
for game_type, game_data in games.items():
if game_data and game_data.get('games_played', 0) > 0:
has_activity = True
logger.info(f"✅ {username} has {game_type} activity: {game_data.get('games_played')} games")
break
else:
# API вернул ответ, но без данных (нет активности)
message = data.get('message', 'No message')
# Filter out old "No active player" messages - this functionality is deprecated
if 'No active player' in message or 'Нет активного игрока' in message or 'active player' in message.lower() or 'активного игрока' in message.lower():
logger.info(f"ℹ️ API response for {username}: filtered out deprecated 'No active player' message")
message = None
else:
logger.info(f"ℹ️ API response for {username}: {message} (no activity data)")
else:
logger.warning(f"⚠️ No response data for {username}: data is None")
# Only send response if there's activity
if has_activity:
# Дополнительный, параллельный запрос за реальными партиями периода —
# только чтобы добавить точность (accuracy) и, для today/yesterday,
# построчный разбор партий. Шапку (данные из /activity) не трогаем:
# при любой ошибке здесь просто не покажем точность.
accuracy_extra = None
try:
now_dt = datetime.now()
if period == "today":
since_dt = now_dt.replace(hour=0, minute=0, second=0, microsecond=0)
until_dt = now_dt
want_rows = True
elif period == "yesterday":
today_midnight = now_dt.replace(hour=0, minute=0, second=0, microsecond=0)
since_dt = today_midnight - timedelta(days=1)
until_dt = today_midnight
want_rows = True
else: # week — то же окно (today-6 .. now), что использует _is_date_in_range(days_back=7)
since_dt = now_dt.replace(hour=0, minute=0, second=0, microsecond=0) - timedelta(days=6)
until_dt = now_dt
want_rows = False
accuracy_extra = await self.lichess_api.get_games_period(
username,
int(since_dt.timestamp() * 1000),
int(until_dt.timestamp() * 1000),
rated_only=True,
include_games=want_rows,
priority="interactive"
)
except Exception as e:
logger.warning(f"⚠️ Supplementary accuracy fetch failed for {username}/{period}: {e}")
accuracy_extra = None
formatted_response = StatsFormatter.format_stats_response(data, username, period, lang, accuracy_extra=accuracy_extra)
await update.message.reply_text(formatted_response, parse_mode='Markdown')
has_any_activity = True
else:
logger.info(f"ℹ️ No activity found for {username}, skipping response")
# Add delay between requests to avoid rate limiting
if i < len(gamers) - 1:
await asyncio.sleep(1.0)
# If no activity for any player
if not has_any_activity:
await update.message.reply_text(t('no_activity', lang))
# Increment counter for the period command
if period == "today":
self.counters.increment('today')
elif period == "yesterday":
self.counters.increment('yesterday')
elif period == "week":
self.counters.increment('week')
async def today(self, update: Update, context: ContextTypes.DEFAULT_TYPE):
"""Today command"""
await self.get_stats(update, context, "today")
async def yesterday(self, update: Update, context: ContextTypes.DEFAULT_TYPE):
"""Yesterday command"""
await self.get_stats(update, context, "yesterday")
async def week(self, update: Update, context: ContextTypes.DEFAULT_TYPE):
"""Week command"""
await self.get_stats(update, context, "week")
async def support(self, update: Update, context: ContextTypes.DEFAULT_TYPE):
"""Support command - show contact information"""
lang = self.get_user_language_from_update(update)
support_msg = t('support_message', lang, version=BOT_VERSION)
await update.message.reply_text(support_msg, parse_mode='HTML')
self.counters.increment('support')
async def last_year_or_1000games(self, update: Update, context: ContextTypes.DEFAULT_TYPE):
"""Get last year stats or last 1000 rated games for all players with activity"""
user_id = update.effective_user.id
# Get all gamers for this user
gamers = self.db.get_user_gamers(user_id)
lang = self.get_user_language_from_update(update)
if not gamers:
await update.message.reply_text(
t('no_gamers', lang)
)
return
now_ms = int(time.time() * 1000)
year_ms = 365 * 24 * 3600 * 1000
since_ms = now_ms - year_ms
has_any_activity = False
# Process each gamer sequentially
for i, gamer in enumerate(gamers):
username = gamer['username']
try:
# Send message about processing this player
processing_msg = None
try:
processing_msg = await update.message.reply_text(t('last_year_1000_player_processing', lang, username=username), parse_mode='HTML')
except Exception:
pass
# Get data for this player
# User-initiated command: jump ahead of the periodic backlog in the
# shared-token queue instead of waiting it out as "background".
data = await self.lichess_api.get_games_period(username, since_ms, now_ms, rated_only=True, priority="interactive")
# Delete processing message
if processing_msg:
try:
await processing_msg.delete()
except Exception:
pass
if data:
# Check if there's activity (games_count > 0)
games_count = data.get('games_count', 0)
if games_count > 0:
# Format and send immediately
text = StatsFormatter.format_last_year_or_1000(data, username, lang)
await update.message.reply_text(text, parse_mode='Markdown')
has_any_activity = True
# Wait 3 seconds before next request (except after the last one)
if i < len(gamers) - 1:
await asyncio.sleep(3.0)
except Exception as e:
logger.error(f"/lastYear_or_1000games error for {username}: {e}")
await update.message.reply_text(f"Error for {username}: {e}")
# If no activity for any player
if not has_any_activity:
await update.message.reply_text(t('no_activity', lang))
self.counters.increment('last_year_1000')
async def setperiod(self, update: Update, context: ContextTypes.DEFAULT_TYPE):
"""Set period command - first select gamer, then select period"""
user_id = update.effective_user.id
# Get all gamers for this user
gamers = self.db.get_user_gamers(user_id)
lang = self.get_user_language_from_update(update)
if not gamers:
await update.message.reply_text(t('no_gamers', lang))
self.counters.increment('setperiod')
return
# Create keyboard with gamers and their periods
keyboard = []
for gamer in gamers:
username = gamer['username']
period_minutes = gamer.get('period_minutes', 0)
# Format period text
if period_minutes == 0:
period_text = "—"
elif period_minutes < 60:
period_text = f"{period_minutes}m"
elif period_minutes == 60:
period_text = "1h"
else:
hours = period_minutes // 60
period_text = f"{hours}h"
keyboard.append([InlineKeyboardButton(
text=f"{username} · {period_text}",
callback_data=f"select_gamer_period_{gamer['id']}"
)])
reply_markup = InlineKeyboardMarkup(keyboard)
await update.message.reply_text(
t('select_player_period', lang),
reply_markup=reply_markup
)
self.counters.increment('setperiod')
async def select_gamer_for_period(self, update: Update, context: ContextTypes.DEFAULT_TYPE):
"""Handle gamer selection for period setting"""
query = update.callback_query
await query.answer()
logger.info(f"select_gamer_for_period called with callback_data: {query.data}")
user_id = query.from_user.id
# Parse callback_data: select_gamer_period_{gamer_id}
try:
gamer_id = int(query.data.split('_')[-1])
logger.info(f"Parsed gamer_id: {gamer_id}")
except (ValueError, IndexError) as e:
logger.error(f"Error parsing gamer_id from callback_data '{query.data}': {e}")
await query.edit_message_text("❌ Error: Invalid player selection")
return
# Get gamer info
gamers = self.db.get_user_gamers(user_id)
selected_gamer = None
for gamer in gamers:
if gamer['id'] == gamer_id:
selected_gamer = gamer
break
if not selected_gamer:
await query.edit_message_text("❌ Player not found")
return
# Для callback query получаем язык из БД
if update.effective_user:
self.db.add_or_get_telegram_user(
user_id=update.effective_user.id,
username=update.effective_user.username,
first_name=update.effective_user.first_name,
last_name=update.effective_user.last_name,
language_code=update.effective_user.language_code
)
lang = self.db.get_user_language(user_id)
# Show period options for selected gamer
keyboard = []
for period in PERIOD_OPTIONS:
if period == 0:
button_text = t('disable_notifications', lang)
else:
button_text = f"⏰ {format_period(period, lang)}"
keyboard.append([InlineKeyboardButton(
button_text,
callback_data=f"period_{gamer_id}_{period}"
)])
reply_markup = InlineKeyboardMarkup(keyboard)
await query.edit_message_text(
t('select_period', lang, username=selected_gamer['username']),
reply_markup=reply_markup,
parse_mode='HTML'
)
async def select_period(self, update: Update, context: ContextTypes.DEFAULT_TYPE):
"""Handle period selection"""
query = update.callback_query
await query.answer()
user_id = query.from_user.id
# Parse callback data: period_{gamer_id}_{period}
parts = query.data.split('_')
gamer_id = int(parts[1])
period = int(parts[2])
# Get gamer info
gamers = self.db.get_user_gamers(user_id)
selected_gamer = None
for gamer in gamers:
if gamer['id'] == gamer_id:
selected_gamer = gamer
break
if not selected_gamer:
await query.edit_message_text("❌ Player not found")
return
# Для callback query получаем язык из БД
if update.effective_user:
self.db.add_or_get_telegram_user(
user_id=update.effective_user.id,
username=update.effective_user.username,
first_name=update.effective_user.first_name,
last_name=update.effective_user.last_name,
language_code=update.effective_user.language_code
)
lang = self.db.get_user_language(user_id)
# Set period for this user-gamer pair
self.db.set_user_gamer_period(user_id, gamer_id, period)
if period == 0:
# Отключаем мониторинг: чистим чекпоинт, чтобы при повторном включении
# не было catch-up на потенциально очень старое (устаревшее) окно.
self.db.clear_period_checkpoint(user_id, gamer_id)
await self.monitor.stop_periodic_task(gamer_id, user_id)
await query.edit_message_text(
t('notifications_disabled', lang, username=selected_gamer['username'])
)
else:
await query.edit_message_text(
t('period_set_confirm', lang, period=format_period(period, lang), username=selected_gamer['username'])
)
# Start periodic task for this gamer (send to user's personal messages)
await self.monitor.start_periodic_task(selected_gamer, user_id, period)
async def set_lang(self, update: Update, context: ContextTypes.DEFAULT_TYPE):
"""Show language selection menu"""
user = update.effective_user
if not user:
await update.message.reply_text("❌ Failed to get user information")
return
# Get current language to show menu in user's language
lang = self.get_user_language_from_update(update)
# Create keyboard with language buttons
keyboard = [
[
InlineKeyboardButton("🇬🇧 English", callback_data="lang_en"),
InlineKeyboardButton("🇷🇺 Русский", callback_data="lang_ru")
]
]
reply_markup = InlineKeyboardMarkup(keyboard)
await update.message.reply_text(
t('select_language', lang),
reply_markup=reply_markup,
parse_mode='HTML'
)
async def handle_language_selection(self, update: Update, context: ContextTypes.DEFAULT_TYPE):
"""Handle language selection callback"""
query = update.callback_query
await query.answer()
user = query.from_user
user_id = user.id
selected_lang = query.data.split('_')[1] # 'en' or 'ru'
# Update user info in database
self.db.add_or_get_telegram_user(
user_id=user_id,
username=user.username,
first_name=user.first_name,
last_name=user.last_name,
language_code=user.language_code
)
# Save selected language to database
success = self.db.set_user_language(user_id, selected_lang)
if success:
# Get message in selected language
message = t('language_set_ru', selected_lang) if selected_lang == 'ru' else t('language_set_en', selected_lang)
await query.edit_message_text(message)
else:
# Use current language for error message
lang = self.db.get_user_language(user_id)
error_msg = "❌ Не удалось установить язык" if lang == 'ru' else "❌ Failed to set language"
await query.edit_message_text(error_msg)
async def profile(self, update: Update, context: ContextTypes.DEFAULT_TYPE):
"""Show list of players to view their profiles"""
user_id = update.effective_user.id
gamers = self.db.get_user_gamers(user_id)
lang = self.get_user_language_from_update(update)
if not gamers:
await update.message.reply_text(t('no_gamers', lang))
return
# Create keyboard with player buttons
keyboard = []
for gamer in gamers:
username = gamer['username']
keyboard.append([
InlineKeyboardButton(
username,
callback_data=f"profile_{gamer['id']}"
)
])
reply_markup = InlineKeyboardMarkup(keyboard)
await update.message.reply_text(
t('select_player_profile', lang),
reply_markup=reply_markup,
parse_mode='HTML'
)
async def handle_profile_selection(self, update: Update, context: ContextTypes.DEFAULT_TYPE):
"""Handle profile selection callback - send profile link"""
query = update.callback_query
await query.answer()
user_id = query.from_user.id
gamer_id = int(query.data.split('_')[1])
# Get gamer info
gamers = self.db.get_user_gamers(user_id)
selected_gamer = next((g for g in gamers if g['id'] == gamer_id), None)
if not selected_gamer:
lang = self.db.get_user_language(user_id)
await query.edit_message_text(t('gamer_not_found', lang))
return
username = selected_gamer['username']
profile_url = f"https://lichess.org/@/{username}"
lang = self.db.get_user_language(user_id)
# Send profile link
await query.message.reply_text(
f"🔗 <a href=\"{profile_url}\">{profile_url}</a>",
parse_mode='HTML'
)
# Edit original message to show confirmation
await query.edit_message_text(
t('profile_link_sent', lang),
parse_mode='HTML'
)
async def log_incoming_update(self, update: Update, context: ContextTypes.DEFAULT_TYPE):
"""One INFO line per incoming update (runs before all other handlers, never blocks them)."""
user = update.effective_user
uid = user.id if user else None
if update.callback_query:
logger.info(f"⬅️ callback from user {uid}: {update.callback_query.data!r}")
elif update.message:
msg = update.message
if msg.text is not None:
logger.info(f"⬅️ text from user {uid}: {msg.text[:80]!r}")
else:
kind = next((k for k in ('photo', 'sticker', 'document', 'contact', 'voice', 'video', 'location')
if getattr(msg, k, None)), 'other')
logger.info(f"⬅️ non-text message ({kind}) from user {uid}")
else:
logger.info(f"⬅️ update of another type from user {uid}")
async def handle_non_text(self, update: Update, context: ContextTypes.DEFAULT_TYPE):
"""Photos, stickers, contacts etc. used to be ignored silently; tell the user what we accept."""
lang = self.get_user_language_from_update(update)
await update.message.reply_text(t('unsupported_message', lang))
def setup_handlers(self, application: Application):
"""Setup all handlers"""
self.application = application # Store application reference
self.monitor.application = application # periodic notifications go out via application.bot
# Group -1 runs before group 0 and does not stop it: a single log line per update
application.add_handler(TypeHandler(Update, self.log_incoming_update), group=-1)
# Conversation handler for addtoken (token required)
# Must be added BEFORE general MessageHandler to avoid conflicts
addtoken_conv = ConversationHandler(
entry_points=[CommandHandler("addtoken", self.addtoken_start)],
states={
WAITING_FOR_TOKEN: [MessageHandler(filters.TEXT & ~filters.COMMAND, self.handle_token)],
},
fallbacks=[
CommandHandler("cancel", lambda u, c: ConversationHandler.END),
CommandHandler("addtoken", self.addtoken_start) # Allow restarting conversation
],
per_chat=True,
per_user=True
)
# Add handlers - ConversationHandler must be before general MessageHandler
application.add_handler(CommandHandler("start", self.start_and_addgamer))
application.add_handler(CommandHandler("help", self.help_command))
application.add_handler(CommandHandler("addgamer", self.addgamer_start))
application.add_handler(addtoken_conv) # Add before general MessageHandler
application.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, self.handle_username))
application.add_handler(CommandHandler("getgamers", self.getgamers))
application.add_handler(CommandHandler("delgamer", self.delgamer))
application.add_handler(CommandHandler("today", self.today))
application.add_handler(CommandHandler("yesterday", self.yesterday))
application.add_handler(CommandHandler("week", self.week))
application.add_handler(CommandHandler("lastYear_or_1000games", self.last_year_or_1000games))
application.add_handler(CommandHandler("support", self.support))
application.add_handler(CommandHandler("setperiod", self.setperiod))
application.add_handler(CommandHandler("set_lang", self.set_lang))
application.add_handler(CommandHandler("profile", self.profile))
application.add_handler(CommandHandler("test_admin_notify", self.test_admin_notify))
# Callback handlers (order matters - more specific patterns first)
application.add_handler(CallbackQueryHandler(self.addgamer_show_prompt, pattern="^addgamer_add$"))
application.add_handler(CallbackQueryHandler(self.addgamer_show_help, pattern="^addgamer_how$"))
application.add_handler(CallbackQueryHandler(self.handle_language_selection, pattern="^lang_"))
application.add_handler(CallbackQueryHandler(self.handle_profile_selection, pattern="^profile_"))
application.add_handler(CallbackQueryHandler(self.select_gamer_for_period, pattern="^select_gamer_period_"))
application.add_handler(CallbackQueryHandler(self.select_gamer, pattern="^select_"))
application.add_handler(CallbackQueryHandler(self.handle_delete_gamer, pattern="^delete_"))
application.add_handler(CallbackQueryHandler(self.select_period, pattern="^period_"))
# Anything that is a private message but not text/command (photo of a profile,
# sticker, contact...) — last in group 0, so it only fires when nothing else matched
application.add_handler(MessageHandler(
filters.ChatType.PRIVATE & ~filters.TEXT & ~filters.COMMAND & ~filters.StatusUpdate.ALL,
self.handle_non_text
))
def main():
"""Main function"""
bot = LichessBot()
# Persist user_data (e.g. awaiting_addgamer_username) to disk so an in-flight
# /addgamer conversation survives a bot restart instead of silently dropping
# the next message the user sends.
persistence_path = os.path.join(os.path.dirname(DATABASE_PATH), "bot_persistence.pickle")
persistence = PicklePersistence(filepath=persistence_path)
# Create application with Long Polling configuration
application = Application.builder().token(TELEGRAM_BOT_TOKEN).persistence(persistence).build()
# Setup handlers
bot.setup_handlers(application)
# Set application reference for periodic tasks
bot.application = application
bot.monitor.application = application
# Start periodic tasks for existing gamers (will be called after application starts)
async def post_init(app):
await bot.monitor.start_existing_periodic_tasks()
application.post_init = post_init
# Add error handler
async def error_handler(update: object, context: ContextTypes.DEFAULT_TYPE) -> None:
"""Log the error with its real traceback and which update triggered it."""
# traceback.format_exc() here printed "NoneType: None": the error handler runs
# outside the except block, so the traceback has to come from context.error itself.
who = ""
if isinstance(update, Update):
user = update.effective_user
what = (update.message.text[:60] if update.message and update.message.text
else (update.callback_query.data if update.callback_query else type(update).__name__))
who = f" (user {user.id if user else None}, update: {what!r})"
logger.error(f"Exception while handling an update{who}: {context.error!r}", exc_info=context.error)
application.add_error_handler(error_handler)
# Start the bot with Long Polling
logger.info("Starting Lichess Statistics Bot with Long Polling...")
try:
application.run_polling(
poll_interval=POLL_INTERVAL,
timeout=POLL_TIMEOUT,
drop_pending_updates=DROP_PENDING_UPDATES,
allowed_updates=ALLOWED_UPDATES
)
except Exception as e:
logger.error(f"Fatal error in run_polling: {e}")
import traceback
logger.error(traceback.format_exc())
raise
if __name__ == '__main__':
main()