bug fix notification
This commit is contained in:
parent
0e66a05b90
commit
3619eab74e
1 changed files with 77 additions and 13 deletions
|
|
@ -86,6 +86,40 @@ class LichessBot:
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.error(f"Fallback admin notification failed: {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):
|
async def test_admin_notify(self, update: Update, context: ContextTypes.DEFAULT_TYPE):
|
||||||
"""Manual test to verify admin notifications delivery path."""
|
"""Manual test to verify admin notifications delivery path."""
|
||||||
user = update.effective_user
|
user = update.effective_user
|
||||||
|
|
@ -113,21 +147,37 @@ class LichessBot:
|
||||||
"""Start periodic tasks for all user-gamer pairs that have periods set"""
|
"""Start periodic tasks for all user-gamer pairs that have periods set"""
|
||||||
try:
|
try:
|
||||||
gamers_with_periods = self.db.get_all_gamers_with_periods()
|
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:
|
for gamer in gamers_with_periods:
|
||||||
if gamer['period_minutes'] > 0:
|
if gamer['period_minutes'] > 0:
|
||||||
user_id = gamer['user_id']
|
user_id = gamer['user_id']
|
||||||
# Start periodic task with user_id and gamer
|
# Start periodic task with user_id and gamer
|
||||||
await self.start_periodic_task(gamer, user_id, gamer['period_minutes'])
|
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
|
# Start daily counter reset task
|
||||||
asyncio.create_task(self.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:
|
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):
|
async def daily_counter_reset_task(self):
|
||||||
"""Background task to reset daily counters at midnight"""
|
"""Background task to reset daily counters at midnight"""
|
||||||
|
|
@ -170,6 +220,7 @@ class LichessBot:
|
||||||
)
|
)
|
||||||
# Notify admin bot about new user
|
# Notify admin bot about new user
|
||||||
if is_new_user:
|
if is_new_user:
|
||||||
|
try:
|
||||||
admin_bot = get_admin_bot()
|
admin_bot = get_admin_bot()
|
||||||
if admin_bot:
|
if admin_bot:
|
||||||
await admin_bot.notify_new_user(
|
await admin_bot.notify_new_user(
|
||||||
|
|
@ -177,6 +228,18 @@ class LichessBot:
|
||||||
username=user.username,
|
username=user.username,
|
||||||
first_name=user.first_name
|
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)
|
lang = self.get_user_language_from_update(update)
|
||||||
start_msg = t('start_message', lang)
|
start_msg = t('start_message', lang)
|
||||||
|
|
@ -1157,6 +1220,7 @@ class LichessBot:
|
||||||
|
|
||||||
# Отправляем уведомление только если есть реальная активность
|
# Отправляем уведомление только если есть реальная активность
|
||||||
if has_games or has_puzzles:
|
if has_games or has_puzzles:
|
||||||
|
logger.info(f"📊 Activity detected for {gamer['username']}, preparing notification...")
|
||||||
try:
|
try:
|
||||||
# Get user language from database
|
# Get user language from database
|
||||||
user_lang = self.db.get_user_language(user_id)
|
user_lang = self.db.get_user_language(user_id)
|
||||||
|
|
@ -1182,7 +1246,7 @@ class LichessBot:
|
||||||
# Обновляем время начала даже при ошибке отправки, чтобы не зацикливаться
|
# Обновляем время начала даже при ошибке отправки, чтобы не зацикливаться
|
||||||
self.period_start_times[task_key] = now
|
self.period_start_times[task_key] = now
|
||||||
else:
|
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
|
self.period_start_times[task_key] = now
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.error(f"Error formatting notification for {gamer['username']}: {e}")
|
logger.error(f"Error formatting notification for {gamer['username']}: {e}")
|
||||||
|
|
@ -1191,7 +1255,7 @@ class LichessBot:
|
||||||
# Обновляем время начала даже при ошибке форматирования
|
# Обновляем время начала даже при ошибке форматирования
|
||||||
self.period_start_times[task_key] = now
|
self.period_start_times[task_key] = now
|
||||||
else:
|
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
|
self.period_start_times[task_key] = now
|
||||||
|
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue