From 1d485fc100f137e074282ea6a75a99c8b26c41e5 Mon Sep 17 00:00:00 2001 From: vrubel Date: Sun, 16 Nov 2025 13:38:25 +0300 Subject: [PATCH] bug fixed /addplayer --- LichessClientTG_bot/bot.py | 108 +++++++++++++++++++++++--------- LichessClientTG_bot/config.py | 16 ++++- LichessClientTG_bot/database.py | 1 + 3 files changed, 93 insertions(+), 32 deletions(-) diff --git a/LichessClientTG_bot/bot.py b/LichessClientTG_bot/bot.py index 4aa3143..d43e2a8 100644 --- a/LichessClientTG_bot/bot.py +++ b/LichessClientTG_bot/bot.py @@ -22,6 +22,7 @@ from i18n import t from admin_bot import get_admin_bot, init_admin_bot from message_counters import MessageCounters import time +import aiohttp # Configure logging logging.basicConfig( @@ -42,6 +43,58 @@ class LichessBot: self.application = None # Will be set when application is created self.counters = MessageCounters() # Message counters + async def _notify_admin_new_player(self, player_username: str, added_by_user_id: int, added_by_username: Optional[str]): + """Notify admin about newly linked player (always try to send).""" + try: + admin_bot = get_admin_bot() + if admin_bot: + logger.info("Sending admin notification via admin_bot instance") + await admin_bot.notify_new_player( + player_username=player_username, + added_by_user_id=added_by_user_id, + added_by_username=added_by_username + ) + return + except Exception as e: + logger.warning(f"notify_new_player via admin_bot failed: {e}") + # Fallback: direct API call using admin bot token and chat id from DB + try: + admin_chat_id = self.db.get_admin_chat_id() + if not admin_chat_id: + logger.warning("Admin chat id is not set; cannot send admin notification.") + return + url = f"https://api.telegram.org/bot{ADMINPANEL_TELEGRAM_BOT_TOKEN}/sendMessage" + added_by_text = f"@{added_by_username}" if added_by_username else f"ID: {added_by_user_id}" + lichess_url = f"https://lichess.org/@/{player_username}" + message = ( + f"🎮 Добавлен новый игрок для отслеживания\n\n" + f"Игрок: {player_username}\n" + f"Добавил: {added_by_text}" + ) + logger.info(f"Sending admin notification via direct API to chat_id={admin_chat_id}") + async with aiohttp.ClientSession() as session: + async with session.post(url, json={ + "chat_id": admin_chat_id, + "text": message, + "parse_mode": "HTML" + }) as response: + if response.status != 200: + error_text = await response.text() + logger.error(f"Failed to send admin notification (fallback): {response.status} - {error_text}") + else: + logger.info("Admin notification sent successfully via direct API") + except Exception as e: + logger.error(f"Fallback admin notification failed: {e}") + + async def test_admin_notify(self, update: Update, context: ContextTypes.DEFAULT_TYPE): + """Manual test to verify admin notifications delivery path.""" + user = update.effective_user + try: + await self._notify_admin_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: """Always return English language""" # Update user info in database @@ -189,6 +242,12 @@ class LichessBot: 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._notify_admin_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 # Check if gamer already exists @@ -210,16 +269,14 @@ class LichessBot: if len(user_gamers) == 1: self.db.set_user_active_gamer(user_id, gamer_id) - # Notify admin bot about new player (only if it's a new gamer) - if is_new_gamer: - admin_bot = get_admin_bot() - if admin_bot: - user_obj = update.effective_user - await admin_bot.notify_new_player( - player_username=username, - added_by_user_id=user_id, - added_by_username=user_obj.username if user_obj else None - ) + # Notify admin bot about new player (always notify on link) + try: + user_obj = update.effective_user + await self._notify_admin_new_player( + username, user_id, user_obj.username if user_obj else None + ) + except Exception as e: + logger.error(f"Admin notify failed after adding gamer with token: {e}") await update.message.reply_text( t('gamer_added_with_token', lang, username=username) @@ -279,27 +336,15 @@ class LichessBot: if len(user_gamers) == 1: self.db.set_user_active_gamer(user_id, gamer_id) - # Notify admin bot about new player (only if it's a new gamer) - if is_new_gamer: - logger.info(f"New gamer detected: {username}, notifying admin bot...") - admin_bot = get_admin_bot() - if admin_bot: - user_obj = update.effective_user - try: - await admin_bot.notify_new_player( - player_username=username, - added_by_user_id=user_id, - added_by_username=user_obj.username if user_obj else None - ) - logger.info(f"Admin bot notification sent for player {username}") - except Exception as e: - logger.error(f"Failed to notify admin bot: {e}") - import traceback - logger.error(traceback.format_exc()) - else: - logger.warning("Admin bot not available for notification") - else: - logger.info(f"Gamer {username} already exists, skipping admin notification") + # Notify admin bot about player link (always notify) + try: + user_obj = update.effective_user + await self._notify_admin_new_player( + username, user_id, user_obj.username if user_obj else None + ) + logger.info(f"Admin notification processed for player {username}") + except Exception as e: + logger.error(f"Failed to notify admin about new player link: {e}") lang = self.get_user_language_from_update(update) await update.message.reply_text( @@ -942,6 +987,7 @@ class LichessBot: application.add_handler(CommandHandler("setperiod", self.setperiod)) application.add_handler(CommandHandler("lang", self.check_language)) application.add_handler(CommandHandler("resetlang", self.reset_language)) + application.add_handler(CommandHandler("test_admin_notify", self.test_admin_notify)) # Callback handlers application.add_handler(CallbackQueryHandler(self.select_gamer, pattern="^select_")) diff --git a/LichessClientTG_bot/config.py b/LichessClientTG_bot/config.py index e32207b..38d606a 100644 --- a/LichessClientTG_bot/config.py +++ b/LichessClientTG_bot/config.py @@ -14,7 +14,21 @@ LICHESS_API_BASE_URL = "https://lichess.org/api" LICHESS_STATS_API_BASE_URL = "http://localhost:8001" # For Docker container access # Database Configuration -DATABASE_PATH = "/app/data/lichess_bot.db" +def _resolve_database_path() -> str: + # 1) Explicit env var has highest priority + db_from_env = os.getenv("DATABASE_PATH") + if db_from_env: + return db_from_env + # 2) Docker default if volume is mounted + docker_data_dir = "/app/data" + if os.path.isdir(docker_data_dir): + return os.path.join(docker_data_dir, "lichess_bot.db") + # 3) Local development fallback (repo data dir) + repo_data_dir = os.path.join(os.path.dirname(__file__), "data") + os.makedirs(repo_data_dir, exist_ok=True) + return os.path.join(repo_data_dir, "lichess_bot.db") + +DATABASE_PATH = _resolve_database_path() # Period options for /setperiod command PERIOD_OPTIONS = [0, 15, 30, 60, 120, 180] # minutes diff --git a/LichessClientTG_bot/database.py b/LichessClientTG_bot/database.py index 40f8d54..9317b2a 100644 --- a/LichessClientTG_bot/database.py +++ b/LichessClientTG_bot/database.py @@ -14,6 +14,7 @@ class Database: """Initialize database tables""" with sqlite3.connect(self.db_path) as conn: cursor = conn.cursor() + logger.info(f"Using database at: {self.db_path}") # Create telegram_users table (Telegram bot users) cursor.execute('''