From 5f50cfeaee9f42001373300ba419589b1c872abf Mon Sep 17 00:00:00 2001 From: machka pasla Date: Sat, 11 Oct 2025 16:53:26 +0300 Subject: [PATCH] broadcast real time logs --- bot/handlers/admin/broadcast.py | 67 ++++++++++++++++++++++++++++----- locales/en.json | 2 +- locales/ru.json | 1 + 3 files changed, 60 insertions(+), 10 deletions(-) diff --git a/bot/handlers/admin/broadcast.py b/bot/handlers/admin/broadcast.py index ce3821d..d395eca 100644 --- a/bot/handlers/admin/broadcast.py +++ b/bot/handlers/admin/broadcast.py @@ -334,11 +334,12 @@ async def confirm_broadcast_callback_handler( await session.rollback() logging.error(f"Error committing broadcast logs: {e_commit}") - # Get queue stats for detailed report + # Prepare queue stats presentation queue_stats = queue_manager.get_queue_stats() - - result_message = ( - _( + back_keyboard = get_back_to_admin_panel_keyboard(current_lang, i18n) + + def build_queue_status(stats: dict) -> str: + return _( "broadcast_queue_result", default=( "🚀 Рассылка поставлена в очередь!\n" @@ -351,15 +352,63 @@ async def confirm_broadcast_callback_handler( ), sent_count=sent_count, failed_count=failed_count, - user_queue_size=queue_stats["user_queue_size"], - group_queue_size=queue_stats["group_queue_size"], + user_queue_size=stats["user_queue_size"], + group_queue_size=stats["group_queue_size"], ) - ) - await callback.message.answer( + + result_message = build_queue_status(queue_stats) + + status_message = await callback.message.answer( result_message, - reply_markup=get_back_to_admin_panel_keyboard(current_lang, i18n), + reply_markup=back_keyboard, ) + async def auto_update_queue_status() -> None: + """Refresh queue stats message twice per second via message edit.""" + last_text = result_message + # Update for up to 2 minutes (240 iterations at 0.5s intervals) + max_iterations = 240 + for _ in range(max_iterations): + await asyncio.sleep(0.5) + + stats = queue_manager.get_queue_stats() + new_text = build_queue_status(stats) + queues_drained = ( + stats["user_queue_size"] == 0 + and stats["group_queue_size"] == 0 + and not stats.get("user_queue_processing") + and not stats.get("group_queue_processing") + ) + + if new_text != last_text: + try: + await status_message.edit_text( + new_text, + reply_markup=back_keyboard, + ) + last_text = new_text + except TelegramBadRequest as e: + if "message is not modified" in str(e): + last_text = new_text + else: + logging.debug( + "Broadcast queue auto-update stopped: %s", e + ) + break + except Exception as e: + logging.debug( + "Broadcast queue auto-update unexpected error: %s", e + ) + break + + if queues_drained: + # Final refresh already attempted; exit loop. + break + else: + logging.debug("Broadcast queue auto-update reached time limit.") + + asyncio.create_task(auto_update_queue_status()) + elif action == "cancel": await callback.message.edit_text( _("admin_broadcast_cancelled"), diff --git a/locales/en.json b/locales/en.json index 6d6b0a3..43dc91b 100644 --- a/locales/en.json +++ b/locales/en.json @@ -5,7 +5,7 @@ "menu_activate_trial_button": "🆓 Free Trial", "menu_subscribe_inline": "🚀 Purchase", "menu_my_subscription_inline": "🔐 My Subscription", - "no_subscription options available": "Subscription issuance is not configured by the bot administrator", + "no_subscription_options_available": "Subscription issuance is not configured by the bot administrator", "menu_referral_inline": "🎁 Referrals", "referral_no_bonuses_configured": "Sorry, the referral program is currently disabled", "menu_apply_promo_button": "🎟 Promo Code", diff --git a/locales/ru.json b/locales/ru.json index 686bc23..0fd7895 100644 --- a/locales/ru.json +++ b/locales/ru.json @@ -131,6 +131,7 @@ "admin_broadcast_cancelled": "Рассылка отменена.", "admin_broadcast_cancelled_alert": "Рассылка отменена!", "admin_broadcast_cancelled_nav_back": "Рассылка отменена. Вы возвращены в админ-панель.", + "broadcast_queue_result": "🚀 Рассылка поставлена в очередь!\n📤 В очередь добавлено: {sent_count}\n❌ Ошибок: {failed_count}\n\n📊 Статус очередей:\n👥 Очередь пользователей: {user_queue_size} сообщений\n📢 Очередь групп: {group_queue_size} сообщений\n\nℹ️ Сообщения будут отправлены автоматически с соблюдением лимитов Telegram.", "admin_promo_invalid_code_format": "Код должен быть от 3 до 30 символов и содержать только буквы и цифры.", "admin_promo_invalid_bonus_days": "Количество бонусных дней должно быть положительным числом.", "admin_promo_invalid_max_activations": "Максимальное количество активаций должно быть положительным числом.",