import os from telegram import Update, InlineKeyboardButton, InlineKeyboardMarkup from telegram.ext import ApplicationBuilder, CommandHandler, ContextTypes, MessageHandler, CallbackQueryHandler, filters from dotenv import load_dotenv from engine.security import decrypt_token load_dotenv() class WolfC2Bot: def __init__(self, kill_callback=None, deploy_callback=None, monitor=None): raw_token = os.getenv("TELEGRAM_BOT_TOKEN") self.token = decrypt_token(raw_token) if raw_token else None self.chat_id = os.getenv("TELEGRAM_CHAT_ID") self.kill_callback = kill_callback self.deploy_callback = deploy_callback self.monitor = monitor self.app = None async def auth_check(self, update: Update): if str(update.effective_chat.id) != self.chat_id: await update.message.reply_text("⛔ ACCESS DENIED | WOLF-ID REQUIRED") return False return True async def start_cmd(self, update: Update, context: ContextTypes.DEFAULT_TYPE): if not await self.auth_check(update): return welcome = ( "🐺 *WHITE WOLF SOVEREIGN CORE*\n" "C2 Interface Operational\n\n" "Select an operation below or use text commands:" ) keyboard = [ [InlineKeyboardButton("📊 System Status", callback_data='status'), InlineKeyboardButton("📋 View Logs", callback_data='logs')], [InlineKeyboardButton("☁️ Sync Backup", callback_data='backup'), InlineKeyboardButton("🔄 Reboot Core", callback_data='reboot')], [InlineKeyboardButton("🛑 PURGE ALL", callback_data='killall')] ] reply_markup = InlineKeyboardMarkup(keyboard) await update.message.reply_text(welcome, reply_markup=reply_markup, parse_mode='Markdown') async def button_handler(self, update: Update, context: ContextTypes.DEFAULT_TYPE): query = update.callback_query await query.answer() if not await self.auth_check(update): return action = query.data if action == 'status': await self.status_cmd(update, context) elif action == 'logs': await self.logs_cmd(update, context) elif action == 'backup': await self.backup_cmd(update, context) elif action == 'reboot': await query.edit_message_text("🔄 Watchdog pinged. System is monitoring processes. (Use /reboot to force)") elif action == 'killall': await self.kill_all_cmd(update, context) await query.edit_message_text("🛑 *GLOBAL PURGE EXECUTED*. All nodes offline.", parse_mode='Markdown') async def status_cmd(self, update: Update, context: ContextTypes.DEFAULT_TYPE): if not await self.auth_check(update): return if self.monitor: m = self.monitor.get_metrics() text = ( "📊 *SYSTEM STATUS*\n" f"CPU: {m['cpu']}%\n" f"RAM: {m['ram']}%\n" f"DISK: {m['disk']}%\n" f"ACTIVE PROCS: {m['processes']}\n" f"UPTIME: {m['uptime']}s" ) await update.message.reply_text(text, parse_mode='Markdown') async def deploy_cmd(self, update: Update, context: ContextTypes.DEFAULT_TYPE): if not await self.auth_check(update): return if len(context.args) < 2: await update.message.reply_text("❌ Usage: /deploy ") return url, name = context.args[0], context.args[1] msg = await update.message.reply_text(f"🚀 *INITIATING DEPLOYMENT*\nProject: `{name}`\nSource: {url}", parse_mode='Markdown') if self.deploy_callback: try: # Run in a thread to avoid blocking the event loop import threading def run_deploy(): try: path = self.deploy_callback(url, name) context.application.loop.call_soon_threadsafe( lambda: asyncio.create_task(update.message.reply_text(f"✅ *DEPLOYMENT SUCCESSFUL*\nProject: `{name}`\nPath: `{path}`", parse_mode='Markdown')) ) except Exception as e: context.application.loop.call_soon_threadsafe( lambda: asyncio.create_task(update.message.reply_text(f"❌ *DEPLOYMENT FAILED*\nError: {str(e)}")) ) threading.Thread(target=run_deploy, daemon=True).start() except Exception as e: await update.message.reply_text(f"❌ *ENGINE ERROR*\n{str(e)}") async def handle_document(self, update: Update, context: ContextTypes.DEFAULT_TYPE): if not await self.auth_check(update): return doc = update.message.document file = await doc.get_file() # Create deployments dir if not exists os.makedirs("deployments", exist_ok=True) save_path = os.path.join("deployments", doc.file_name) await file.download_to_drive(save_path) await update.message.reply_text(f"📥 *FILE RECEIVED*\nName: `{doc.file_name}`\nSize: {doc.file_size} bytes\n\nUse `/run {doc.file_name}` to execute.", parse_mode='Markdown') async def run_cmd(self, update: Update, context: ContextTypes.DEFAULT_TYPE): if not await self.auth_check(update): return if not context.args: await update.message.reply_text("❌ Usage: /run ") return filename = context.args[0] await update.message.reply_text(f"⚙️ EXECUTING: `{filename}`...") # Here we integrate with the deployer (this will be handled by main.py callback usually) # For simplicity in this structure, we'll assume the callback handles arbitrary runs if self.deploy_callback: try: # We reuse the deploy_callback or add a new one. # Let's assume the user wants to run it as a standalone project proj_name = filename.split('.')[0] self.deploy_callback(None, proj_name, custom_script=filename) await update.message.reply_text(f"🚀 `{filename}` IS NOW RUNNING.\nCheck Dashboard for logs.") except Exception as e: await update.message.reply_text(f"❌ EXECUTION FAILED: {str(e)}") async def kill_all_cmd(self, update: Update, context: ContextTypes.DEFAULT_TYPE): if not await self.auth_check(update): return if self.kill_callback: self.kill_callback() await update.message.reply_text("💀 SYSTEM PURGED | ALL PROCESSES KILLED") async def logs_cmd(self, update: Update, context: ContextTypes.DEFAULT_TYPE): if not await self.auth_check(update): return log_path = "wolf_host.log" if os.path.exists(log_path): with open(log_path, "r") as f: lines = f.readlines()[-15:] # Last 15 lines log_snippet = "".join(lines) await update.message.reply_text(f"📋 *REAL-TIME SYSTEM LOGS*\n```\n{log_snippet}\n```", parse_mode='Markdown') else: await update.message.reply_text("❌ No logs found.") async def usage_cmd(self, update: Update, context: ContextTypes.DEFAULT_TYPE): if not await self.auth_check(update): return if self.monitor: m = self.monitor.get_metrics() report = ( f"📊 *SYSTEM STATUS*\n" f"CPU: `{m['cpu']}%`\n" f"RAM: `{m['ram']}%` (`{m.get('ram_mb', 0)} MB`)\n" f"DISK: `{m['disk']}%` (Hugging Face /)" ) await update.message.reply_text(report, parse_mode='Markdown') async def reboot_cmd(self, update: Update, context: ContextTypes.DEFAULT_TYPE): if not await self.auth_check(update): return await update.message.reply_text("🔄 *REBOOT SEQUENCE INITIATED*\nSystem will be offline for 30s.") os._exit(0) # Let the container manager (Hugging Face) restart it async def backup_cmd(self, update: Update, context: ContextTypes.DEFAULT_TYPE): if not await self.auth_check(update): return msg = await update.callback_query.message.reply_text("☁️ *SYNCING TO CLOUD...* Packing deployments...", parse_mode='Markdown') if update.callback_query else await update.message.reply_text("☁️ *SYNCING TO CLOUD...*", parse_mode='Markdown') try: import shutil shutil.make_archive("backup", 'zip', "deployments") await context.bot.send_document(chat_id=self.chat_id, document=open("backup.zip", "rb"), caption="📦 *PROJECT BACKUP*\nHere are your persistent files.", parse_mode='Markdown') os.remove("backup.zip") await msg.edit_text("✅ *SYNC COMPLETE*. Files secured in Telegram Cloud.", parse_mode='Markdown') except Exception as e: await msg.edit_text(f"❌ *SYNC FAILED*: {e}", parse_mode='Markdown') def run(self): if not self.token: print("[BOT] CRITICAL: MISSING TOKEN. BOT OFFLINE.") return self.app = ApplicationBuilder().token(self.token).build() self.app.add_handler(CommandHandler("start", self.start_cmd)) self.app.add_handler(CommandHandler("status", self.status_cmd)) self.app.add_handler(CommandHandler("deploy", self.deploy_cmd)) self.app.add_handler(CommandHandler("run", self.run_cmd)) self.app.add_handler(CommandHandler("logs", self.logs_cmd)) self.app.add_handler(CommandHandler("usage", self.usage_cmd)) self.app.add_handler(CommandHandler("reboot", self.reboot_cmd)) self.app.add_handler(CommandHandler("killall", self.kill_all_cmd)) self.app.add_handler(CallbackQueryHandler(self.button_handler)) # Handle code files and zip uploads self.app.add_handler(MessageHandler(filters.Document.ALL | filters.TEXT & ~filters.COMMAND, self.handle_document))