Practica2025/bot/router.py
2025-12-29 04:26:49 +03:00

44 lines
1.5 KiB
Python

import logging
from django.utils import translation
logger = logging.getLogger(__name__)
class CallbackRouter:
def __init__(self):
self.routes = {}
def route(self, pattern):
"""Декоратор для регистрации обработчика callback"""
def decorator(func):
self.routes[pattern] = func
return func
return decorator
async def handle(self, update, context):
query = update.callback_query
await query.answer()
data = query.data
# Простой протокол: "action:payload"
action = data.split(':')[0]
handler = self.routes.get(action)
if handler:
# Берем язык из данных пользователя (по умолчанию ru)
user_lang = context.user_data.get('lang', 'ru')
translation.activate(user_lang)
try:
await handler(update, context)
except Exception as e:
logger.error(f"Error in handler {action}: {e}")
finally:
translation.deactivate()
else:
try:
await query.edit_message_text("Неизвестная команда / Unknown command")
except Exception:
pass
# Глобальный объект роутера, который мы импортируем в handlers.py
router = CallbackRouter()