diff --git a/.env.example b/.env.example index 6eacaf2..93063cf 100644 --- a/.env.example +++ b/.env.example @@ -10,3 +10,10 @@ ADMINPANEL_TELEGRAM_BOT_TOKEN=8588876086:AAHoZncfhTCbul1BblpvnZMzvz7jAYVFmcw # anonymous requests to these endpoints with a 404; any valid token works, # it does not need to belong to a tracked player. LICHESS_APP_TOKEN=lip_xxxxxxxxxxxxxxxxxxxx + +# 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 diff --git a/LichessClientTG_bot/admin_bot.py b/LichessClientTG_bot/admin_bot.py index b12ab7c..960a80d 100644 --- a/LichessClientTG_bot/admin_bot.py +++ b/LichessClientTG_bot/admin_bot.py @@ -15,15 +15,13 @@ from telegram.ext import ( 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 message_counters import MessageCounters -# Configure logging -logging.basicConfig( - format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', - level=logging.INFO -) +# NOTE: no logging.basicConfig() at import time. This module is imported by bot.py, +# and a module-level basicConfig here used to win over bot.py's own one, silently +# forcing its level. Each process configures logging in its main(). logger = logging.getLogger(__name__) # Conversation states for system message @@ -86,12 +84,15 @@ class AdminBot: self.db.set_admin_chat_id(chat_id) 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: import urllib.parse import aiohttp 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 session.get(tts_url, timeout=aiohttp.ClientTimeout(total=5)) as response: if response.status == 200: @@ -490,6 +491,14 @@ def init_admin_bot(): def main(): """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() # Create application with Long Polling configuration @@ -504,9 +513,7 @@ def main(): # Add error handler async def error_handler(update: object, context: ContextTypes.DEFAULT_TYPE) -> None: """Log the error and send a telegram message to notify the developer.""" - logger.error(f"Exception while handling an update: {context.error}") - import traceback - logger.error(traceback.format_exc()) + logger.error("Exception while handling an update: %r", context.error, exc_info=context.error) application.add_error_handler(error_handler) diff --git a/LichessClientTG_bot/bot.py b/LichessClientTG_bot/bot.py index cdcfd35..bdc6cba 100644 --- a/LichessClientTG_bot/bot.py +++ b/LichessClientTG_bot/bot.py @@ -11,7 +11,7 @@ from telegram import Update, InlineKeyboardButton, InlineKeyboardMarkup from telegram.ext import ( Application, CommandHandler, CallbackQueryHandler, MessageHandler, filters, ContextTypes, ConversationHandler, - PicklePersistence + PicklePersistence, TypeHandler ) from telegram.error import Forbidden @@ -20,24 +20,27 @@ from config import ( TELEGRAM_BOT_TOKEN, PERIOD_OPTIONS, POLL_INTERVAL, POLL_TIMEOUT, DROP_PENDING_UPDATES, ALLOWED_UPDATES, LICHESS_STATS_API_BASE_URL, ADMINPANEL_TELEGRAM_BOT_TOKEN, - DATABASE_PATH + DATABASE_PATH, LOG_LEVEL ) from version import BOT_VERSION from database import Database from lichess_api import LichessAPI, InvalidTokenError 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 message_counters import MessageCounters from request_queue import get_request_queue import time import aiohttp -# Configure logging +# Configure logging (level from LOG_LEVEL env, INFO by default) logging.basicConfig( 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__) # Conversation states @@ -457,7 +460,6 @@ class LichessBot: possible_paths = [ image_path, # В папке бота 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 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 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): """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')): + 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() - user_id = update.effective_user.id lang = self.get_user_language_from_update(update) if not username: @@ -624,8 +632,9 @@ class LichessBot: return # Check if user exists on Lichess - user_exists = await self.lichess_api.check_user_exists(username) - if user_exists is None: + 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( @@ -633,12 +642,24 @@ class LichessBot: parse_mode='HTML' ) 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( t('user_not_found', lang, username=username) + '\n\n' + t('addgamer_prompt', lang), 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 user_gamers = self.db.get_user_gamers(user_id) @@ -658,7 +679,7 @@ class LichessBot: import sqlite3 with sqlite3.connect(self.db.db_path) as conn: 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() 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 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 user_gamers = self.db.get_user_gamers(user_id) @@ -1271,7 +1294,7 @@ class LichessBot: reply_markup = InlineKeyboardMarkup(keyboard) await update.message.reply_text( - "⏱️ Select player to set notification period:", + t('select_player_period', lang), reply_markup=reply_markup ) self.counters.increment('setperiod') @@ -1322,14 +1345,7 @@ class LichessBot: if period == 0: button_text = t('disable_notifications', lang) else: - # Format period text: minutes for < 60, hours for >= 60 - if period < 60: - button_text = f"⏰ {period} minutes" - elif period == 60: - button_text = "⏰ 1 hour" - else: - hours = period // 60 - button_text = f"⏰ {hours} hours" + button_text = f"⏰ {format_period(period, lang)}" keyboard.append([InlineKeyboardButton( button_text, callback_data=f"period_{gamer_id}_{period}" @@ -1388,16 +1404,8 @@ class LichessBot: t('notifications_disabled', lang, username=selected_gamer['username']) ) 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( - 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) @@ -1623,13 +1631,13 @@ class LichessBot: # Если следующий период еще не наступил, ждем if next_period_start > now: 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) # Используем сохраненное время как начало периода since_time = last_check_time # Конец периода - это момент, когда должен был начаться следующий период 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: # Мы отстаём от расписания (бэклог): если догонять по period_minutes # за раз, при большом отставании (недели простоя, много отслеживаемых @@ -1679,7 +1687,7 @@ class LichessBot: 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"📅 Unix timestamps: since={since_timestamp}, until_approx={until_timestamp_approx}") + logger.debug(f"📅 Unix timestamps: since={since_timestamp}, until_approx={until_timestamp_approx}") # Делаем запросы к API через очередь с обработкой ошибок games_data = None @@ -1687,7 +1695,7 @@ class LichessBot: try: # Добавляем запрос в очередь (будет выполнен с задержкой 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( self.lichess_api.get_games_period, gamer['username'], since_timestamp, until_timestamp_approx, @@ -1697,7 +1705,7 @@ class LichessBot: raise RuntimeError("Games period API returned no data") # Фиксируем фактическое время получения ответа 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: logger.error(f"❌ Error getting games data for {gamer['username']}: {e}") consecutive_errors += 1 @@ -1722,7 +1730,7 @@ class LichessBot: # (401), ретраить бессмысленно — это раньше приводило к вечному циклу # ретраев без продвижения чекпоинта (см. историю с Dor1zz). Вместо этого # отключаем пазлы для этой пары и продолжаем отслеживать партии как обычно. - logger.info(f"📥 Adding puzzles request to queue for {gamer['username']}") + logger.debug(f"📥 Adding puzzles request to queue for {gamer['username']}") try: puzzles_data = await self.request_queue.add_request( self.lichess_api.get_puzzles_period, @@ -1746,7 +1754,7 @@ class LichessBot: raise RuntimeError("Puzzles period API returned no data") # Обновляем фактическое время после получения ответа по пазлам 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 @@ -1756,7 +1764,7 @@ class LichessBot: total_games = 0 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 на верхнем уровне (приоритет) top_level_count = games_data.get('games_count', 0) @@ -1765,7 +1773,7 @@ class LichessBot: if top_level_count > 0: total_games = top_level_count 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: # Также проверяем data.total.games_played games_data_dict = games_data.get('data') @@ -1779,29 +1787,29 @@ class LichessBot: if total_games_played > 0: total_games = total_games_played 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: - 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: logger.warning(f"⚠️ No games_data returned for {username}") has_puzzles = False total_puzzles = 0 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 на верхнем уровне (приоритет) if puzzles_data.get('puzzles_in_period', 0) > 0: total_puzzles = puzzles_data.get('puzzles_in_period', 0) 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 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) 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, см. выше). @@ -1863,11 +1871,11 @@ class LichessBot: # 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())) - 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(): delay = (request_end_time - period_end_approx).total_seconds() 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: logger.info(f"Periodic check cancelled for {gamer['username']}") @@ -1891,9 +1899,34 @@ class LichessBot: await asyncio.sleep(backoff_seconds) 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): """Setup all handlers""" 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) # Must be added BEFORE general MessageHandler to avoid conflicts @@ -1938,6 +1971,13 @@ class LichessBot: 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""" # Initialize admin bot for notifications (admin bot runs as separate service) @@ -1968,10 +2008,16 @@ def main(): # Add error handler async def error_handler(update: object, context: ContextTypes.DEFAULT_TYPE) -> None: - """Log the error and send a telegram message to notify the developer.""" - logger.error(f"Exception while handling an update: {context.error}") - import traceback - logger.error(traceback.format_exc()) + """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) diff --git a/LichessClientTG_bot/config.py b/LichessClientTG_bot/config.py index b355981..4e3c0b7 100644 --- a/LichessClientTG_bot/config.py +++ b/LichessClientTG_bot/config.py @@ -6,6 +6,15 @@ load_dotenv() TELEGRAM_BOT_TOKEN = os.getenv("TELEGRAM_BOT_TOKEN") ADMINPANEL_TELEGRAM_BOT_TOKEN = os.getenv("ADMINPANEL_TELEGRAM_BOT_TOKEN") +# Python logging level for the bot processes (DEBUG/INFO/WARNING). INFO by default: +# the old code asked for DEBUG but never actually got it (admin_bot's basicConfig +# ran first at import time), and DEBUG would multiply an already multi-GB log. +LOG_LEVEL = os.getenv("LOG_LEVEL", "INFO").upper() + +# Optional text-to-speech announcer for admin events ("new user", "new player"). +# Only reachable from the home LAN, so it is unset on prod and skipped there. +TTS_URL = os.getenv("TTS_URL") or None + # Lichess API Configuration LICHESS_API_BASE_URL = "https://lichess.org/api" @@ -53,5 +62,8 @@ PERIOD_OPTIONS = [0, 15, 30, 60, 120, 180, 360, 720, 1440] # minutes (0=disable # Telegram Bot Long Polling Configuration POLL_INTERVAL = 1.0 # 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"] diff --git a/LichessClientTG_bot/database.py b/LichessClientTG_bot/database.py index 161b29d..004266a 100644 --- a/LichessClientTG_bot/database.py +++ b/LichessClientTG_bot/database.py @@ -108,7 +108,7 @@ class Database: # Initialize counters for all commands commands = ['start', 'addgamer', 'addtoken', 'getgamers', 'delgamer', 'today', 'yesterday', 'week', 'setperiod', 'lang', 'resetlang', - 'periodic_notification'] + 'periodic_notification', 'gamer_added'] for cmd in commands: cursor.execute(''' INSERT OR IGNORE INTO message_counters (command, total_count, today_count, last_reset_date) @@ -119,8 +119,73 @@ class Database: # Migrate tokens from gamers to user_gamers if needed 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") + + 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): """Migrate tokens from old gamers table to user_gamers table if needed""" @@ -222,8 +287,8 @@ class Database: with sqlite3.connect(self.db_path) as conn: cursor = conn.cursor() - # Check if gamer already exists - cursor.execute("SELECT id FROM gamers WHERE username = ?", (username,)) + # Check if gamer already exists (Lichess usernames are case-insensitive) + cursor.execute("SELECT id FROM gamers WHERE lower(username) = lower(?)", (username,)) existing = cursor.fetchone() if existing: diff --git a/LichessClientTG_bot/i18n.py b/LichessClientTG_bot/i18n.py index f31da60..9a9e695 100644 --- a/LichessClientTG_bot/i18n.py +++ b/LichessClientTG_bot/i18n.py @@ -141,6 +141,14 @@ TRANSLATIONS = { # Common '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 'select_language': "🌐 Select language / Выберите язык:", @@ -285,6 +293,14 @@ TRANSLATIONS = { # Common '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 'select_language': "🌐 Выберите язык / Select language:", @@ -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: """ Translate a key to the specified language. diff --git a/LichessClientTG_bot/lichess_api.py b/LichessClientTG_bot/lichess_api.py index 26cc162..fcc5ac0 100644 --- a/LichessClientTG_bot/lichess_api.py +++ b/LichessClientTG_bot/lichess_api.py @@ -121,14 +121,14 @@ class LichessAPI: params["rated_only"] = "true" if rated_only else "false" if include_games: 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 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: result = await response.json() - logger.info(f"🔍 LichessAPI.get_games_period: result={result}") + logger.debug(f"🔍 LichessAPI.get_games_period: result={result}") return result else: logger.error(f"Failed to get games period: {response.status}") @@ -170,14 +170,17 @@ class LichessAPI: logger.error(f"Error getting puzzles period: {e}") 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. - Returns True/False for a definitive answer (200/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. + Returns a dict for an existing account: + {'username': , 'disabled': bool} + (Lichess answers 200 for closed accounts too, with "disabled": true — the + 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() try: @@ -186,7 +189,11 @@ class LichessAPI: f"{self.lichess_base_url}/user/{username}" ) as response: 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: logger.warning(f"User {username} not found on Lichess (404)") return False diff --git a/LichessClientTG_bot/message_counters.py b/LichessClientTG_bot/message_counters.py index 303e976..5572328 100644 --- a/LichessClientTG_bot/message_counters.py +++ b/LichessClientTG_bot/message_counters.py @@ -24,7 +24,7 @@ class MessageCounters: cursor = conn.cursor() commands = ['start', 'addgamer', 'addtoken', 'getgamers', 'delgamer', 'today', 'yesterday', 'week', 'setperiod', 'lang', 'resetlang', - 'periodic_notification'] + 'periodic_notification', 'gamer_added'] for cmd in commands: cursor.execute(''' INSERT OR IGNORE INTO message_counters (command, total_count, today_count, last_reset_date) diff --git a/docker-compose.prod.yml b/docker-compose.prod.yml index d13e572..bcc3d3e 100644 --- a/docker-compose.prod.yml +++ b/docker-compose.prod.yml @@ -9,6 +9,11 @@ services: environment: - PYTHONUNBUFFERED=1 restart: always + logging: + driver: json-file + options: + max-size: "50m" + max-file: "3" healthcheck: test: ["CMD", "python", "-c", "import urllib.request; urllib.request.urlopen('http://localhost:8000/health').read()"] interval: 30s @@ -28,6 +33,11 @@ services: - PYTHONUNBUFFERED=1 network_mode: "host" restart: always + logging: + driver: json-file + options: + max-size: "50m" + max-file: "3" depends_on: - lichess-api healthcheck: @@ -49,6 +59,11 @@ services: - PYTHONUNBUFFERED=1 network_mode: "host" restart: always + logging: + driver: json-file + options: + max-size: "50m" + max-file: "3" depends_on: - lichess-api diff --git a/docker-compose.yml b/docker-compose.yml index 1200f0d..562284a 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -13,6 +13,11 @@ services: volumes: - ./LichessWebServices:/app restart: always + logging: + driver: json-file + options: + max-size: "50m" + max-file: "3" healthcheck: test: ["CMD", "python", "-c", "import urllib.request; urllib.request.urlopen('http://localhost:8000/health').read()"] interval: 30s @@ -35,6 +40,11 @@ services: - PYTHONUNBUFFERED=1 network_mode: "host" restart: always + logging: + driver: json-file + options: + max-size: "50m" + max-file: "3" depends_on: - lichess-api healthcheck: @@ -61,6 +71,11 @@ services: - PYTHONUNBUFFERED=1 network_mode: "host" restart: always + logging: + driver: json-file + options: + max-size: "50m" + max-file: "3" depends_on: - lichess-api