import html
import logging
import time
from aiogram import Bot
from aiogram.types import ErrorEvent
from app.config import get_settings
log = logging.getLogger(__name__)
_last_notified: dict[str, float] = {}
NOTICE = "⚠️ Something went wrong. Please try again."
async def on_error(event: ErrorEvent, bot: Bot) -> bool:
exc = event.exception
log.error("Unhandled error while processing an update", exc_info=exc)
update = event.update
try: # never leave the user staring at a silent button
if update.callback_query:
await update.callback_query.answer(NOTICE[:190], show_alert=True)
elif update.message:
await update.message.answer(NOTICE)
except Exception:
pass
key = f"{type(exc).__name__}:{str(exc)[:80]}"
now = time.monotonic()
if now - _last_notified.get(key, 0) > 300: # at most one admin alert per distinct error / 5 min
_last_notified[key] = now
text = f"⚠️ {html.escape(type(exc).__name__)}\n{html.escape(str(exc)[:1500])}"
for admin_id in get_settings().admin_id_set:
try:
await bot.send_message(admin_id, text)
except Exception:
pass
return True