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>
This commit is contained in:
parent
d4eb61f994
commit
6355cd917d
10 changed files with 288 additions and 77 deletions
|
|
@ -10,3 +10,10 @@ ADMINPANEL_TELEGRAM_BOT_TOKEN=8588876086:AAHoZncfhTCbul1BblpvnZMzvz7jAYVFmcw
|
||||||
# anonymous requests to these endpoints with a 404; any valid token works,
|
# anonymous requests to these endpoints with a 404; any valid token works,
|
||||||
# it does not need to belong to a tracked player.
|
# it does not need to belong to a tracked player.
|
||||||
LICHESS_APP_TOKEN=lip_xxxxxxxxxxxxxxxxxxxx
|
LICHESS_APP_TOKEN=lip_xxxxxxxxxxxxxxxxxxxx
|
||||||
|
|
||||||
|
# Optional: logging level for the bots (INFO by default).
|
||||||
|
#LOG_LEVEL=INFO
|
||||||
|
|
||||||
|
# Optional: text-to-speech announcer for admin events, reachable only from the
|
||||||
|
# home LAN. Leave unset on prod (the bot then skips it instead of timing out).
|
||||||
|
#TTS_URL=http://192.168.8.111:7901
|
||||||
|
|
|
||||||
|
|
@ -15,15 +15,13 @@ from telegram.ext import (
|
||||||
ConversationHandler, MessageHandler, filters
|
ConversationHandler, MessageHandler, filters
|
||||||
)
|
)
|
||||||
|
|
||||||
from config import ADMINPANEL_TELEGRAM_BOT_TOKEN, DATABASE_PATH, TELEGRAM_BOT_TOKEN
|
from config import ADMINPANEL_TELEGRAM_BOT_TOKEN, DATABASE_PATH, TELEGRAM_BOT_TOKEN, LOG_LEVEL, TTS_URL
|
||||||
from database import Database
|
from database import Database
|
||||||
from message_counters import MessageCounters
|
from message_counters import MessageCounters
|
||||||
|
|
||||||
# Configure logging
|
# NOTE: no logging.basicConfig() at import time. This module is imported by bot.py,
|
||||||
logging.basicConfig(
|
# and a module-level basicConfig here used to win over bot.py's own one, silently
|
||||||
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
|
# forcing its level. Each process configures logging in its main().
|
||||||
level=logging.INFO
|
|
||||||
)
|
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
# Conversation states for system message
|
# Conversation states for system message
|
||||||
|
|
@ -86,12 +84,15 @@ class AdminBot:
|
||||||
self.db.set_admin_chat_id(chat_id)
|
self.db.set_admin_chat_id(chat_id)
|
||||||
|
|
||||||
async def _call_tts_service(self, text: str):
|
async def _call_tts_service(self, text: str):
|
||||||
"""Call TTS service with given text"""
|
"""Call the optional TTS announcer (config.TTS_URL); no-op when it is not configured."""
|
||||||
|
if not TTS_URL:
|
||||||
|
logger.debug(f"TTS_URL not set, skipping TTS announcement: {text}")
|
||||||
|
return
|
||||||
try:
|
try:
|
||||||
import urllib.parse
|
import urllib.parse
|
||||||
import aiohttp
|
import aiohttp
|
||||||
encoded_text = urllib.parse.quote(text)
|
encoded_text = urllib.parse.quote(text)
|
||||||
tts_url = f"http://192.168.8.111:7901/TTS?text={encoded_text}"
|
tts_url = f"{TTS_URL.rstrip('/')}/TTS?text={encoded_text}"
|
||||||
async with aiohttp.ClientSession() as session:
|
async with aiohttp.ClientSession() as session:
|
||||||
async with session.get(tts_url, timeout=aiohttp.ClientTimeout(total=5)) as response:
|
async with session.get(tts_url, timeout=aiohttp.ClientTimeout(total=5)) as response:
|
||||||
if response.status == 200:
|
if response.status == 200:
|
||||||
|
|
@ -490,6 +491,14 @@ def init_admin_bot():
|
||||||
|
|
||||||
def main():
|
def main():
|
||||||
"""Main function"""
|
"""Main function"""
|
||||||
|
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, including the full URL with the
|
||||||
|
# bot token in it: one line per getUpdates every 30s, token in plain text.
|
||||||
|
logging.getLogger("httpx").setLevel(logging.WARNING)
|
||||||
|
|
||||||
admin_bot = init_admin_bot()
|
admin_bot = init_admin_bot()
|
||||||
|
|
||||||
# Create application with Long Polling configuration
|
# Create application with Long Polling configuration
|
||||||
|
|
@ -504,9 +513,7 @@ def main():
|
||||||
# Add error handler
|
# Add error handler
|
||||||
async def error_handler(update: object, context: ContextTypes.DEFAULT_TYPE) -> None:
|
async def error_handler(update: object, context: ContextTypes.DEFAULT_TYPE) -> None:
|
||||||
"""Log the error and send a telegram message to notify the developer."""
|
"""Log the error and send a telegram message to notify the developer."""
|
||||||
logger.error(f"Exception while handling an update: {context.error}")
|
logger.error("Exception while handling an update: %r", context.error, exc_info=context.error)
|
||||||
import traceback
|
|
||||||
logger.error(traceback.format_exc())
|
|
||||||
|
|
||||||
application.add_error_handler(error_handler)
|
application.add_error_handler(error_handler)
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -11,7 +11,7 @@ from telegram import Update, InlineKeyboardButton, InlineKeyboardMarkup
|
||||||
from telegram.ext import (
|
from telegram.ext import (
|
||||||
Application, CommandHandler, CallbackQueryHandler,
|
Application, CommandHandler, CallbackQueryHandler,
|
||||||
MessageHandler, filters, ContextTypes, ConversationHandler,
|
MessageHandler, filters, ContextTypes, ConversationHandler,
|
||||||
PicklePersistence
|
PicklePersistence, TypeHandler
|
||||||
)
|
)
|
||||||
from telegram.error import Forbidden
|
from telegram.error import Forbidden
|
||||||
|
|
||||||
|
|
@ -20,24 +20,27 @@ from config import (
|
||||||
TELEGRAM_BOT_TOKEN, PERIOD_OPTIONS, POLL_INTERVAL,
|
TELEGRAM_BOT_TOKEN, PERIOD_OPTIONS, POLL_INTERVAL,
|
||||||
POLL_TIMEOUT, DROP_PENDING_UPDATES, ALLOWED_UPDATES,
|
POLL_TIMEOUT, DROP_PENDING_UPDATES, ALLOWED_UPDATES,
|
||||||
LICHESS_STATS_API_BASE_URL, ADMINPANEL_TELEGRAM_BOT_TOKEN,
|
LICHESS_STATS_API_BASE_URL, ADMINPANEL_TELEGRAM_BOT_TOKEN,
|
||||||
DATABASE_PATH
|
DATABASE_PATH, LOG_LEVEL
|
||||||
)
|
)
|
||||||
from version import BOT_VERSION
|
from version import BOT_VERSION
|
||||||
from database import Database
|
from database import Database
|
||||||
from lichess_api import LichessAPI, InvalidTokenError
|
from lichess_api import LichessAPI, InvalidTokenError
|
||||||
from formatters import StatsFormatter
|
from formatters import StatsFormatter
|
||||||
from i18n import t
|
from i18n import t, format_period
|
||||||
from admin_bot import get_admin_bot, init_admin_bot
|
from admin_bot import get_admin_bot, init_admin_bot
|
||||||
from message_counters import MessageCounters
|
from message_counters import MessageCounters
|
||||||
from request_queue import get_request_queue
|
from request_queue import get_request_queue
|
||||||
import time
|
import time
|
||||||
import aiohttp
|
import aiohttp
|
||||||
|
|
||||||
# Configure logging
|
# Configure logging (level from LOG_LEVEL env, INFO by default)
|
||||||
logging.basicConfig(
|
logging.basicConfig(
|
||||||
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
|
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
|
||||||
level=logging.DEBUG
|
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__)
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
# Conversation states
|
# Conversation states
|
||||||
|
|
@ -457,7 +460,6 @@ class LichessBot:
|
||||||
possible_paths = [
|
possible_paths = [
|
||||||
image_path, # В папке бота
|
image_path, # В папке бота
|
||||||
bot_dir.parent / image_filename, # В корне проекта
|
bot_dir.parent / image_filename, # В корне проекта
|
||||||
Path("/home/vrubel/PROJECTS/LichessStatTgWeb/LichessClientTG_bot") / image_filename, # Абсолютный путь
|
|
||||||
]
|
]
|
||||||
|
|
||||||
# Ищем существующий файл
|
# Ищем существующий файл
|
||||||
|
|
@ -561,6 +563,7 @@ class LichessBot:
|
||||||
|
|
||||||
# Set default period to 1 hour (60 minutes) for new gamer
|
# Set default period to 1 hour (60 minutes) for new gamer
|
||||||
self.db.set_user_gamer_period(user_id, gamer_id, 60)
|
self.db.set_user_gamer_period(user_id, gamer_id, 60)
|
||||||
|
self.counters.increment('gamer_added')
|
||||||
|
|
||||||
# If this is the first gamer for this user, make it active
|
# If this is the first gamer for this user, make it active
|
||||||
user_gamers = self.db.get_user_gamers(user_id)
|
user_gamers = self.db.get_user_gamers(user_id)
|
||||||
|
|
@ -610,11 +613,16 @@ class LichessBot:
|
||||||
|
|
||||||
async def handle_username(self, update: Update, context: ContextTypes.DEFAULT_TYPE):
|
async def handle_username(self, update: Update, context: ContextTypes.DEFAULT_TYPE):
|
||||||
"""Handle username input for /addgamer"""
|
"""Handle username input for /addgamer"""
|
||||||
# Only handle if we are awaiting an addgamer username
|
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')):
|
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
|
return
|
||||||
username = update.message.text.strip()
|
username = update.message.text.strip()
|
||||||
user_id = update.effective_user.id
|
|
||||||
|
|
||||||
lang = self.get_user_language_from_update(update)
|
lang = self.get_user_language_from_update(update)
|
||||||
if not username:
|
if not username:
|
||||||
|
|
@ -624,8 +632,9 @@ class LichessBot:
|
||||||
return
|
return
|
||||||
|
|
||||||
# Check if user exists on Lichess
|
# Check if user exists on Lichess
|
||||||
user_exists = await self.lichess_api.check_user_exists(username)
|
logger.info(f"addgamer: user {user_id} entered username {username!r}")
|
||||||
if user_exists is None:
|
lichess_user = await self.lichess_api.check_user_exists(username)
|
||||||
|
if lichess_user is None:
|
||||||
# Transient API failure (rate limit, network error, unexpected status) —
|
# Transient API failure (rate limit, network error, unexpected status) —
|
||||||
# don't tell the user the name is wrong, it may well be valid.
|
# don't tell the user the name is wrong, it may well be valid.
|
||||||
await update.message.reply_text(
|
await update.message.reply_text(
|
||||||
|
|
@ -633,12 +642,24 @@ class LichessBot:
|
||||||
parse_mode='HTML'
|
parse_mode='HTML'
|
||||||
)
|
)
|
||||||
return
|
return
|
||||||
if not user_exists:
|
if not lichess_user:
|
||||||
|
logger.info(f"addgamer: username {username!r} not found on Lichess (user {user_id})")
|
||||||
await update.message.reply_text(
|
await update.message.reply_text(
|
||||||
t('user_not_found', lang, username=username) + '\n\n' + t('addgamer_prompt', lang),
|
t('user_not_found', lang, username=username) + '\n\n' + t('addgamer_prompt', lang),
|
||||||
parse_mode='HTML'
|
parse_mode='HTML'
|
||||||
)
|
)
|
||||||
return WAITING_FOR_USERNAME
|
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
|
# Check if this gamer is already tracked by this user
|
||||||
user_gamers = self.db.get_user_gamers(user_id)
|
user_gamers = self.db.get_user_gamers(user_id)
|
||||||
|
|
@ -658,7 +679,7 @@ class LichessBot:
|
||||||
import sqlite3
|
import sqlite3
|
||||||
with sqlite3.connect(self.db.db_path) as conn:
|
with sqlite3.connect(self.db.db_path) as conn:
|
||||||
cursor = conn.cursor()
|
cursor = conn.cursor()
|
||||||
cursor.execute("SELECT id FROM gamers WHERE username = ?", (username,))
|
cursor.execute("SELECT id FROM gamers WHERE lower(username) = lower(?)", (username,))
|
||||||
existing_gamer_row = cursor.fetchone()
|
existing_gamer_row = cursor.fetchone()
|
||||||
is_new_gamer = existing_gamer_row is None
|
is_new_gamer = existing_gamer_row is None
|
||||||
|
|
||||||
|
|
@ -677,6 +698,8 @@ class LichessBot:
|
||||||
|
|
||||||
# Set default period to 1 hour (60 minutes) for new gamer
|
# Set default period to 1 hour (60 minutes) for new gamer
|
||||||
self.db.set_user_gamer_period(user_id, gamer_id, 60)
|
self.db.set_user_gamer_period(user_id, gamer_id, 60)
|
||||||
|
self.counters.increment('gamer_added')
|
||||||
|
logger.info(f"addgamer: player {username} added for user {user_id} (new_gamer={is_new_gamer})")
|
||||||
|
|
||||||
# If this is the first gamer for this user, make it active
|
# If this is the first gamer for this user, make it active
|
||||||
user_gamers = self.db.get_user_gamers(user_id)
|
user_gamers = self.db.get_user_gamers(user_id)
|
||||||
|
|
@ -1271,7 +1294,7 @@ class LichessBot:
|
||||||
reply_markup = InlineKeyboardMarkup(keyboard)
|
reply_markup = InlineKeyboardMarkup(keyboard)
|
||||||
|
|
||||||
await update.message.reply_text(
|
await update.message.reply_text(
|
||||||
"⏱️ Select player to set notification period:",
|
t('select_player_period', lang),
|
||||||
reply_markup=reply_markup
|
reply_markup=reply_markup
|
||||||
)
|
)
|
||||||
self.counters.increment('setperiod')
|
self.counters.increment('setperiod')
|
||||||
|
|
@ -1322,14 +1345,7 @@ class LichessBot:
|
||||||
if period == 0:
|
if period == 0:
|
||||||
button_text = t('disable_notifications', lang)
|
button_text = t('disable_notifications', lang)
|
||||||
else:
|
else:
|
||||||
# Format period text: minutes for < 60, hours for >= 60
|
button_text = f"⏰ {format_period(period, lang)}"
|
||||||
if period < 60:
|
|
||||||
button_text = f"⏰ {period} minutes"
|
|
||||||
elif period == 60:
|
|
||||||
button_text = "⏰ 1 hour"
|
|
||||||
else:
|
|
||||||
hours = period // 60
|
|
||||||
button_text = f"⏰ {hours} hours"
|
|
||||||
keyboard.append([InlineKeyboardButton(
|
keyboard.append([InlineKeyboardButton(
|
||||||
button_text,
|
button_text,
|
||||||
callback_data=f"period_{gamer_id}_{period}"
|
callback_data=f"period_{gamer_id}_{period}"
|
||||||
|
|
@ -1388,16 +1404,8 @@ class LichessBot:
|
||||||
t('notifications_disabled', lang, username=selected_gamer['username'])
|
t('notifications_disabled', lang, username=selected_gamer['username'])
|
||||||
)
|
)
|
||||||
else:
|
else:
|
||||||
# Format period text for confirmation message
|
|
||||||
if period < 60:
|
|
||||||
period_text = f"{period} minutes"
|
|
||||||
elif period == 60:
|
|
||||||
period_text = "1 hour"
|
|
||||||
else:
|
|
||||||
hours = period // 60
|
|
||||||
period_text = f"{hours} hours"
|
|
||||||
await query.edit_message_text(
|
await query.edit_message_text(
|
||||||
f"✅ Period {period_text} set for {selected_gamer['username']}\n📱 Notifications will be sent to personal messages"
|
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)
|
# Start periodic task for this gamer (send to user's personal messages)
|
||||||
|
|
@ -1623,13 +1631,13 @@ class LichessBot:
|
||||||
# Если следующий период еще не наступил, ждем
|
# Если следующий период еще не наступил, ждем
|
||||||
if next_period_start > now:
|
if next_period_start > now:
|
||||||
wait_seconds = (next_period_start - now).total_seconds()
|
wait_seconds = (next_period_start - now).total_seconds()
|
||||||
logger.info(f"⏳ Waiting {wait_seconds:.1f} seconds until next period start ({next_period_start}) for {username}")
|
logger.debug(f"⏳ Waiting {wait_seconds:.1f} seconds until next period start ({next_period_start}) for {username}")
|
||||||
await asyncio.sleep(wait_seconds)
|
await asyncio.sleep(wait_seconds)
|
||||||
# Используем сохраненное время как начало периода
|
# Используем сохраненное время как начало периода
|
||||||
since_time = last_check_time
|
since_time = last_check_time
|
||||||
# Конец периода - это момент, когда должен был начаться следующий период
|
# Конец периода - это момент, когда должен был начаться следующий период
|
||||||
period_end_approx = next_period_start
|
period_end_approx = next_period_start
|
||||||
logger.info(f"📌 Using saved period: from {since_time} to {period_end_approx}")
|
logger.debug(f"📌 Using saved period: from {since_time} to {period_end_approx}")
|
||||||
else:
|
else:
|
||||||
# Мы отстаём от расписания (бэклог): если догонять по period_minutes
|
# Мы отстаём от расписания (бэклог): если догонять по period_minutes
|
||||||
# за раз, при большом отставании (недели простоя, много отслеживаемых
|
# за раз, при большом отставании (недели простоя, много отслеживаемых
|
||||||
|
|
@ -1679,7 +1687,7 @@ class LichessBot:
|
||||||
until_timestamp_approx = int(period_end_approx.timestamp() * 1000)
|
until_timestamp_approx = int(period_end_approx.timestamp() * 1000)
|
||||||
|
|
||||||
logger.info(f"🔍 Checking activity for {username} (user {user_id}): period from {since_time} to {period_end_approx} (approx, last {period_minutes} minutes)")
|
logger.info(f"🔍 Checking activity for {username} (user {user_id}): period from {since_time} to {period_end_approx} (approx, last {period_minutes} minutes)")
|
||||||
logger.info(f"📅 Unix timestamps: since={since_timestamp}, until_approx={until_timestamp_approx}")
|
logger.debug(f"📅 Unix timestamps: since={since_timestamp}, until_approx={until_timestamp_approx}")
|
||||||
|
|
||||||
# Делаем запросы к API через очередь с обработкой ошибок
|
# Делаем запросы к API через очередь с обработкой ошибок
|
||||||
games_data = None
|
games_data = None
|
||||||
|
|
@ -1687,7 +1695,7 @@ class LichessBot:
|
||||||
|
|
||||||
try:
|
try:
|
||||||
# Добавляем запрос в очередь (будет выполнен с задержкой 7 секунд)
|
# Добавляем запрос в очередь (будет выполнен с задержкой 7 секунд)
|
||||||
logger.info(f"📥 Adding games request to queue for {gamer['username']}")
|
logger.debug(f"📥 Adding games request to queue for {gamer['username']}")
|
||||||
games_data = await self.request_queue.add_request(
|
games_data = await self.request_queue.add_request(
|
||||||
self.lichess_api.get_games_period,
|
self.lichess_api.get_games_period,
|
||||||
gamer['username'], since_timestamp, until_timestamp_approx,
|
gamer['username'], since_timestamp, until_timestamp_approx,
|
||||||
|
|
@ -1697,7 +1705,7 @@ class LichessBot:
|
||||||
raise RuntimeError("Games period API returned no data")
|
raise RuntimeError("Games period API returned no data")
|
||||||
# Фиксируем фактическое время получения ответа
|
# Фиксируем фактическое время получения ответа
|
||||||
request_end_time = datetime.now()
|
request_end_time = datetime.now()
|
||||||
logger.info(f"✅ Games API response received for {gamer['username']} at {request_end_time}")
|
logger.debug(f"✅ Games API response received for {gamer['username']} at {request_end_time}")
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.error(f"❌ Error getting games data for {gamer['username']}: {e}")
|
logger.error(f"❌ Error getting games data for {gamer['username']}: {e}")
|
||||||
consecutive_errors += 1
|
consecutive_errors += 1
|
||||||
|
|
@ -1722,7 +1730,7 @@ class LichessBot:
|
||||||
# (401), ретраить бессмысленно — это раньше приводило к вечному циклу
|
# (401), ретраить бессмысленно — это раньше приводило к вечному циклу
|
||||||
# ретраев без продвижения чекпоинта (см. историю с Dor1zz). Вместо этого
|
# ретраев без продвижения чекпоинта (см. историю с Dor1zz). Вместо этого
|
||||||
# отключаем пазлы для этой пары и продолжаем отслеживать партии как обычно.
|
# отключаем пазлы для этой пары и продолжаем отслеживать партии как обычно.
|
||||||
logger.info(f"📥 Adding puzzles request to queue for {gamer['username']}")
|
logger.debug(f"📥 Adding puzzles request to queue for {gamer['username']}")
|
||||||
try:
|
try:
|
||||||
puzzles_data = await self.request_queue.add_request(
|
puzzles_data = await self.request_queue.add_request(
|
||||||
self.lichess_api.get_puzzles_period,
|
self.lichess_api.get_puzzles_period,
|
||||||
|
|
@ -1746,7 +1754,7 @@ class LichessBot:
|
||||||
raise RuntimeError("Puzzles period API returned no data")
|
raise RuntimeError("Puzzles period API returned no data")
|
||||||
# Обновляем фактическое время после получения ответа по пазлам
|
# Обновляем фактическое время после получения ответа по пазлам
|
||||||
request_end_time = datetime.now()
|
request_end_time = datetime.now()
|
||||||
logger.info(f"✅ Puzzles API response received for {gamer['username']} at {request_end_time}")
|
logger.debug(f"✅ Puzzles API response received for {gamer['username']} at {request_end_time}")
|
||||||
|
|
||||||
# Сбрасываем счетчик ошибок при успешном запросе
|
# Сбрасываем счетчик ошибок при успешном запросе
|
||||||
consecutive_errors = 0
|
consecutive_errors = 0
|
||||||
|
|
@ -1756,7 +1764,7 @@ class LichessBot:
|
||||||
total_games = 0
|
total_games = 0
|
||||||
if games_data:
|
if games_data:
|
||||||
# Логируем структуру ответа для отладки
|
# Логируем структуру ответа для отладки
|
||||||
logger.info(f"📊 Games data structure for {username}: {games_data}")
|
logger.debug(f"📊 Games data structure for {username}: {games_data}")
|
||||||
|
|
||||||
# Проверяем games_count на верхнем уровне (приоритет)
|
# Проверяем games_count на верхнем уровне (приоритет)
|
||||||
top_level_count = games_data.get('games_count', 0)
|
top_level_count = games_data.get('games_count', 0)
|
||||||
|
|
@ -1765,7 +1773,7 @@ class LichessBot:
|
||||||
if top_level_count > 0:
|
if top_level_count > 0:
|
||||||
total_games = top_level_count
|
total_games = top_level_count
|
||||||
has_games = True
|
has_games = True
|
||||||
logger.info(f"✅ Found {total_games} games via games_count field")
|
logger.debug(f"✅ Found {total_games} games via games_count field")
|
||||||
else:
|
else:
|
||||||
# Также проверяем data.total.games_played
|
# Также проверяем data.total.games_played
|
||||||
games_data_dict = games_data.get('data')
|
games_data_dict = games_data.get('data')
|
||||||
|
|
@ -1779,29 +1787,29 @@ class LichessBot:
|
||||||
if total_games_played > 0:
|
if total_games_played > 0:
|
||||||
total_games = total_games_played
|
total_games = total_games_played
|
||||||
has_games = True
|
has_games = True
|
||||||
logger.info(f"✅ Found {total_games} games via data.total.games_played field")
|
logger.debug(f"✅ Found {total_games} games via data.total.games_played field")
|
||||||
else:
|
else:
|
||||||
logger.warning(f"⚠️ No games found: games_count={top_level_count}, data.total.games_played={total_games_played}")
|
logger.debug(f"⚠️ No games found: games_count={top_level_count}, data.total.games_played={total_games_played}")
|
||||||
else:
|
else:
|
||||||
logger.warning(f"⚠️ No games_data returned for {username}")
|
logger.warning(f"⚠️ No games_data returned for {username}")
|
||||||
|
|
||||||
has_puzzles = False
|
has_puzzles = False
|
||||||
total_puzzles = 0
|
total_puzzles = 0
|
||||||
if puzzles_data:
|
if puzzles_data:
|
||||||
logger.info(f"📊 Puzzles data structure for {username}: {puzzles_data}")
|
logger.debug(f"📊 Puzzles data structure for {username}: {puzzles_data}")
|
||||||
|
|
||||||
# Проверяем puzzles_in_period на верхнем уровне (приоритет)
|
# Проверяем puzzles_in_period на верхнем уровне (приоритет)
|
||||||
if puzzles_data.get('puzzles_in_period', 0) > 0:
|
if puzzles_data.get('puzzles_in_period', 0) > 0:
|
||||||
total_puzzles = puzzles_data.get('puzzles_in_period', 0)
|
total_puzzles = puzzles_data.get('puzzles_in_period', 0)
|
||||||
has_puzzles = True
|
has_puzzles = True
|
||||||
logger.info(f"✅ Found {total_puzzles} puzzles via puzzles_in_period field")
|
logger.debug(f"✅ Found {total_puzzles} puzzles via puzzles_in_period field")
|
||||||
# Также проверяем data.total_attempts
|
# Также проверяем data.total_attempts
|
||||||
elif puzzles_data.get('data') and puzzles_data.get('data', {}).get('total_attempts', 0) > 0:
|
elif puzzles_data.get('data') and puzzles_data.get('data', {}).get('total_attempts', 0) > 0:
|
||||||
total_puzzles = puzzles_data.get('data', {}).get('total_attempts', 0)
|
total_puzzles = puzzles_data.get('data', {}).get('total_attempts', 0)
|
||||||
has_puzzles = True
|
has_puzzles = True
|
||||||
logger.info(f"✅ Found {total_puzzles} puzzles via data.total_attempts field")
|
logger.debug(f"✅ Found {total_puzzles} puzzles via data.total_attempts field")
|
||||||
|
|
||||||
logger.info(f"🔍 Activity check result for {username}: has_games={has_games} (total={total_games}), has_puzzles={has_puzzles} (total={total_puzzles})")
|
logger.debug(f"🔍 Activity check result for {username}: has_games={has_games} (total={total_games}), has_puzzles={has_puzzles} (total={total_puzzles})")
|
||||||
|
|
||||||
# Отправляем уведомление только если есть реальная активность и это не
|
# Отправляем уведомление только если есть реальная активность и это не
|
||||||
# молчаливый догон устаревшего бэклога (is_stale_backlog, см. выше).
|
# молчаливый догон устаревшего бэклога (is_stale_backlog, см. выше).
|
||||||
|
|
@ -1863,11 +1871,11 @@ class LichessBot:
|
||||||
# period_end_approx уже установлено в начале итерации
|
# period_end_approx уже установлено в начале итерации
|
||||||
self.period_start_times[task_key] = period_end_approx
|
self.period_start_times[task_key] = period_end_approx
|
||||||
self.db.set_period_checkpoint(user_id, gamer['id'], int(period_end_approx.timestamp()))
|
self.db.set_period_checkpoint(user_id, gamer['id'], int(period_end_approx.timestamp()))
|
||||||
logger.info(f"📌 Updated period_start_time for {username} to {period_end_approx} (planned period end, next period will start from here)")
|
logger.debug(f"📌 Updated period_start_time for {username} to {period_end_approx} (planned period end, next period will start from here)")
|
||||||
if 'request_end_time' in locals():
|
if 'request_end_time' in locals():
|
||||||
delay = (request_end_time - period_end_approx).total_seconds()
|
delay = (request_end_time - period_end_approx).total_seconds()
|
||||||
if delay > 0:
|
if delay > 0:
|
||||||
logger.info(f"⏱️ Request completed with {delay:.1f}s delay after planned period end")
|
logger.debug(f"⏱️ Request completed with {delay:.1f}s delay after planned period end")
|
||||||
|
|
||||||
except asyncio.CancelledError:
|
except asyncio.CancelledError:
|
||||||
logger.info(f"Periodic check cancelled for {gamer['username']}")
|
logger.info(f"Periodic check cancelled for {gamer['username']}")
|
||||||
|
|
@ -1891,10 +1899,35 @@ class LichessBot:
|
||||||
await asyncio.sleep(backoff_seconds)
|
await asyncio.sleep(backoff_seconds)
|
||||||
continue
|
continue
|
||||||
|
|
||||||
|
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):
|
def setup_handlers(self, application: Application):
|
||||||
"""Setup all handlers"""
|
"""Setup all handlers"""
|
||||||
self.application = application # Store application reference
|
self.application = application # Store application reference
|
||||||
|
|
||||||
|
# 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)
|
# Conversation handler for addtoken (token required)
|
||||||
# Must be added BEFORE general MessageHandler to avoid conflicts
|
# Must be added BEFORE general MessageHandler to avoid conflicts
|
||||||
addtoken_conv = ConversationHandler(
|
addtoken_conv = ConversationHandler(
|
||||||
|
|
@ -1938,6 +1971,13 @@ class LichessBot:
|
||||||
application.add_handler(CallbackQueryHandler(self.handle_delete_gamer, pattern="^delete_"))
|
application.add_handler(CallbackQueryHandler(self.handle_delete_gamer, pattern="^delete_"))
|
||||||
application.add_handler(CallbackQueryHandler(self.select_period, pattern="^period_"))
|
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():
|
def main():
|
||||||
"""Main function"""
|
"""Main function"""
|
||||||
# Initialize admin bot for notifications (admin bot runs as separate service)
|
# Initialize admin bot for notifications (admin bot runs as separate service)
|
||||||
|
|
@ -1968,10 +2008,16 @@ def main():
|
||||||
|
|
||||||
# Add error handler
|
# Add error handler
|
||||||
async def error_handler(update: object, context: ContextTypes.DEFAULT_TYPE) -> None:
|
async def error_handler(update: object, context: ContextTypes.DEFAULT_TYPE) -> None:
|
||||||
"""Log the error and send a telegram message to notify the developer."""
|
"""Log the error with its real traceback and which update triggered it."""
|
||||||
logger.error(f"Exception while handling an update: {context.error}")
|
# traceback.format_exc() here printed "NoneType: None": the error handler runs
|
||||||
import traceback
|
# outside the except block, so the traceback has to come from context.error itself.
|
||||||
logger.error(traceback.format_exc())
|
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)
|
application.add_error_handler(error_handler)
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -6,6 +6,15 @@ load_dotenv()
|
||||||
TELEGRAM_BOT_TOKEN = os.getenv("TELEGRAM_BOT_TOKEN")
|
TELEGRAM_BOT_TOKEN = os.getenv("TELEGRAM_BOT_TOKEN")
|
||||||
ADMINPANEL_TELEGRAM_BOT_TOKEN = os.getenv("ADMINPANEL_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 Configuration
|
||||||
LICHESS_API_BASE_URL = "https://lichess.org/api"
|
LICHESS_API_BASE_URL = "https://lichess.org/api"
|
||||||
|
|
@ -53,5 +62,8 @@ PERIOD_OPTIONS = [0, 15, 30, 60, 120, 180, 360, 720, 1440] # minutes (0=disable
|
||||||
# Telegram Bot Long Polling Configuration
|
# Telegram Bot Long Polling Configuration
|
||||||
POLL_INTERVAL = 1.0 # seconds
|
POLL_INTERVAL = 1.0 # seconds
|
||||||
POLL_TIMEOUT = 30 # seconds
|
POLL_TIMEOUT = 30 # seconds
|
||||||
DROP_PENDING_UPDATES = True # Drop pending updates on startup
|
# 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"]
|
ALLOWED_UPDATES = ["message", "callback_query"]
|
||||||
|
|
|
||||||
|
|
@ -108,7 +108,7 @@ class Database:
|
||||||
# Initialize counters for all commands
|
# Initialize counters for all commands
|
||||||
commands = ['start', 'addgamer', 'addtoken', 'getgamers', 'delgamer',
|
commands = ['start', 'addgamer', 'addtoken', 'getgamers', 'delgamer',
|
||||||
'today', 'yesterday', 'week', 'setperiod', 'lang', 'resetlang',
|
'today', 'yesterday', 'week', 'setperiod', 'lang', 'resetlang',
|
||||||
'periodic_notification']
|
'periodic_notification', 'gamer_added']
|
||||||
for cmd in commands:
|
for cmd in commands:
|
||||||
cursor.execute('''
|
cursor.execute('''
|
||||||
INSERT OR IGNORE INTO message_counters (command, total_count, today_count, last_reset_date)
|
INSERT OR IGNORE INTO message_counters (command, total_count, today_count, last_reset_date)
|
||||||
|
|
@ -120,8 +120,73 @@ class Database:
|
||||||
# Migrate tokens from gamers to user_gamers if needed
|
# Migrate tokens from gamers to user_gamers if needed
|
||||||
self._migrate_tokens_from_gamers()
|
self._migrate_tokens_from_gamers()
|
||||||
|
|
||||||
|
# Lichess usernames are case-insensitive, but gamers.username UNIQUE is
|
||||||
|
# case-sensitive, so "Zhigalko_Sergei" and "Zhigalko_sergei" ended up as
|
||||||
|
# two players checked separately every hour. Merge such duplicates and
|
||||||
|
# forbid new ones with a case-insensitive unique index.
|
||||||
|
self._merge_case_duplicate_gamers()
|
||||||
|
with sqlite3.connect(self.db_path) as conn:
|
||||||
|
conn.execute(
|
||||||
|
"CREATE UNIQUE INDEX IF NOT EXISTS idx_gamers_username_nocase ON gamers(lower(username))"
|
||||||
|
)
|
||||||
|
conn.commit()
|
||||||
|
|
||||||
logger.info("Database initialized successfully")
|
logger.info("Database initialized successfully")
|
||||||
|
|
||||||
|
def _merge_case_duplicate_gamers(self):
|
||||||
|
"""Merge gamers rows whose usernames differ only by case into the oldest row."""
|
||||||
|
with sqlite3.connect(self.db_path) as conn:
|
||||||
|
cursor = conn.cursor()
|
||||||
|
cursor.execute(
|
||||||
|
"SELECT lower(username) FROM gamers GROUP BY lower(username) HAVING COUNT(*) > 1"
|
||||||
|
)
|
||||||
|
groups = [row[0] for row in cursor.fetchall()]
|
||||||
|
if not groups:
|
||||||
|
return
|
||||||
|
merged_links = 0
|
||||||
|
for lowered in groups:
|
||||||
|
cursor.execute(
|
||||||
|
"SELECT id, username FROM gamers WHERE lower(username) = ? ORDER BY id",
|
||||||
|
(lowered,)
|
||||||
|
)
|
||||||
|
rows = cursor.fetchall()
|
||||||
|
keep_id, keep_name = rows[0]
|
||||||
|
for dup_id, dup_name in rows[1:]:
|
||||||
|
cursor.execute(
|
||||||
|
"SELECT id, user_id, token, is_active, period_minutes, last_period_end_ts "
|
||||||
|
"FROM user_gamers WHERE gamer_id = ?",
|
||||||
|
(dup_id,)
|
||||||
|
)
|
||||||
|
for link_id, user_id, token, is_active, period, checkpoint in cursor.fetchall():
|
||||||
|
cursor.execute(
|
||||||
|
"SELECT id, token, is_active, period_minutes FROM user_gamers "
|
||||||
|
"WHERE user_id = ? AND gamer_id = ?",
|
||||||
|
(user_id, keep_id)
|
||||||
|
)
|
||||||
|
existing = cursor.fetchone()
|
||||||
|
if existing is None:
|
||||||
|
cursor.execute(
|
||||||
|
"UPDATE user_gamers SET gamer_id = ? WHERE id = ?",
|
||||||
|
(keep_id, link_id)
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
# Same user tracks both spellings: keep one link, but don't
|
||||||
|
# lose a token / enabled period / active flag from the other.
|
||||||
|
ex_id, ex_token, ex_active, ex_period = existing
|
||||||
|
cursor.execute(
|
||||||
|
"UPDATE user_gamers SET token = COALESCE(token, ?), "
|
||||||
|
"is_active = (is_active OR ?), "
|
||||||
|
"period_minutes = CASE WHEN period_minutes > 0 THEN period_minutes ELSE ? END, "
|
||||||
|
"last_period_end_ts = COALESCE(last_period_end_ts, ?) WHERE id = ?",
|
||||||
|
(token, 1 if is_active else 0, period or 0, checkpoint, ex_id)
|
||||||
|
)
|
||||||
|
cursor.execute("DELETE FROM user_gamers WHERE id = ?", (link_id,))
|
||||||
|
merged_links += 1
|
||||||
|
cursor.execute("DELETE FROM gamers WHERE id = ?", (dup_id,))
|
||||||
|
logger.info(f"Merged duplicate gamer '{dup_name}' (id={dup_id}) into '{keep_name}' (id={keep_id})")
|
||||||
|
conn.commit()
|
||||||
|
logger.info(f"Merged {len(groups)} case-duplicate gamer groups, {merged_links} user links re-pointed")
|
||||||
|
|
||||||
def _migrate_tokens_from_gamers(self):
|
def _migrate_tokens_from_gamers(self):
|
||||||
"""Migrate tokens from old gamers table to user_gamers table if needed"""
|
"""Migrate tokens from old gamers table to user_gamers table if needed"""
|
||||||
with sqlite3.connect(self.db_path) as conn:
|
with sqlite3.connect(self.db_path) as conn:
|
||||||
|
|
@ -222,8 +287,8 @@ class Database:
|
||||||
with sqlite3.connect(self.db_path) as conn:
|
with sqlite3.connect(self.db_path) as conn:
|
||||||
cursor = conn.cursor()
|
cursor = conn.cursor()
|
||||||
|
|
||||||
# Check if gamer already exists
|
# Check if gamer already exists (Lichess usernames are case-insensitive)
|
||||||
cursor.execute("SELECT id FROM gamers WHERE username = ?", (username,))
|
cursor.execute("SELECT id FROM gamers WHERE lower(username) = lower(?)", (username,))
|
||||||
existing = cursor.fetchone()
|
existing = cursor.fetchone()
|
||||||
|
|
||||||
if existing:
|
if existing:
|
||||||
|
|
|
||||||
|
|
@ -141,6 +141,14 @@ TRANSLATIONS = {
|
||||||
|
|
||||||
# Common
|
# Common
|
||||||
'period_minutes_suffix': "m",
|
'period_minutes_suffix': "m",
|
||||||
|
'select_player_period': "⏱️ Select a player to set the notification period:",
|
||||||
|
'period_set_confirm': "✅ Period {period} set for {username}\n📱 Notifications will be sent to personal messages",
|
||||||
|
'period_label_minutes': "{n} minutes",
|
||||||
|
'period_label_hour': "1 hour",
|
||||||
|
'period_label_hours': "{n} hours",
|
||||||
|
'user_closed': "❌ Lichess account {username} is closed, it cannot be tracked.",
|
||||||
|
'text_not_expected': "ℹ️ To add a player, use /addgamer.\n\nOther commands: /today, /yesterday, /week, /getgamers, /setperiod, /help",
|
||||||
|
'unsupported_message': "ℹ️ I only understand text messages. Send the Lichess username as plain text, or use /addgamer.",
|
||||||
|
|
||||||
# Language selection
|
# Language selection
|
||||||
'select_language': "🌐 <b>Select language / Выберите язык:</b>",
|
'select_language': "🌐 <b>Select language / Выберите язык:</b>",
|
||||||
|
|
@ -285,6 +293,14 @@ TRANSLATIONS = {
|
||||||
|
|
||||||
# Common
|
# Common
|
||||||
'period_minutes_suffix': "м",
|
'period_minutes_suffix': "м",
|
||||||
|
'select_player_period': "⏱️ Выберите игрока, чтобы настроить период уведомлений:",
|
||||||
|
'period_set_confirm': "✅ Период {period} установлен для {username}\n📱 Уведомления будут приходить в личные сообщения",
|
||||||
|
'period_label_minutes': "{n} минут",
|
||||||
|
'period_label_hour': "1 час",
|
||||||
|
'period_label_hours': "{n} {hours_word}",
|
||||||
|
'user_closed': "❌ Аккаунт {username} на Lichess закрыт, его нельзя отслеживать.",
|
||||||
|
'text_not_expected': "ℹ️ Чтобы добавить игрока, используйте /addgamer.\n\nДругие команды: /today, /yesterday, /week, /getgamers, /setperiod, /help",
|
||||||
|
'unsupported_message': "ℹ️ Я понимаю только текст. Отправьте username игрока Lichess обычным текстом или используйте /addgamer.",
|
||||||
|
|
||||||
# Language selection
|
# Language selection
|
||||||
'select_language': "🌐 <b>Выберите язык / Select language:</b>",
|
'select_language': "🌐 <b>Выберите язык / Select language:</b>",
|
||||||
|
|
@ -298,6 +314,27 @@ TRANSLATIONS = {
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def _ru_hours_word(n: int) -> str:
|
||||||
|
"""Russian plural for 'час': 1 час, 2-4 часа, 5-20 часов, 21 час, ..."""
|
||||||
|
if 11 <= n % 100 <= 14:
|
||||||
|
return "часов"
|
||||||
|
if n % 10 == 1:
|
||||||
|
return "час"
|
||||||
|
if 2 <= n % 10 <= 4:
|
||||||
|
return "часа"
|
||||||
|
return "часов"
|
||||||
|
|
||||||
|
|
||||||
|
def format_period(minutes: int, lang: str = 'en') -> str:
|
||||||
|
"""Human-readable period length ("15 minutes", "1 hour", "2 часа") in the user's language."""
|
||||||
|
if minutes < 60:
|
||||||
|
return t('period_label_minutes', lang, n=minutes)
|
||||||
|
hours = minutes // 60
|
||||||
|
if hours == 1:
|
||||||
|
return t('period_label_hour', lang)
|
||||||
|
return t('period_label_hours', lang, n=hours, hours_word=_ru_hours_word(hours))
|
||||||
|
|
||||||
|
|
||||||
def t(key: str, lang: str = 'en', **kwargs) -> str:
|
def t(key: str, lang: str = 'en', **kwargs) -> str:
|
||||||
"""
|
"""
|
||||||
Translate a key to the specified language.
|
Translate a key to the specified language.
|
||||||
|
|
|
||||||
|
|
@ -121,14 +121,14 @@ class LichessAPI:
|
||||||
params["rated_only"] = "true" if rated_only else "false"
|
params["rated_only"] = "true" if rated_only else "false"
|
||||||
if include_games:
|
if include_games:
|
||||||
params["include_games"] = "true"
|
params["include_games"] = "true"
|
||||||
logger.info(f"🔍 LichessAPI.get_games_period: URL={url}, params={params}")
|
logger.debug(f"🔍 LichessAPI.get_games_period: URL={url}, params={params}")
|
||||||
|
|
||||||
async with aiohttp.ClientSession() as session:
|
async with aiohttp.ClientSession() as session:
|
||||||
async with session.get(url, params=params) as response:
|
async with session.get(url, params=params) as response:
|
||||||
logger.info(f"🔍 LichessAPI.get_games_period: response.status={response.status}")
|
logger.debug(f"🔍 LichessAPI.get_games_period: response.status={response.status}")
|
||||||
if response.status == 200:
|
if response.status == 200:
|
||||||
result = await response.json()
|
result = await response.json()
|
||||||
logger.info(f"🔍 LichessAPI.get_games_period: result={result}")
|
logger.debug(f"🔍 LichessAPI.get_games_period: result={result}")
|
||||||
return result
|
return result
|
||||||
else:
|
else:
|
||||||
logger.error(f"Failed to get games period: {response.status}")
|
logger.error(f"Failed to get games period: {response.status}")
|
||||||
|
|
@ -170,14 +170,17 @@ class LichessAPI:
|
||||||
logger.error(f"Error getting puzzles period: {e}")
|
logger.error(f"Error getting puzzles period: {e}")
|
||||||
return None
|
return None
|
||||||
|
|
||||||
async def check_user_exists(self, username: str) -> Optional[bool]:
|
async def check_user_exists(self, username: str) -> Optional[Dict[str, Any]]:
|
||||||
"""
|
"""
|
||||||
Check if user exists on Lichess.
|
Check if user exists on Lichess.
|
||||||
|
|
||||||
Returns True/False for a definitive answer (200/404), or None if the
|
Returns a dict for an existing account:
|
||||||
check itself failed (rate limit, network error, unexpected status) —
|
{'username': <canonical spelling as Lichess has it>, 'disabled': bool}
|
||||||
callers must not treat None as "not found", since the username may
|
(Lichess answers 200 for closed accounts too, with "disabled": true — the
|
||||||
well be valid.
|
caller must reject those, they can't be tracked), False for a definitive
|
||||||
|
"not found" (404), or None if the check itself failed (rate limit,
|
||||||
|
network error, unexpected status) — callers must not treat None as
|
||||||
|
"not found", since the username may well be valid.
|
||||||
"""
|
"""
|
||||||
await self.rate_limiter.wait_if_needed()
|
await self.rate_limiter.wait_if_needed()
|
||||||
try:
|
try:
|
||||||
|
|
@ -186,7 +189,11 @@ class LichessAPI:
|
||||||
f"{self.lichess_base_url}/user/{username}"
|
f"{self.lichess_base_url}/user/{username}"
|
||||||
) as response:
|
) as response:
|
||||||
if response.status == 200:
|
if response.status == 200:
|
||||||
return True
|
data = await response.json()
|
||||||
|
return {
|
||||||
|
'username': data.get('username') or username,
|
||||||
|
'disabled': bool(data.get('disabled', False)),
|
||||||
|
}
|
||||||
elif response.status == 404:
|
elif response.status == 404:
|
||||||
logger.warning(f"User {username} not found on Lichess (404)")
|
logger.warning(f"User {username} not found on Lichess (404)")
|
||||||
return False
|
return False
|
||||||
|
|
|
||||||
|
|
@ -24,7 +24,7 @@ class MessageCounters:
|
||||||
cursor = conn.cursor()
|
cursor = conn.cursor()
|
||||||
commands = ['start', 'addgamer', 'addtoken', 'getgamers', 'delgamer',
|
commands = ['start', 'addgamer', 'addtoken', 'getgamers', 'delgamer',
|
||||||
'today', 'yesterday', 'week', 'setperiod', 'lang', 'resetlang',
|
'today', 'yesterday', 'week', 'setperiod', 'lang', 'resetlang',
|
||||||
'periodic_notification']
|
'periodic_notification', 'gamer_added']
|
||||||
for cmd in commands:
|
for cmd in commands:
|
||||||
cursor.execute('''
|
cursor.execute('''
|
||||||
INSERT OR IGNORE INTO message_counters (command, total_count, today_count, last_reset_date)
|
INSERT OR IGNORE INTO message_counters (command, total_count, today_count, last_reset_date)
|
||||||
|
|
|
||||||
|
|
@ -9,6 +9,11 @@ services:
|
||||||
environment:
|
environment:
|
||||||
- PYTHONUNBUFFERED=1
|
- PYTHONUNBUFFERED=1
|
||||||
restart: always
|
restart: always
|
||||||
|
logging:
|
||||||
|
driver: json-file
|
||||||
|
options:
|
||||||
|
max-size: "50m"
|
||||||
|
max-file: "3"
|
||||||
healthcheck:
|
healthcheck:
|
||||||
test: ["CMD", "python", "-c", "import urllib.request; urllib.request.urlopen('http://localhost:8000/health').read()"]
|
test: ["CMD", "python", "-c", "import urllib.request; urllib.request.urlopen('http://localhost:8000/health').read()"]
|
||||||
interval: 30s
|
interval: 30s
|
||||||
|
|
@ -28,6 +33,11 @@ services:
|
||||||
- PYTHONUNBUFFERED=1
|
- PYTHONUNBUFFERED=1
|
||||||
network_mode: "host"
|
network_mode: "host"
|
||||||
restart: always
|
restart: always
|
||||||
|
logging:
|
||||||
|
driver: json-file
|
||||||
|
options:
|
||||||
|
max-size: "50m"
|
||||||
|
max-file: "3"
|
||||||
depends_on:
|
depends_on:
|
||||||
- lichess-api
|
- lichess-api
|
||||||
healthcheck:
|
healthcheck:
|
||||||
|
|
@ -49,6 +59,11 @@ services:
|
||||||
- PYTHONUNBUFFERED=1
|
- PYTHONUNBUFFERED=1
|
||||||
network_mode: "host"
|
network_mode: "host"
|
||||||
restart: always
|
restart: always
|
||||||
|
logging:
|
||||||
|
driver: json-file
|
||||||
|
options:
|
||||||
|
max-size: "50m"
|
||||||
|
max-file: "3"
|
||||||
depends_on:
|
depends_on:
|
||||||
- lichess-api
|
- lichess-api
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -13,6 +13,11 @@ services:
|
||||||
volumes:
|
volumes:
|
||||||
- ./LichessWebServices:/app
|
- ./LichessWebServices:/app
|
||||||
restart: always
|
restart: always
|
||||||
|
logging:
|
||||||
|
driver: json-file
|
||||||
|
options:
|
||||||
|
max-size: "50m"
|
||||||
|
max-file: "3"
|
||||||
healthcheck:
|
healthcheck:
|
||||||
test: ["CMD", "python", "-c", "import urllib.request; urllib.request.urlopen('http://localhost:8000/health').read()"]
|
test: ["CMD", "python", "-c", "import urllib.request; urllib.request.urlopen('http://localhost:8000/health').read()"]
|
||||||
interval: 30s
|
interval: 30s
|
||||||
|
|
@ -35,6 +40,11 @@ services:
|
||||||
- PYTHONUNBUFFERED=1
|
- PYTHONUNBUFFERED=1
|
||||||
network_mode: "host"
|
network_mode: "host"
|
||||||
restart: always
|
restart: always
|
||||||
|
logging:
|
||||||
|
driver: json-file
|
||||||
|
options:
|
||||||
|
max-size: "50m"
|
||||||
|
max-file: "3"
|
||||||
depends_on:
|
depends_on:
|
||||||
- lichess-api
|
- lichess-api
|
||||||
healthcheck:
|
healthcheck:
|
||||||
|
|
@ -61,6 +71,11 @@ services:
|
||||||
- PYTHONUNBUFFERED=1
|
- PYTHONUNBUFFERED=1
|
||||||
network_mode: "host"
|
network_mode: "host"
|
||||||
restart: always
|
restart: always
|
||||||
|
logging:
|
||||||
|
driver: json-file
|
||||||
|
options:
|
||||||
|
max-size: "50m"
|
||||||
|
max-file: "3"
|
||||||
depends_on:
|
depends_on:
|
||||||
- lichess-api
|
- lichess-api
|
||||||
|
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue