bug fixed /addplayer

This commit is contained in:
vrubel 2025-11-16 13:38:25 +03:00
parent 3e61fa33c4
commit 1d485fc100
3 changed files with 93 additions and 32 deletions

View file

@ -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"🎮 <b>Добавлен новый игрок для отслеживания</b>\n\n"
f"Игрок: <a href=\"{lichess_url}\">{player_username}</a>\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_"))