import os import asyncio import httpx from modules.agents import MODULES, run_module from jarvis_links import get_all_links, get_random_template BOT_TOKEN = os.environ.get("TELEGRAM_BOT_TOKEN", "") MASTER_CHAT_ID = os.environ.get("TELEGRAM_CHAT_ID", "") API_URL = f"https://api.telegram.org/bot{BOT_TOKEN}" class JarvisTelegramBot: def __init__(self): self.offset = 0 self.running = False async def send_message(self, chat_id: str, text: str) -> bool: if not BOT_TOKEN: return False try: async with httpx.AsyncClient(timeout=30) as client: response = await client.post(f"{API_URL}/sendMessage", json={ "chat_id": chat_id, "text": text[:4096], "parse_mode": "Markdown" }) return response.status_code == 200 except Exception: return False async def notify_master(self, text: str): if MASTER_CHAT_ID: await self.send_message(MASTER_CHAT_ID, text) async def get_updates(self) -> list: try: async with httpx.AsyncClient(timeout=30) as client: response = await client.get(f"{API_URL}/getUpdates", params={"offset": self.offset, "timeout": 10}) if response.status_code == 200: return response.json().get("result", []) except Exception: pass return [] async def process_command(self, chat_id: str, text: str) -> str: parts = text.strip().split(None, 2) command = parts[0].lower() args = parts[1] if len(parts) > 1 else "" extra = parts[2] if len(parts) > 2 else "" if command in ["/start", "/help"]: return """🤖 *JARVIS EMPIRE — Online* *COMMANDS:* /status — Cek status sistem /trend [topik] — Hijack trending topic /write [topik] [hostinger/shopee] — Tulis konten /analyze [konten] — Prediksi viral score /scout [target] — Riset kompetitor /ghost [konten] — Distribusi multi-platform /publish [konten] — Jadwal publishing /analyst — Analisa performa /links — Affiliate links /runall — Jalankan semua modul""" elif command == "/status": from ai_engine import engine available = engine.get_available_providers() return f"""⚡ *JARVIS STATUS* *AI Providers:* {len(available)} aktif {chr(10).join(['✅ ' + p for p in available]) if available else '❌ Tidak ada API key'} *Modul:* 7 aktif *Status:* 🟢 Online""" elif command == "/links": links = get_all_links() msg = "🔗 *AFFILIATE LINKS*\n\n" for platform, data in links.items(): msg += f"*{platform.upper()}*\n{data['full']}\nKomisi: {data['commission']}\n\n" return msg elif command == "/trend": topic = args or None await self.send_message(chat_id, "🔥 Mencari trending topic...") result = await run_module("trend", custom_topic=topic) return f"🔥 *TREND HIJACKER*\n\n{result['output']}\n\n_via {result['provider']}_" elif command == "/write": if not args: return "❌ Format: `/write [topik] [hostinger/shopee]`" platform = "shopee" if "shopee" in text.lower() else "hostinger" topic = args.replace("shopee","").replace("hostinger","").strip() await self.send_message(chat_id, f"✍️ Menulis konten '{topic}'...") result = await run_module("writer", topic=topic, platform=platform) return f"✍️ *KONTEN AFFILIATE*\n\n{result['output']}\n\n_via {result['provider']}_" elif command == "/analyze": content = f"{args} {extra}".strip() if not content: return "❌ Format: `/analyze [konten]`" await self.send_message(chat_id, "📊 Menganalisa...") result = await run_module("viral", content=content) return f"📊 *VIRAL PREDICTOR*\n\n{result['output']}\n\n_via {result['provider']}_" elif command == "/scout": target = args or "hostinger competitor indonesia" await self.send_message(chat_id, f"🔍 Riset '{target}'...") result = await run_module("scout", target=target) return f"🔍 *SCOUT REPORT*\n\n{result['output']}\n\n_via {result['provider']}_" elif command == "/ghost": content = f"{args} {extra}".strip() if not content: return "❌ Format: `/ghost [konten]`" await self.send_message(chat_id, "👻 Menyiapkan distribusi...") result = await run_module("ghost", content=content) return f"👻 *GHOST NETWORK*\n\n{result['output']}\n\n_via {result['provider']}_" elif command == "/publish": content = f"{args} {extra}".strip() if not content: return "❌ Format: `/publish [konten]`" await self.send_message(chat_id, "📢 Membuat jadwal...") result = await run_module("publisher", content=content) return f"📢 *PUBLISHER*\n\n{result['output']}\n\n_via {result['provider']}_" elif command == "/analyst": await self.send_message(chat_id, "📈 Menganalisa performa...") result = await run_module("analyst") return f"📈 *ANALYST*\n\n{result['output']}\n\n_via {result['provider']}_" elif command == "/runall": await self.send_message(chat_id, "🚀 Menjalankan semua modul...") results = [] for name, module in MODULES.items(): try: await module.run() results.append(f"✅ {module.name}") except: results.append(f"❌ {name}") return "🚀 *RUN ALL*\n\n" + "\n".join(results) else: from ai_engine import engine result = await engine.think(text) return f"🤖 *JARVIS:*\n\n{result['response']}\n\n_via {result['provider']}_" async def start_polling(self): self.running = True print("🤖 Telegram Bot polling started...") if MASTER_CHAT_ID: await self.notify_master("🟢 *JARVIS EMPIRE ONLINE*\n\nSistem aktif, Master!") while self.running: try: updates = await self.get_updates() for update in updates: self.offset = update["update_id"] + 1 message = update.get("message", {}) if not message: continue chat_id = str(message["chat"]["id"]) text = message.get("text", "") if not text: continue if MASTER_CHAT_ID and chat_id != MASTER_CHAT_ID: await self.send_message(chat_id, "⛔ Unauthorized.") continue response = await self.process_command(chat_id, text) if response: for i in range(0, len(response), 4000): await self.send_message(chat_id, response[i:i+4000]) except Exception as e: print(f"Bot error: {e}") await asyncio.sleep(1) def stop(self): self.running = False bot = JarvisTelegramBot()