Enhance inline query handling and admin statistics retrieval
- Updated inline query handler to include settings for thumbnail URLs, improving the customization of inline results. - Refactored admin statistics retrieval to utilize new data structures for user status and bandwidth statistics, enhancing clarity and accuracy in reporting. - Removed deprecated help result creation code to streamline the inline query functionality. - Added new settings for inline mode thumbnail URLs to improve maintainability and flexibility in the codebase.
This commit is contained in:
@@ -106,7 +106,6 @@ async def admin_panel_actions_callback_handler(
|
||||
await admin_logs_handlers.display_logs_menu(callback, i18n_data,
|
||||
settings, session)
|
||||
elif action == "promo_management":
|
||||
from . import promo_codes as admin_promo_handlers
|
||||
await admin_promo_handlers.promo_management_handler(
|
||||
callback, i18n_data, settings, session)
|
||||
elif action == "sync_panel":
|
||||
|
||||
@@ -70,58 +70,66 @@ async def show_statistics_handler(callback: types.CallbackQuery,
|
||||
|
||||
if system_stats:
|
||||
users = system_stats.get('users', {})
|
||||
active_users = users.get('active', 0)
|
||||
disabled_users = users.get('disabled', 0)
|
||||
expired_users = users.get('expired', 0)
|
||||
limited_users = users.get('limited', 0)
|
||||
total_users = users.get('total', 0)
|
||||
status_counts = users.get('statusCounts', {})
|
||||
online_stats = system_stats.get('onlineStats', {})
|
||||
|
||||
stats_text_parts.append(f"🟢 {_('admin_panel_online_label', default='Онлайн')}: <b>{active_users}</b>")
|
||||
stats_text_parts.append(f"🔴 {_('admin_panel_offline_label', default='Офлайн')}: <b>{disabled_users}</b>")
|
||||
active_users = status_counts.get('ACTIVE', 0)
|
||||
disabled_users = status_counts.get('DISABLED', 0)
|
||||
expired_users = status_counts.get('EXPIRED', 0)
|
||||
limited_users = status_counts.get('LIMITED', 0)
|
||||
total_users = users.get('totalUsers', 0)
|
||||
online_now = online_stats.get('onlineNow', 0)
|
||||
|
||||
stats_text_parts.append(f"🟢 {_('admin_panel_online_label', default='Онлайн')}: <b>{online_now}</b>")
|
||||
stats_text_parts.append(f"📊 {_('admin_panel_active_label', default='Активных')}: <b>{active_users}</b>")
|
||||
stats_text_parts.append(f"🔴 {_('admin_panel_disabled_label', default='Отключенных')}: <b>{disabled_users}</b>")
|
||||
stats_text_parts.append(f"⏰ {_('admin_panel_expired_label', default='Истекшие')}: <b>{expired_users}</b>")
|
||||
stats_text_parts.append(f"⚠️ {_('admin_panel_limited_label', default='Ограниченные')}: <b>{limited_users}</b>")
|
||||
stats_text_parts.append(f"👥 {_('admin_panel_total_users_label', default='Всего пользователей')}: <b>{total_users}</b>")
|
||||
|
||||
# System resources
|
||||
cpu = system_stats.get('cpu', {})
|
||||
memory = system_stats.get('memory', {})
|
||||
if cpu:
|
||||
cpu_usage = cpu.get('usage', 0)
|
||||
stats_text_parts.append(f"🔄 {_('admin_panel_cpu_usage_label', default='Загрузка CPU')}: <b>{cpu_usage:.1f}%</b>")
|
||||
if memory:
|
||||
memory_usage = memory.get('usage', 0)
|
||||
memory_total = memory.get('total', 1)
|
||||
memory_used = memory.get('used', 0)
|
||||
memory_usage = (memory_used / memory_total) * 100 if memory_total > 0 else 0
|
||||
stats_text_parts.append(f"💾 {_('admin_panel_memory_usage_label', default='Использование RAM')}: <b>{memory_usage:.1f}%</b>")
|
||||
else:
|
||||
stats_text_parts.append(f"⚠️ {_('admin_panel_system_stats_error', default='Ошибка получения системной статистики')}")
|
||||
|
||||
# Bandwidth stats
|
||||
if bandwidth_stats:
|
||||
today_traffic = bandwidth_stats.get('bandwidthToday', {})
|
||||
week_traffic = bandwidth_stats.get('bandwidthLastSevenDays', {})
|
||||
month_traffic = bandwidth_stats.get('bandwidthLastThirtyDays', {})
|
||||
|
||||
if today_traffic:
|
||||
today_total = today_traffic.get('total', '0 B')
|
||||
stats_text_parts.append(f"📊 {_('admin_panel_traffic_today_label', default='Трафик сегодня')}: <b>{today_total}</b>")
|
||||
month_traffic = bandwidth_stats.get('bandwidthLast30Days', {})
|
||||
# Fallback to the actual key name from API if the above doesn't exist
|
||||
if not month_traffic:
|
||||
month_traffic = bandwidth_stats.get('bandwidthLastThirtyDays', {})
|
||||
|
||||
if week_traffic:
|
||||
week_total = week_traffic.get('total', '0 B')
|
||||
week_total = week_traffic.get('current', '0 B')
|
||||
stats_text_parts.append(f"📊 {_('admin_panel_traffic_week_label', default='Трафик за неделю')}: <b>{week_total}</b>")
|
||||
|
||||
if month_traffic:
|
||||
month_total = month_traffic.get('total', '0 B')
|
||||
month_total = month_traffic.get('current', '0 B')
|
||||
stats_text_parts.append(f"📊 {_('admin_panel_traffic_month_label', default='Трафик за месяц')}: <b>{month_total}</b>")
|
||||
else:
|
||||
stats_text_parts.append(f"⚠️ {_('admin_panel_bandwidth_stats_error', default='Ошибка получения статистики трафика')}")
|
||||
|
||||
# Nodes stats
|
||||
if nodes_stats:
|
||||
# Nodes stats
|
||||
if nodes_stats and 'lastSevenDays' in nodes_stats:
|
||||
last_seven_days = nodes_stats.get('lastSevenDays', [])
|
||||
active_nodes_count = len([node for node in last_seven_days if node.get('status') == 'active'])
|
||||
total_nodes_count = len(last_seven_days)
|
||||
stats_text_parts.append(f"🔗 {_('admin_panel_nodes_label', default='Активных нод')}: <b>{active_nodes_count}/{total_nodes_count}</b>")
|
||||
# Get unique node names from the data
|
||||
unique_nodes = set()
|
||||
for node_data in last_seven_days:
|
||||
unique_nodes.add(node_data.get('nodeName', ''))
|
||||
total_nodes_count = len(unique_nodes)
|
||||
# Assume all nodes are active since we don't have status info
|
||||
stats_text_parts.append(f"🔗 {_('admin_panel_nodes_label', default='Активных нод')}: <b>{total_nodes_count}/{total_nodes_count}</b>")
|
||||
else:
|
||||
stats_text_parts.append(f"⚠️ {_('admin_panel_nodes_stats_error', default='Ошибка получения статистики нод')}")
|
||||
# Use nodes total from system stats as fallback
|
||||
nodes_info = system_stats.get('nodes', {}) if system_stats else {}
|
||||
total_online = nodes_info.get('totalOnline', 0)
|
||||
stats_text_parts.append(f"🔗 {_('admin_panel_nodes_label', default='Активных нод')}: <b>{total_online}</b>")
|
||||
|
||||
except Exception as e:
|
||||
logging.error(f"Failed to fetch panel statistics: {e}", exc_info=True)
|
||||
|
||||
+15
-56
@@ -38,7 +38,7 @@ async def inline_query_handler(inline_query: InlineQuery,
|
||||
# For all users: referral functionality
|
||||
if not query or "реф" in query or "ref" in query or "друг" in query or "friend" in query:
|
||||
referral_result = await create_referral_result(
|
||||
inline_query, bot, referral_service, i18n, current_lang
|
||||
inline_query, bot, referral_service, i18n, current_lang, settings
|
||||
)
|
||||
if referral_result:
|
||||
results.append(referral_result)
|
||||
@@ -46,14 +46,11 @@ async def inline_query_handler(inline_query: InlineQuery,
|
||||
# For admins: statistics
|
||||
if is_admin and (not query or "стат" in query or "stat" in query or "админ" in query or "admin" in query):
|
||||
stats_results = await create_admin_stats_results(
|
||||
session, i18n, current_lang
|
||||
session, i18n, current_lang, settings
|
||||
)
|
||||
results.extend(stats_results)
|
||||
|
||||
# Show help if no specific query
|
||||
if not query:
|
||||
help_result = await create_help_result(i18n, current_lang, is_admin)
|
||||
results.append(help_result)
|
||||
|
||||
|
||||
# Limit results to 50 (Telegram limit)
|
||||
results = results[:50]
|
||||
@@ -72,7 +69,7 @@ async def inline_query_handler(inline_query: InlineQuery,
|
||||
|
||||
async def create_referral_result(inline_query: InlineQuery, bot: Bot,
|
||||
referral_service: ReferralService,
|
||||
i18n_instance, lang: str) -> Optional[InlineQueryResultArticle]:
|
||||
i18n_instance, lang: str, settings: Settings) -> Optional[InlineQueryResultArticle]:
|
||||
"""Create referral link result for inline query"""
|
||||
_ = lambda key, **kwargs: i18n_instance.gettext(lang, key, **kwargs)
|
||||
|
||||
@@ -110,7 +107,7 @@ async def create_referral_result(inline_query: InlineQuery, bot: Bot,
|
||||
message_text=message_text,
|
||||
disable_web_page_preview=True
|
||||
),
|
||||
thumbnail_url="https://cdn-icons-png.flaticon.com/512/1077/1077114.png"
|
||||
thumbnail_url=settings.INLINE_REFERRAL_THUMBNAIL_URL
|
||||
)
|
||||
|
||||
except Exception as e:
|
||||
@@ -118,24 +115,24 @@ async def create_referral_result(inline_query: InlineQuery, bot: Bot,
|
||||
return None
|
||||
|
||||
|
||||
async def create_admin_stats_results(session: AsyncSession, i18n_instance, lang: str) -> List[InlineQueryResultArticle]:
|
||||
async def create_admin_stats_results(session: AsyncSession, i18n_instance, lang: str, settings: Settings) -> List[InlineQueryResultArticle]:
|
||||
"""Create admin statistics results for inline query"""
|
||||
_ = lambda key, **kwargs: i18n_instance.gettext(lang, key, **kwargs)
|
||||
results = []
|
||||
|
||||
try:
|
||||
# Quick user stats
|
||||
user_stats_result = await create_user_stats_result(session, i18n_instance, lang)
|
||||
user_stats_result = await create_user_stats_result(session, i18n_instance, lang, settings)
|
||||
if user_stats_result:
|
||||
results.append(user_stats_result)
|
||||
|
||||
# Quick financial stats
|
||||
financial_stats_result = await create_financial_stats_result(session, i18n_instance, lang)
|
||||
financial_stats_result = await create_financial_stats_result(session, i18n_instance, lang, settings)
|
||||
if financial_stats_result:
|
||||
results.append(financial_stats_result)
|
||||
|
||||
# Quick system stats
|
||||
system_stats_result = await create_system_stats_result(session, i18n_instance, lang)
|
||||
system_stats_result = await create_system_stats_result(session, i18n_instance, lang, settings)
|
||||
if system_stats_result:
|
||||
results.append(system_stats_result)
|
||||
|
||||
@@ -145,7 +142,7 @@ async def create_admin_stats_results(session: AsyncSession, i18n_instance, lang:
|
||||
return results
|
||||
|
||||
|
||||
async def create_user_stats_result(session: AsyncSession, i18n_instance, lang: str) -> Optional[InlineQueryResultArticle]:
|
||||
async def create_user_stats_result(session: AsyncSession, i18n_instance, lang: str, settings: Settings) -> Optional[InlineQueryResultArticle]:
|
||||
"""Create user statistics result"""
|
||||
_ = lambda key, **kwargs: i18n_instance.gettext(lang, key, **kwargs)
|
||||
|
||||
@@ -188,7 +185,7 @@ async def create_user_stats_result(session: AsyncSession, i18n_instance, lang: s
|
||||
message_text=stats_text,
|
||||
parse_mode="HTML"
|
||||
),
|
||||
thumbnail_url="https://cdn-icons-png.flaticon.com/512/681/681494.png"
|
||||
thumbnail_url=settings.INLINE_USER_STATS_THUMBNAIL_URL
|
||||
)
|
||||
|
||||
except Exception as e:
|
||||
@@ -196,7 +193,7 @@ async def create_user_stats_result(session: AsyncSession, i18n_instance, lang: s
|
||||
return None
|
||||
|
||||
|
||||
async def create_financial_stats_result(session: AsyncSession, i18n_instance, lang: str) -> Optional[InlineQueryResultArticle]:
|
||||
async def create_financial_stats_result(session: AsyncSession, i18n_instance, lang: str, settings: Settings) -> Optional[InlineQueryResultArticle]:
|
||||
"""Create financial statistics result"""
|
||||
_ = lambda key, **kwargs: i18n_instance.gettext(lang, key, **kwargs)
|
||||
|
||||
@@ -234,7 +231,7 @@ async def create_financial_stats_result(session: AsyncSession, i18n_instance, la
|
||||
message_text=stats_text,
|
||||
parse_mode="HTML"
|
||||
),
|
||||
thumbnail_url="https://cdn-icons-png.flaticon.com/512/2769/2769339.png"
|
||||
thumbnail_url=settings.INLINE_FINANCIAL_STATS_THUMBNAIL_URL
|
||||
)
|
||||
|
||||
except Exception as e:
|
||||
@@ -242,7 +239,7 @@ async def create_financial_stats_result(session: AsyncSession, i18n_instance, la
|
||||
return None
|
||||
|
||||
|
||||
async def create_system_stats_result(session: AsyncSession, i18n_instance, lang: str) -> Optional[InlineQueryResultArticle]:
|
||||
async def create_system_stats_result(session: AsyncSession, i18n_instance, lang: str, settings: Settings) -> Optional[InlineQueryResultArticle]:
|
||||
"""Create system statistics result with online/offline/expired/limited info"""
|
||||
_ = lambda key, **kwargs: i18n_instance.gettext(lang, key, **kwargs)
|
||||
|
||||
@@ -307,7 +304,7 @@ async def create_system_stats_result(session: AsyncSession, i18n_instance, lang:
|
||||
message_text=stats_text,
|
||||
parse_mode="HTML"
|
||||
),
|
||||
thumbnail_url="https://cdn-icons-png.flaticon.com/512/2920/2920277.png"
|
||||
thumbnail_url=settings.INLINE_SYSTEM_STATS_THUMBNAIL_URL
|
||||
)
|
||||
|
||||
except Exception as e:
|
||||
@@ -315,41 +312,3 @@ async def create_system_stats_result(session: AsyncSession, i18n_instance, lang:
|
||||
return None
|
||||
|
||||
|
||||
async def create_help_result(i18n_instance, lang: str, is_admin: bool) -> InlineQueryResultArticle:
|
||||
"""Create help result explaining inline mode features"""
|
||||
_ = lambda key, **kwargs: i18n_instance.gettext(lang, key, **kwargs)
|
||||
|
||||
if is_admin:
|
||||
help_text = _(
|
||||
"inline_admin_help_message",
|
||||
default="🤖 <b>Inline режим бота</b>\n\n"
|
||||
"📱 <b>Доступные команды:</b>\n\n"
|
||||
"🎁 <b>реф/ref</b> - поделиться реферальной ссылкой\n"
|
||||
"👥 <b>стат/stat</b> - статистика пользователей\n"
|
||||
"💰 <b>финансы</b> - финансовая статистика\n"
|
||||
"🖥 <b>система</b> - системная статистика\n\n"
|
||||
"💡 Просто напишите @{bot_username} и начните вводить команду в любом чате!"
|
||||
)
|
||||
title = _("inline_admin_help_title", default="🤖 Inline помощь (Админ)")
|
||||
description = _("inline_admin_help_description", default="Доступны команды: реф, стат, финансы, система")
|
||||
else:
|
||||
help_text = _(
|
||||
"inline_user_help_message",
|
||||
default="🤖 <b>Inline режим бота</b>\n\n"
|
||||
"📱 <b>Доступные команды:</b>\n\n"
|
||||
"🎁 <b>реф/ref</b> - поделиться реферальной ссылкой\n\n"
|
||||
"💡 Просто напишите @{bot_username} и начните вводить 'реф' в любом чате!"
|
||||
)
|
||||
title = _("inline_user_help_title", default="🤖 Inline помощь")
|
||||
description = _("inline_user_help_description", default="Доступна команда: реф (реферальная ссылка)")
|
||||
|
||||
return InlineQueryResultArticle(
|
||||
id="help",
|
||||
title=title,
|
||||
description=description,
|
||||
input_message_content=InputTextMessageContent(
|
||||
message_text=help_text,
|
||||
parse_mode="HTML"
|
||||
),
|
||||
thumbnail_url="https://cdn-icons-png.flaticon.com/512/906/906794.png"
|
||||
)
|
||||
Reference in New Issue
Block a user