bug fix notification

This commit is contained in:
vrubelroman 2025-11-18 14:03:06 +03:00
parent 0e66a05b90
commit 3619eab74e

View file

@ -86,6 +86,40 @@ class LichessBot:
except Exception as e:
logger.error(f"Fallback admin notification failed: {e}")
async def _notify_admin_new_user(self, user_id: int, username: Optional[str], first_name: Optional[str]):
"""Notify admin about new Telegram user (fallback method)."""
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"
username_text = f"@{username}" if username else "без username"
name_text = first_name if first_name else "без имени"
message = (
f"🆕 <b>Новый пользователь Telegram</b>\n\n"
f"ID: {user_id}\n"
f"Username: {username_text}\n"
f"Имя: {name_text}"
)
logger.info(f"Sending admin notification via direct API to chat_id={admin_chat_id}")
import aiohttp
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:
logger.info(f"Admin notification sent successfully via direct API")
else:
error_text = await response.text()
logger.error(f"Failed to send admin notification: {response.status} - {error_text}")
except Exception as e:
logger.error(f"Failed to send admin notification via API: {e}")
import traceback
logger.error(traceback.format_exc())
async def test_admin_notify(self, update: Update, context: ContextTypes.DEFAULT_TYPE):
"""Manual test to verify admin notifications delivery path."""
user = update.effective_user
@ -113,21 +147,37 @@ class LichessBot:
"""Start periodic tasks for all user-gamer pairs that have periods set"""
try:
gamers_with_periods = self.db.get_all_gamers_with_periods()
logger.info(f"Found {len(gamers_with_periods)} user-gamer pairs with periodic notifications")
# Get statistics
import sqlite3
with sqlite3.connect(self.db.db_path) as conn:
cursor = conn.cursor()
cursor.execute("SELECT COUNT(*) FROM telegram_users")
total_users = cursor.fetchone()[0]
cursor.execute("SELECT COUNT(DISTINCT username) FROM gamers")
total_gamers = cursor.fetchone()[0]
logger.info(f"📊 Statistics: {total_users} users, {total_gamers} tracked gamers")
logger.info(f"🔔 Found {len(gamers_with_periods)} user-gamer pairs with periodic notifications enabled")
if len(gamers_with_periods) == 0:
logger.warning("⚠️ No periodic notifications configured! Users need to set periods using /setperiod")
for gamer in gamers_with_periods:
if gamer['period_minutes'] > 0:
user_id = gamer['user_id']
# Start periodic task with user_id and gamer
await self.start_periodic_task(gamer, user_id, gamer['period_minutes'])
logger.info(f"Started periodic task for {gamer['username']} (user {user_id}) with period {gamer['period_minutes']} minutes")
logger.info(f"Started periodic task for {gamer['username']} (user {user_id}) with period {gamer['period_minutes']} minutes")
# Start daily counter reset task
asyncio.create_task(self.daily_counter_reset_task())
logger.info("Started daily counter reset task")
logger.info("Started daily counter reset task")
except Exception as e:
logger.error(f"Error starting existing periodic tasks: {e}")
logger.error(f"❌ Error starting existing periodic tasks: {e}")
import traceback
logger.error(traceback.format_exc())
async def daily_counter_reset_task(self):
"""Background task to reset daily counters at midnight"""
@ -170,6 +220,7 @@ class LichessBot:
)
# Notify admin bot about new user
if is_new_user:
try:
admin_bot = get_admin_bot()
if admin_bot:
await admin_bot.notify_new_user(
@ -177,6 +228,18 @@ class LichessBot:
username=user.username,
first_name=user.first_name
)
else:
# Fallback: direct API call
await self._notify_admin_new_user(user.id, user.username, user.first_name)
except Exception as e:
logger.error(f"Failed to notify admin about new user: {e}")
import traceback
logger.error(traceback.format_exc())
# Try fallback
try:
await self._notify_admin_new_user(user.id, user.username, user.first_name)
except Exception as e2:
logger.error(f"Fallback notification also failed: {e2}")
lang = self.get_user_language_from_update(update)
start_msg = t('start_message', lang)
@ -1157,6 +1220,7 @@ class LichessBot:
# Отправляем уведомление только если есть реальная активность
if has_games or has_puzzles:
logger.info(f"📊 Activity detected for {gamer['username']}, preparing notification...")
try:
# Get user language from database
user_lang = self.db.get_user_language(user_id)
@ -1182,7 +1246,7 @@ class LichessBot:
# Обновляем время начала даже при ошибке отправки, чтобы не зацикливаться
self.period_start_times[task_key] = now
else:
logger.error(f"Application not initialized, cannot send notification for {gamer['username']}")
logger.error(f"Application not initialized, cannot send notification for {gamer['username']} to user {user_id}")
self.period_start_times[task_key] = now
except Exception as e:
logger.error(f"Error formatting notification for {gamer['username']}: {e}")
@ -1191,7 +1255,7 @@ class LichessBot:
# Обновляем время начала даже при ошибке форматирования
self.period_start_times[task_key] = now
else:
logger.info(f"No activity found for {gamer['username']} in the last {period_minutes} minutes")
logger.debug(f"⏭️ No activity found for {gamer['username']} in the last {period_minutes} minutes")
# Обновляем время начала даже если нет активности, чтобы не зацикливаться
self.period_start_times[task_key] = now