Refactor broadcast confirmation prompt and enhance sync notification handling

- Updated the broadcast confirmation prompt to display the full message instead of a truncated preview.
- Improved error handling in the sync process by removing character limits on error details and ensuring comprehensive logging.
- Added a notification feature to inform admins about the panel synchronization status, including success and failure details.
- Enhanced localization for the broadcast confirmation prompt and added new log messages for sync notifications.
This commit is contained in:
machka-pasla
2025-08-06 19:04:03 +03:00
parent f8e3bee52a
commit a42f80160b
5 changed files with 77 additions and 12 deletions
+1 -2
View File
@@ -84,8 +84,7 @@ async def process_broadcast_message_handler(
broadcast_entities=entities,
)
preview_snippet = (text[:200] + "...") if len(text) > 200 else text
confirmation_prompt = _("admin_broadcast_confirm_prompt", message_preview=preview_snippet)
confirmation_prompt = _("admin_broadcast_confirm_prompt", message_preview=text)
await message.answer(
confirmation_prompt,
+22 -7
View File
@@ -7,6 +7,7 @@ from datetime import datetime, timezone
from config.settings import Settings
from bot.services.panel_api_service import PanelApiService
from bot.services.notification_service import notify_admin_panel_sync
from db.dal import user_dal, subscription_dal, panel_sync_dal
@@ -222,7 +223,7 @@ async def perform_sync(panel_service: PanelApiService, session: AsyncSession,
except Exception as e_sync_global:
await session.rollback()
logging.error(f"Global error during sync: {e_sync_global}", exc_info=True)
error_detail = f"Unexpected error during sync: {str(e_sync_global)[:200]}"
error_detail = f"Unexpected error during sync: {str(e_sync_global)}"
await panel_sync_dal.update_panel_sync_status(
session, "failed", error_detail, panel_records_checked, subscriptions_synced_count
@@ -286,7 +287,7 @@ async def sync_command_handler(
users_synced=sync_result.get("users_synced", 0),
subs_synced=sync_result.get("subs_synced", 0),
errors_count=len(errors),
error_details_preview=error_preview[:200] + "..." if len(error_preview) > 200 else error_preview
error_details_preview=error_preview
)
await bot.send_message(target_chat_id, final_message)
else:
@@ -297,10 +298,28 @@ async def sync_command_handler(
subs_synced=sync_result.get("subs_synced", 0)
)
await bot.send_message(target_chat_id, _("sync_completed", status="Success", details=final_message))
# Send notification to log channel with proper thread handling
try:
await notify_admin_panel_sync(
bot, settings, i18n, status, details,
sync_result.get("users_processed", 0),
sync_result.get("subs_synced", 0)
)
except Exception as e_notification:
logging.error(f"Failed to send sync notification: {e_notification}")
except Exception as e_sync_global:
logging.error(f"Global error during /sync command: {e_sync_global}", exc_info=True)
await bot.send_message(target_chat_id, _("sync_failed", details=str(e_sync_global)))
# Send notification to log channel about failure
try:
await notify_admin_panel_sync(
bot, settings, i18n, "failed", str(e_sync_global), 0, 0
)
except Exception as e_notification:
logging.error(f"Failed to send sync failure notification: {e_notification}")
@router.message(Command("syncstatus"))
@@ -323,11 +342,7 @@ async def sync_status_command_handler(
)
details_val = status_record_model.details
details_str = (
(details_val[:200] + "...")
if details_val and len(details_val) > 200
else (details_val or "N/A")
)
details_str = details_val or "N/A"
response_text = (
f"<b>{_('admin_stats_last_sync_header')}</b>\n"
+46 -1
View File
@@ -221,6 +221,42 @@ class NotificationService:
# Send to log channel
await self._send_to_log_channel(message)
async def notify_panel_sync(self, status: str, details: str,
users_processed: int, subs_synced: int,
username: Optional[str] = None):
"""Send notification about panel synchronization"""
if not getattr(self.settings, 'LOG_PANEL_SYNC', True):
return
admin_lang = self.settings.DEFAULT_LANGUAGE
_ = lambda k, **kw: self.i18n.gettext(admin_lang, k, **kw) if self.i18n else k
# Status emoji based on sync result
status_emoji = {
"completed": "",
"completed_with_errors": "⚠️",
"failed": ""
}.get(status, "🔄")
message = _(
"log_panel_sync",
default="{status_emoji} <b>Синхронизация с панелью</b>\n\n"
"📊 Статус: <b>{status}</b>\n"
"👥 Обработано пользователей: <b>{users_processed}</b>\n"
"📋 Синхронизировано подписок: <b>{subs_synced}</b>\n"
"🕐 Время: {timestamp}\n\n"
"📝 Детали:\n{details}",
status_emoji=status_emoji,
status=status,
users_processed=users_processed,
subs_synced=subs_synced,
timestamp=datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M:%S %Z"),
details=details
)
# Send to log channel
await self._send_to_log_channel(message)
async def notify_suspicious_promo_attempt(
self, user_id: int, suspicious_input: str,
username: Optional[str] = None, first_name: Optional[str] = None):
@@ -297,4 +333,13 @@ async def notify_admin_promo_activation(bot: Bot, settings: Settings,
user_id=user_id,
code=code,
bonus_days=bonus_days,
)
)
async def notify_admin_panel_sync(bot: Bot, settings: Settings,
i18n: JsonI18n, status: str,
details: str, users_processed: int,
subs_synced: int) -> None:
"""Send notification to admins about panel sync (legacy)"""
notification_service = NotificationService(bot, settings, i18n)
await notification_service.notify_panel_sync(status, details, users_processed, subs_synced)