# -*- coding: utf-8 -*- import time import uuid import asyncio import pyromod from pyromod.helpers import ikb from datetime import datetime as dt from pyrogram import * from pyrogram import Client as ren, filters from pyrogram.types import * from akn.utils.database import db as db_client from akn.manage.settings_control import verify_bot_ownershipdl from akn.utils.logger import LOGS from config import PRIVATE_LOGS @ren.on_callback_query(filters.regex("^my_bots$")) async def show_user_bots(client: Client, callback: CallbackQuery): user_id = callback.from_user.id user_mention = callback.from_user.mention try: user_data = await db_client.alldl_bot.find_one({"user_id": user_id}) if not user_data or not user_data.get("bots"): return await callback.answer( "āŒ You don't have any bots deployed yet!", show_alert=True ) bots_by_status = { "approved": [], "pending": [], "rejected": [], "error": [] } for bot in user_data["bots"]: status = bot.get("status", "pending") bots_by_status.setdefault(status, []).append(bot) start = time.time() await client.get_me() end = time.time() latency = (end - start) * 1000 message_text = f"šŸ¤– Your Bot Dashboard šŸ‘‹ {user_mention}\n\n" message_text += f"šŸ· Tier: {'šŸ’Ž Premium' if user_data.get('is_premium') else 'šŸ†“ Free'}\n" message_text += f"šŸš€ Active Bots: {sum(1 for b in bots_by_status['approved'] if b.get('is_active'))}\n" message_text += f"ā³ Pending: {len(bots_by_status['pending'])}\n" message_text += f"āŒ Rejected: {len(bots_by_status['rejected'])}\n" message_text += f"šŸ“ Pong!: {latency:.2f}.\n\n" buttons = [] if bots_by_status["approved"]: message_text += "āœ… Approved Bots:\n" for bot in bots_by_status["approved"]: bot_name = bot.get("bot_username", "Unknown") status = "🟢 Online" if bot.get("is_active") else "šŸ”“ Offline" message_text += f"┣ {bot_name} - {status} - `{latency:.2f}`\n" buttons.append([ InlineKeyboardButton( f"āš™ļø Manage {bot_name}", callback_data=f"botmgmt_{bot.get('uuid', 'unknown')}" ) ]) if bots_by_status["pending"]: message_text += "\nšŸ•’ Pending Approval:\n" for bot in bots_by_status["pending"]: token_preview = bot.get("bot_token", "")[:10] + f":{bot.get('uuid', '')}" submitted_time = bot.get("timestamp", "Unknown") message_text += f"┣ {token_preview} - {submitted_time}\n" buttons.append([ InlineKeyboardButton( f"āŒ Cancel {token_preview}", callback_data=f"cancelbotdl_{bot.get('uuid', 'unknown')}" ) ]) if bots_by_status["rejected"]: message_text += "\nāŒ Rejected Bots:\n" for bot in bots_by_status["rejected"]: token_preview = bot.get("bot_token", "")[:10] + f":{bot.get('uuid', '')}" reason = bot.get("admin_action", {}).get("reason", "No reason given") message_text += f"┣ {token_preview} - {reason}\n" buttons.append([ InlineKeyboardButton( f"šŸ” Resubmit {token_preview}", callback_data=f"resubmitdl_{bot.get('uuid', 'unknown')}" ) ]) buttons.append([ InlineKeyboardButton("šŸ†• Deploy New Bot", callback_data="tutorial_alldlbot"), InlineKeyboardButton("šŸ’Ž Upgrade Plan", callback_data="premium_upgrades") ]) buttons.append([ InlineKeyboardButton("šŸ”„ Refresh", callback_data="my_bots"), InlineKeyboardButton("āŒ Close", callback_data="close") ]) buttons.append([ InlineKeyboardButton("Ā« Back", callback_data="customzie_bot"), ]) try: await callback.message.edit_text( message_text, reply_markup=InlineKeyboardMarkup(buttons) ) except Exception as e: LOGS.error(f"Edit message failed: {e}") await callback.answer("āš ļø Failed to update message, try again.", show_alert=True) await callback.answer() except Exception as e: LOGS.error(f"Error in my_bots handler: {str(e)}") await callback.answer("āš ļø Error fetching your bots!", show_alert=True) await client.send_message( PRIVATE_LOGS, f"🚨 Error in my_bots handler\n\n" f"šŸ‘¤ User: {user_mention} ({user_id})\n" f"🧠 Error: {type(e).__name__}: {str(e)}" ) @ren.on_callback_query(filters.regex(r"^botmgmt_(\w+)$")) async def manage_single_bot(client: Client, callback: CallbackQuery): bot_uuid = callback.matches[0].group(1) user_id = callback.from_user.id user_mention = callback.from_user.mention try: user_data = await db_client.alldl_bot.find_one( { "user_id": user_id, "bots.uuid": bot_uuid }, {"bots.$": 1} ) if not user_data or not user_data.get("bots"): return await callback.answer("āŒ Bot not found!", show_alert=True) bot = user_data["bots"][0] bot_username = bot.get("bot_username", "Unknown") bot_uuid = bot.get("uuid", "???") status = "🟢 Online" if bot.get("is_active") else "šŸ”“ Offline" last_active = bot.get("last_active", "Never") buttons = [ [ InlineKeyboardButton("šŸ”„ Restart Bot", callback_data=f"restartdl_{bot_uuid}"), InlineKeyboardButton("šŸ›‘ Stop Bot", callback_data=f"stopbotdl_{bot_uuid}") ], [ InlineKeyboardButton("šŸ“Š Stats", callback_data=f"botstatsdl_{bot_uuid}"), InlineKeyboardButton("āš™ļø Settings", callback_data=f"botsettingsdl_{bot_uuid}") ], [InlineKeyboardButton("Ā« Back", callback_data="my_bots")] ] await callback.message.edit_text( f"āš™ļø Managing {bot_username}\n\n" f"Status: {status}\n" f"Last Active: {last_active}\n" f"UUID: {bot_uuid}\n\n" "Choose an action below:", reply_markup=InlineKeyboardMarkup(buttons) ) await callback.answer() except Exception as e: LOGS.error(f"Bot management error: {str(e)}") await callback.answer("āŒ Error managing bot!", show_alert=True) await client.send_message( PRIVATE_LOGS, f"🚨 Error in single manage handler\n\n" f"šŸ‘¤ User: {user_mention} ({user_id})\n" f"🧠 Error: {type(e).__name__}: {str(e)}" ) @ren.on_callback_query(filters.regex(r"^botsettingsdl_(\w+)$")) async def xbot_settingsdl(client: Client, callback: CallbackQuery): try: bots_uuid = callback.matches[0].group(1) user_id = callback.from_user.id user_mention = callback.from_user.mention if not await verify_bot_ownershipdl(user_id, bots_uuid): await callback.answer("āŒ Unauthorized access!", show_alert=True) return bot_data = await db_client.alldl_bot.find_one( {"user_id": user_id, "bots.uuid": bots_uuid}, {"bots.$": 1} ) if not bot_data: return await callback.answer("āŒ Bot not found!", show_alert=True) buttons = InlineKeyboardMarkup([ [InlineKeyboardButton("šŸ” Reset Token", callback_data=f"start_reset_tokendl")], [InlineKeyboardButton("šŸ—‘ Delete Bot", callback_data=f"deletebotdl_{bots_uuid}")], [InlineKeyboardButton("Ā« Back to bot", callback_data="my_bots")] ]) await callback.message.edit_text( f"āš™ļø Bot Settings\n\n" f"šŸ†” UUID: `{bots_uuid}`\n" f"šŸ”— Username: {bot_data['bots'][0].get('bot_username', 'N/A')}\n" f"šŸ“… Created: {bot_data['bots'][0].get('created_at', 'Unknown')}", reply_markup=buttons ) await callback.answer() except Exception as e: LOGS.error(f"Settings error: {str(e)}") await callback.answer("āš ļø Error loading settings!", show_alert=True) await client.send_message( PRIVATE_LOGS, f"🚨 Error in settingdl handler\n\n" f"šŸ‘¤ User: {user_mention} ({user_id})\n" f"🧠 Error: {type(e).__name__}: {str(e)}" ) @ren.on_callback_query(filters.regex("start_reset_tokendl")) async def reset_tokendl_callbackx(client, callback_query): user_id = callback_query.from_user.id bot_data = await db_client.alldl_bot.find_one({"user_id": user_id}) if not bot_data: await callback.answer("āŒ Bot not found!", show_alert=True) return old_uuid = bot_data["bots"][0].get("uuid") await callback_query.message.edit_text( "āœļø Please send the UUID of the bot you want to reset.\n\nYou can cancel by typing `/cancel`\n\nYou can't this button is disabled.", reply_markup=ikb([ [("šŸ”’ Locked Cancel", "noop")] ]) ) try: uuid_msg = await client.listen(callback_query.message.chat.id, timeout=60) if uuid_msg.text.lower() == "/cancel": await uuid_msg.reply( "āŒ Cancelled.", reply_markup=ikb([ [("Ā« Back", "customzie_bot")] ]) ) return bots_uuid = uuid_msg.text.strip() if bots_uuid != old_uuid: await uuid_msg.reply( "āŒ Token reset cancelled.", reply_markup=ikb([ [("Ā« Back", "customzie_bot")] ]) ) return keyboard = InlineKeyboardMarkup([ [ InlineKeyboardButton("āœ… Yes", callback_data=f"resettokendl_{bots_uuid}"), InlineKeyboardButton("āŒ Cancel", callback_data=f"cancel_resetdl_{bots_uuid}") ] ]) await uuid_msg.reply( f"Are you sure you want to reset the token for:\n`{bots_uuid}`", reply_markup=keyboard ) except asyncio.TimeoutError: await callback_query.message.reply("ā° Timeout. Please try again.") @ren.on_callback_query(filters.regex(r"^(resettokendl|cancel_resetdl)_(\w+)$")) async def tokenx_reset_flowdl(client: Client, callback: CallbackQuery): action, bot_uuid = callback.matches[0].groups() user_id = callback.from_user.id user_mention = callback.from_user.mention bot_data = await db_client.alldl_bot.find_one( { "user_id": user_id, "bots.uuid": bot_uuid }, {"bots.$": 1} ) if not bot_data: await callback.answer("āŒ Bot not found!", show_alert=True) return if action == "cancel_resetdl": await callback.answer("Token reset cancelled āŒ", show_alert=False) await callback.message.edit_text( "āŒ Token reset cancelled.", reply_markup=ikb([ [("Ā« Back", "customzie_bot")] ]) ) return try: current_token = bot_data["bots"][0]["uuid"] new_token = str(uuid.uuid4())[:8] await db_client.alldl_bot.update_one( { "user_id": user_id, "bots.uuid": bot_uuid }, { "$set": { "bots.$.uuid": new_token, "bots.$.updated_at": dt.now().strftime("%Y-%m-%d %H:%M:%S"), }, "$push": { "bots.$.old_tokens": { "token": current_token, "reset_at": dt.now().strftime("%Y-%m-%d %H:%M:%S") } } } ) await callback.message.edit_text( f"āœ… Token has been reset successfully!\n\n`{new_token}`", reply_markup=None ) await callback.answer("New token generated āœ…", show_alert=False) except Exception as e: LOGS.error(f"Token reset error: {str(e)}") await callback.answer("āŒ Failed to reset token. Please try again later.", True) await client.send_message( PRIVATE_LOGS, f"🚨 Error in tokenx reset handler\n\n" f"šŸ‘¤ User: {user_mention} ({user_id})\n" f"🧠 Error: {type(e).__name__}: {str(e)}" ) @ren.on_callback_query(filters.regex("^noop$")) async def noopx_callback(client, callback_query): await callback_query.answer("šŸ”’ This button is disabled.", show_alert=False) @ren.on_callback_query(filters.regex(r"^resubmitdl_(\w+)$")) async def resubmissiondl(client: Client, callback: CallbackQuery): try: bots_uuid = callback.matches[0].group(1) user_id = callback.from_user.id user_mention = callback.from_user.mention bot_data = await db_client.alldl_bot.find_one( { "user_id": user_id, "bots.uuid": bots_uuid, "bots.status": "rejected" }, {"bots.$": 1} ) if not bot_data: await callback.answer("āŒ Bot not found or not eligible for resubmission", show_alert=True) return bot = bot_data["bots"][0] rejection_reason = bot.get("admin_action", {}).get("reason", "No reason provided") await callback.message.edit_text( f"šŸ”„ **Resubmit Bot Request**\n\n" f"šŸ†” UUID: `{bots_uuid}`\n" f"āŒ Previous Rejection Reason: {rejection_reason}\n\n" "Please confirm you want to resubmit this bot for approval:", reply_markup=InlineKeyboardMarkup([ [InlineKeyboardButton("āœ… Confirm Resubmit", callback_data=f"confirm_resubmitdl_{bots_uuid}")], [InlineKeyboardButton("āŒ Cancel", callback_data=f"cancel_resubmitdl_")] ]) ) await callback.answer() except Exception as e: LOGS.error(f"Resubmission init error: {str(e)}") await callback.answer("āš ļø Error processing request", show_alert=True) await client.send_message( PRIVATE_LOGS, f"🚨 Error in resubm handler\n\n" f"šŸ‘¤ User: {user_mention} ({user_id})\n" f"🧠 Error: {type(e).__name__}: {str(e)}" ) @ren.on_callback_query(filters.regex(r"^confirm_resubmitdl_(\w+)$")) async def confresubmissiondl(client: Client, callback: CallbackQuery): try: bots_uuid = callback.matches[0].group(1) user_id = callback.from_user.id user_mention = callback.from_user.mention result = await db_client.alldl_bot.update_one( { "user_id": user_id, "bots.uuid": bots_uuid }, { "$set": { "bots.$.status": "pending", "bots.$.resubmitted_at": dt.now(), "bots.$.admin_action.reviewed": False } } ) if result.modified_count == 1: await callback.message.edit_text( f"āœ… **Resubmission Successful**\n\n" f"Bot `{bots_uuid}` has been queued for admin review.\n" f"Average review time: 24-48 hours", reply_markup=InlineKeyboardMarkup([ [InlineKeyboardButton("šŸ“Š View Status", callback_data=f"statusdl_{user_id}")] ]) ) await notify_adminsdl( f"Bot resubmitteddl: {bots_uuid} by {callback.from_user.mention}", user_id=user_id, bots_uuid=bots_uuid ) else: raise Exception("Database update failed") except Exception as e: LOGS.error(f"Resubmission error: {str(e)}") await callback.message.edit_text("āŒ Failed to resubmit. Please try again later.") await client.send_message( PRIVATE_LOGS, f"🚨 Error in config resub handler\n\n" f"šŸ‘¤ User: {user_mention} ({user_id})\n" f"🧠 Error: {type(e).__name__}: {str(e)}" ) async def notify_adminsdl(text_str, user_id, bots_uuid): admin_buttons = InlineKeyboardMarkup([ [InlineKeyboardButton("āœ… Approve", callback_data=f"approved_alldl_{user_id}_{bots_uuid}"), InlineKeyboardButton("āŒ Reject", callback_data=f"rejected_alldl_{user_id}_{bots_uuid}")], [InlineKeyboardButton("šŸ‘¤ View User", url=f"tg://user?id={user_id}")] ]) await client.send_message( PRIVATE_LOGS, text_str, reply_markup=admin_buttons ) @ren.on_callback_query(filters.regex(r"^cancel_resubmitdl_")) async def cancel_resubmitdl(client: Client, callback: CallbackQuery): await callback.message.edit_text( "🚫 Resubmission cancelled", reply_markup=ikb([ [("Ā« Back", "customzie_bot")] ]) ) await callback.answer() @ren.on_callback_query(filters.regex(r"^cancelbotdl_(\w+)$")) async def cancelbotdl(client: Client, callback: CallbackQuery): try: bots_uuid = callback.matches[0].group(1) user_id = callback.from_user.id user_mention = callback.from_user.mention bot_data = await db_client.alldl_bot.find_one( { "user_id": user_id, "bots.uuid": bots_uuid, "bots.status": "pending" }, {"bots.$": 1} ) if not bot_data: await callback.answer("āŒ No pending bot found with this ID", show_alert=True) return await callback.message.edit_text( f"āš ļø **Confirm Cancellation**\n\n" f"UUID: `{bots_uuid}`\n" f"Submitted: {bot_data['bots'][0].get('timestamp', 'Unknown')}\n\n" "This will permanently remove the bot request:", reply_markup=InlineKeyboardMarkup([ [InlineKeyboardButton("šŸ—‘ Confirm Delete", callback_data=f"confirmcanceldl_{bots_uuid}")], [InlineKeyboardButton("šŸ”™ Keep Request", callback_data=f"keepbotdl_{user_id}")] ]) ) await callback.answer() except Exception as e: LOGS.error(f"Cancel init error: {str(e)}") await callback.answer("āš ļø Error processing request", show_alert=True) await client.send_message( PRIVATE_LOGS, f"🚨 Error in cancelbotdl handler\n\n" f"šŸ‘¤ User: {user_mention} ({user_id})\n" f"🧠 Error: {type(e).__name__}: {str(e)}" ) @ren.on_callback_query(filters.regex(r"^confirmcanceldl_(\w+)$")) async def confirm_cancel_botdl(client: Client, callback: CallbackQuery): try: bots_uuid = callback.matches[0].group(1) user_id = callback.from_user.id user_mention = callback.from_user.mention result = await db_client.alldl_bot.update_one( {"user_id": user_id}, {"$pull": {"bots": {"uuid": bots_uuid}}} ) if result.modified_count == 1: await callback.message.edit_text( "āœ… **Request Cancelled**\n\n" f"Bot `{bots_uuid}` has been permanently removed", reply_markup=InlineKeyboardMarkup([ [InlineKeyboardButton("šŸ“‹ My Bots", callback_data="my_bots")], [InlineKeyboardButton("Ā« Back", callback_data="customzie_bot")] ]) ) else: raise Exception("Database update failed") except Exception as e: LOGS.error(f"Cancel error: {str(e)}") await callback.message.edit_text("āŒ Failed to cancel request. Please contact support.") await client.send_message( PRIVATE_LOGS, f"🚨 Error in confirm cancelbotdl handler\n\n" f"šŸ‘¤ User: {user_mention} ({user_id})\n" f"🧠 Error: {type(e).__name__}: {str(e)}" ) @ren.on_callback_query(filters.regex(r"^keepbotdl_(\d+)$")) async def keep_bot_requestdl(client: Client, callback: CallbackQuery): await callback.message.edit_text( "šŸ”„ Bot request kept in queue\n\n" "Your submission remains pending admin review", reply_markup=InlineKeyboardMarkup([ [InlineKeyboardButton("šŸ•’ Check Status", callback_data=f"statusdl_{callback.matches[0].group(1)}")], [InlineKeyboardButton("Ā« Back", callback_data="customzie_bot")] ]) ) await callback.answer()