import time
from datetime import datetime as dt, timedelta
from pyrogram import Client as ren, filters
from pyrogram import *
from pyrogram.types import *
from akn.utils.database import db
from akn.utils.logger import LOGS
from config import *
@ren.on_callback_query(filters.regex(r"^botstatsdl_(\w+)$"))
async def handle_bot_statsdl(client: Client, callback: CallbackQuery):
try:
bots_uuid = callback.matches[0].group(1)
user_id = callback.from_user.id
bot_data = await db.alldl_bot.find_one(
{
"user_id": user_id,
"bots.uuid": bots_uuid
},
{"bots.$": 1}
)
if not bot_data or not bot_data.get("bots"):
return await callback.answer("❌ Bot not found!", show_alert=True)
bot = bot_data["bots"][0]
stats = bot.get("stats", {})
start = time.time()
await client.get_me()
end = time.time()
latency = (end - start) * 1000
start_time = bot.get("start_time")
if start_time:
uptime = str(timedelta(seconds=int(time.time() - start_time)))
else:
uptime = "N/A"
bandwidth_used = stats.get("bandwidth_used", 0)
if bandwidth_used > 1024:
bandwidth = f"{bandwidth_used / 1024:.2f} GB"
else:
bandwidth = f"Unlimited"
last_active = bot.get("last_active")
if isinstance(last_active, dt):
last_active_str = last_active.strftime('%Y-%m-%d %H:%M:%S')
elif isinstance(last_active, str):
last_active_str = last_active
else:
last_active_str = "Never"
stats_message = (
f"📊 Bot Statistics 📊\n\n"
f"🆔 {bots_uuid}
\n"
f"🔗 {bot.get('bot_username', 'N/A')}\n\n"
f"📥 Downloads:\n"
f"├ Total: `{stats.get('total_downloads', 999999999)}`\n"
f"├ Successful: `{stats.get('successful_downloads', 999999999)}`\n"
f"└ Failed: `{stats.get('failed_downloads', 0)}`\n\n"
f"🌐 Bandwidth: {bandwidth}\n"
f"⏱ Uptime: {uptime}\n"
f"✨ Pong!: {latency:.2f}\n"
f"🔄 Restarts: {bot.get('restart_count', 0)}\n"
f"📅 Last Active: {last_active_str}"
)
buttons = InlineKeyboardMarkup([
[InlineKeyboardButton("🔄 Refresh Stats", callback_data=f"botstatsdl_{bots_uuid}")],
[InlineKeyboardButton("📈 Daily Report", callback_data=f"reportdl_{bots_uuid}")],
[InlineKeyboardButton("🔙 Back to Bot", callback_data=f"my_bots")]
])
await callback.message.edit_text(stats_message, reply_markup=buttons)
await callback.answer()
except Exception as e:
LOGS.error(f"Stats error: {str(e)}")
await callback.answer("⚠️ Failed to load stats!", show_alert=True)
async def update_bot_stats(bot_uuid: str, download_success: bool, file_size: int):
update_data = {
"$inc": {
"bots.$.stats.total_downloads": 1,
"bots.$.stats.bandwidth_used": file_size,
"bots.$.stats.uptime": int(time.time() - time.time())
},
"$set": {
"bots.$.stats.last_activity": dt.now()
}
}
if download_success:
update_data["$inc"]["bots.$.stats.successful_downloads"] = 1
else:
update_data["$inc"]["bots.$.stats.failed_downloads"] = 1
await db.alldl_bot.update_one(
{"bots.uuid": bot_uuid},
update_data
)