Files
telegram-helper-bot/helper_bot/middlewares/blacklist_middleware.py
Andrey f097d69dd4 Enhance Makefile and update metrics handling in bot
- Added new commands in the Makefile for restarting individual services: `restart-bot`, `restart-prometheus`, and `restart-grafana`.
- Updated Prometheus and Grafana dashboard expressions for better metrics aggregation.
- Removed the `main_with_metrics.py` file and integrated metrics handling directly into the main bot file.
- Refactored middleware to improve metrics tracking and error handling across message and callback processing.
- Optimized metrics recording with enhanced bucket configurations for better performance monitoring.
2025-08-29 18:23:17 +03:00

49 lines
2.6 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
from typing import Dict, Any
import html
from aiogram import BaseMiddleware, types
from aiogram.types import TelegramObject, Message, CallbackQuery
from helper_bot.utils.base_dependency_factory import get_global_instance
from logs.custom_logger import logger
bdf = get_global_instance()
BotDB = bdf.get_db()
class BlacklistMiddleware(BaseMiddleware):
async def __call__(self, handler, event: TelegramObject, data: Dict[str, Any]) -> Any:
# Проверяем тип события и получаем пользователя
user = None
if isinstance(event, Message):
user = event.from_user
elif isinstance(event, CallbackQuery):
user = event.from_user
# Если это не сообщение или callback, пропускаем проверку
if not user:
return await handler(event, data)
logger.info(f'Вызов BlacklistMiddleware для пользователя {user.username}')
# Используем асинхронную версию для предотвращения блокировки
if await BotDB.check_user_in_blacklist_async(user_id=user.id):
logger.info(f'BlacklistMiddleware результат для пользователя: {user.username} заблокирован!')
user_info = await BotDB.get_blacklist_users_by_id_async(user.id)
# Экранируем потенциально проблемные символы
reason = html.escape(str(user_info[2])) if user_info[2] else "Не указана"
date_unban = html.escape(str(user_info[3])) if user_info[3] else "Не указана"
# Отправляем сообщение в зависимости от типа события
if isinstance(event, Message):
await event.answer(
f"<b>Ты заблокирован.</b>\n<b>Причина блокировки:</b> {reason}\n<b>Дата разбана:</b> {date_unban}")
elif isinstance(event, CallbackQuery):
await event.answer(
f"<b>Ты заблокирован.</b>\n<b>Причина блокировки:</b> {reason}\n<b>Дата разбана:</b> {date_unban}",
show_alert=True)
return False
logger.info(f'BlacklistMiddleware результат для пользователя: {user.username} доступ разрешен')
return await handler(event, data)