Add cancel ban process handler in admin handlers
- Introduced a new handler for canceling the ban process in `admin_handlers.py`, allowing users to easily abort ongoing ban actions. - Enhanced error handling and logging for the cancellation process to improve user experience and debugging. - Removed obsolete comments and cleaned up the code for better readability in the admin handlers. - Updated metrics middleware to streamline event processing and improve logging clarity, ensuring comprehensive metrics collection for all events.
This commit is contained in:
@@ -53,6 +53,29 @@ async def admin_panel(
|
||||
await handle_admin_error(message, e, state, "admin_panel")
|
||||
|
||||
|
||||
# ============================================================================
|
||||
# ХЕНДЛЕР ОТМЕНЫ
|
||||
# ============================================================================
|
||||
|
||||
@admin_router.message(
|
||||
ChatTypeFilter(chat_type=["private"]),
|
||||
StateFilter("AWAIT_BAN_TARGET", "AWAIT_BAN_DETAILS", "AWAIT_BAN_DURATION", "BAN_CONFIRMATION"),
|
||||
F.text == 'Отменить'
|
||||
)
|
||||
async def cancel_ban_process(
|
||||
message: types.Message,
|
||||
state: FSMContext,
|
||||
**kwargs
|
||||
):
|
||||
"""Отмена процесса блокировки"""
|
||||
try:
|
||||
current_state = await state.get_state()
|
||||
logger.info(f"Отмена процедуры блокировки из состояния: {current_state}")
|
||||
await return_to_admin_menu(message, state)
|
||||
except Exception as e:
|
||||
await handle_admin_error(message, e, state, "cancel_ban_process")
|
||||
|
||||
|
||||
@admin_router.message(
|
||||
ChatTypeFilter(chat_type=["private"]),
|
||||
StateFilter("ADMIN"),
|
||||
@@ -321,81 +344,3 @@ async def confirm_ban(
|
||||
await return_to_admin_menu(message, state)
|
||||
except Exception as e:
|
||||
await handle_admin_error(message, e, state, "confirm_ban")
|
||||
|
||||
|
||||
# ============================================================================
|
||||
# ХЕНДЛЕРЫ ОТМЕНЫ И НАВИГАЦИИ
|
||||
# ============================================================================
|
||||
|
||||
@admin_router.message(
|
||||
ChatTypeFilter(chat_type=["private"]),
|
||||
StateFilter("AWAIT_BAN_TARGET", "AWAIT_BAN_DETAILS", "AWAIT_BAN_DURATION", "BAN_CONFIRMATION"),
|
||||
F.text == 'Отменить'
|
||||
)
|
||||
async def cancel_ban_process(
|
||||
message: types.Message,
|
||||
state: FSMContext,
|
||||
**kwargs
|
||||
):
|
||||
"""Отмена процесса блокировки"""
|
||||
try:
|
||||
current_state = await state.get_state()
|
||||
logger.info(f"Отмена процедуры блокировки из состояния: {current_state}")
|
||||
await return_to_admin_menu(message, state)
|
||||
except Exception as e:
|
||||
await handle_admin_error(message, e, state, "cancel_ban_process")
|
||||
|
||||
|
||||
@admin_router.message(Command("test_metrics"))
|
||||
async def test_metrics_handler(
|
||||
message: types.Message,
|
||||
bot_db: MagicData("bot_db"),
|
||||
**kwargs
|
||||
):
|
||||
"""Тестовый хендлер для проверки метрик"""
|
||||
from helper_bot.utils.metrics import metrics
|
||||
|
||||
try:
|
||||
# Принудительно записываем тестовые метрики
|
||||
metrics.record_command("test_metrics", "admin_handler", "admin", "success")
|
||||
metrics.record_message("text", "private", "admin_handler")
|
||||
metrics.record_error("TestError", "admin_handler", "test_metrics_handler")
|
||||
|
||||
# Проверяем активных пользователей
|
||||
if hasattr(bot_db, 'connect') and hasattr(bot_db, 'cursor'):
|
||||
# Используем UNIX timestamp для сравнения с date_changed
|
||||
import time
|
||||
current_timestamp = int(time.time())
|
||||
one_day_ago = current_timestamp - (24 * 60 * 60) # 24 часа назад
|
||||
|
||||
active_users_query = """
|
||||
SELECT COUNT(DISTINCT user_id) as active_users
|
||||
FROM our_users
|
||||
WHERE date_changed > ?
|
||||
"""
|
||||
try:
|
||||
await bot_db.connect()
|
||||
await bot_db.cursor.execute(active_users_query, (one_day_ago,))
|
||||
result = await bot_db.cursor.fetchone()
|
||||
active_users = result[0] if result else 0
|
||||
finally:
|
||||
await bot_db.close()
|
||||
else:
|
||||
active_users = "N/A"
|
||||
|
||||
# ВАЖНО: Записываем метрику активных пользователей
|
||||
if isinstance(active_users, int):
|
||||
metrics.set_active_users(active_users, "daily")
|
||||
metrics.set_active_users(active_users, "total")
|
||||
|
||||
await message.answer(
|
||||
f"✅ Тестовые метрики записаны\n"
|
||||
f"📊 Активных пользователей: {active_users}\n"
|
||||
f"🔧 Проверьте Prometheus метрики\n"
|
||||
f"📈 Метрика active_users обновлена"
|
||||
)
|
||||
|
||||
except Exception as e:
|
||||
await message.answer(f"❌ Ошибка тестирования метрик: {e}")
|
||||
# Записываем ошибку в метрики
|
||||
metrics.record_error(str(type(e).__name__), "admin_handler", "test_metrics_handler")
|
||||
|
||||
Reference in New Issue
Block a user