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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import asyncio
|
| 3 |
+
import httpx
|
| 4 |
+
from modules.agents import MODULES, run_module
|
| 5 |
+
from jarvis_links import get_all_links, get_random_template
|
| 6 |
+
|
| 7 |
+
BOT_TOKEN = os.environ.get("TELEGRAM_BOT_TOKEN", "")
|
| 8 |
+
MASTER_CHAT_ID = os.environ.get("TELEGRAM_CHAT_ID", "")
|
| 9 |
+
API_URL = f"https://api.telegram.org/bot{BOT_TOKEN}"
|
| 10 |
+
|
| 11 |
+
class JarvisTelegramBot:
|
| 12 |
+
def __init__(self):
|
| 13 |
+
self.offset = 0
|
| 14 |
+
self.running = False
|
| 15 |
+
|
| 16 |
+
async def send_message(self, chat_id: str, text: str) -> bool:
|
| 17 |
+
if not BOT_TOKEN:
|
| 18 |
+
return False
|
| 19 |
+
try:
|
| 20 |
+
async with httpx.AsyncClient(timeout=30) as client:
|
| 21 |
+
response = await client.post(f"{API_URL}/sendMessage", json={
|
| 22 |
+
"chat_id": chat_id,
|
| 23 |
+
"text": text[:4096],
|
| 24 |
+
"parse_mode": "Markdown"
|
| 25 |
+
})
|
| 26 |
+
return response.status_code == 200
|
| 27 |
+
except Exception:
|
| 28 |
+
return False
|
| 29 |
+
|
| 30 |
+
async def notify_master(self, text: str):
|
| 31 |
+
if MASTER_CHAT_ID:
|
| 32 |
+
await self.send_message(MASTER_CHAT_ID, text)
|
| 33 |
+
|
| 34 |
+
async def get_updates(self) -> list:
|
| 35 |
+
try:
|
| 36 |
+
async with httpx.AsyncClient(timeout=30) as client:
|
| 37 |
+
response = await client.get(f"{API_URL}/getUpdates",
|
| 38 |
+
params={"offset": self.offset, "timeout": 10})
|
| 39 |
+
if response.status_code == 200:
|
| 40 |
+
return response.json().get("result", [])
|
| 41 |
+
except Exception:
|
| 42 |
+
pass
|
| 43 |
+
return []
|
| 44 |
+
|
| 45 |
+
async def process_command(self, chat_id: str, text: str) -> str:
|
| 46 |
+
parts = text.strip().split(None, 2)
|
| 47 |
+
command = parts[0].lower()
|
| 48 |
+
args = parts[1] if len(parts) > 1 else ""
|
| 49 |
+
extra = parts[2] if len(parts) > 2 else ""
|
| 50 |
+
|
| 51 |
+
if command in ["/start", "/help"]:
|
| 52 |
+
return """🤖 *JARVIS EMPIRE — Online*
|
| 53 |
+
|
| 54 |
+
*COMMANDS:*
|
| 55 |
+
/status — Cek status sistem
|
| 56 |
+
/trend [topik] — Hijack trending topic
|
| 57 |
+
/write [topik] [hostinger/shopee] — Tulis konten
|
| 58 |
+
/analyze [konten] — Prediksi viral score
|
| 59 |
+
/scout [target] — Riset kompetitor
|
| 60 |
+
/ghost [konten] — Distribusi multi-platform
|
| 61 |
+
/publish [konten] — Jadwal publishing
|
| 62 |
+
/analyst — Analisa performa
|
| 63 |
+
/links — Affiliate links
|
| 64 |
+
/runall — Jalankan semua modul"""
|
| 65 |
+
|
| 66 |
+
elif command == "/status":
|
| 67 |
+
from ai_engine import engine
|
| 68 |
+
available = engine.get_available_providers()
|
| 69 |
+
return f"""⚡ *JARVIS STATUS*
|
| 70 |
+
*AI Providers:* {len(available)} aktif
|
| 71 |
+
{chr(10).join(['✅ ' + p for p in available]) if available else '❌ Tidak ada API key'}
|
| 72 |
+
*Modul:* 7 aktif
|
| 73 |
+
*Status:* 🟢 Online"""
|
| 74 |
+
|
| 75 |
+
elif command == "/links":
|
| 76 |
+
links = get_all_links()
|
| 77 |
+
msg = "🔗 *AFFILIATE LINKS*\n\n"
|
| 78 |
+
for platform, data in links.items():
|
| 79 |
+
msg += f"*{platform.upper()}*\n{data['full']}\nKomisi: {data['commission']}\n\n"
|
| 80 |
+
return msg
|
| 81 |
+
|
| 82 |
+
elif command == "/trend":
|
| 83 |
+
topic = args or None
|
| 84 |
+
await self.send_message(chat_id, "🔥 Mencari trending topic...")
|
| 85 |
+
result = await run_module("trend", custom_topic=topic)
|
| 86 |
+
return f"🔥 *TREND HIJACKER*\n\n{result['output']}\n\n_via {result['provider']}_"
|
| 87 |
+
|
| 88 |
+
elif command == "/write":
|
| 89 |
+
if not args:
|
| 90 |
+
return "❌ Format: `/write [topik] [hostinger/shopee]`"
|
| 91 |
+
platform = "shopee" if "shopee" in text.lower() else "hostinger"
|
| 92 |
+
topic = args.replace("shopee","").replace("hostinger","").strip()
|
| 93 |
+
await self.send_message(chat_id, f"✍️ Menulis konten '{topic}'...")
|
| 94 |
+
result = await run_module("writer", topic=topic, platform=platform)
|
| 95 |
+
return f"✍️ *KONTEN AFFILIATE*\n\n{result['output']}\n\n_via {result['provider']}_"
|
| 96 |
+
|
| 97 |
+
elif command == "/analyze":
|
| 98 |
+
content = f"{args} {extra}".strip()
|
| 99 |
+
if not content:
|
| 100 |
+
return "❌ Format: `/analyze [konten]`"
|
| 101 |
+
await self.send_message(chat_id, "📊 Menganalisa...")
|
| 102 |
+
result = await run_module("viral", content=content)
|
| 103 |
+
return f"📊 *VIRAL PREDICTOR*\n\n{result['output']}\n\n_via {result['provider']}_"
|
| 104 |
+
|
| 105 |
+
elif command == "/scout":
|
| 106 |
+
target = args or "hostinger competitor indonesia"
|
| 107 |
+
await self.send_message(chat_id, f"🔍 Riset '{target}'...")
|
| 108 |
+
result = await run_module("scout", target=target)
|
| 109 |
+
return f"🔍 *SCOUT REPORT*\n\n{result['output']}\n\n_via {result['provider']}_"
|
| 110 |
+
|
| 111 |
+
elif command == "/ghost":
|
| 112 |
+
content = f"{args} {extra}".strip()
|
| 113 |
+
if not content:
|
| 114 |
+
return "❌ Format: `/ghost [konten]`"
|
| 115 |
+
await self.send_message(chat_id, "👻 Menyiapkan distribusi...")
|
| 116 |
+
result = await run_module("ghost", content=content)
|
| 117 |
+
return f"👻 *GHOST NETWORK*\n\n{result['output']}\n\n_via {result['provider']}_"
|
| 118 |
+
|
| 119 |
+
elif command == "/publish":
|
| 120 |
+
content = f"{args} {extra}".strip()
|
| 121 |
+
if not content:
|
| 122 |
+
return "❌ Format: `/publish [konten]`"
|
| 123 |
+
await self.send_message(chat_id, "📢 Membuat jadwal...")
|
| 124 |
+
result = await run_module("publisher", content=content)
|
| 125 |
+
return f"📢 *PUBLISHER*\n\n{result['output']}\n\n_via {result['provider']}_"
|
| 126 |
+
|
| 127 |
+
elif command == "/analyst":
|
| 128 |
+
await self.send_message(chat_id, "📈 Menganalisa performa...")
|
| 129 |
+
result = await run_module("analyst")
|
| 130 |
+
return f"📈 *ANALYST*\n\n{result['output']}\n\n_via {result['provider']}_"
|
| 131 |
+
|
| 132 |
+
elif command == "/runall":
|
| 133 |
+
await self.send_message(chat_id, "🚀 Menjalankan semua modul...")
|
| 134 |
+
results = []
|
| 135 |
+
for name, module in MODULES.items():
|
| 136 |
+
try:
|
| 137 |
+
await module.run()
|
| 138 |
+
results.append(f"✅ {module.name}")
|
| 139 |
+
except:
|
| 140 |
+
results.append(f"❌ {name}")
|
| 141 |
+
return "🚀 *RUN ALL*\n\n" + "\n".join(results)
|
| 142 |
+
|
| 143 |
+
else:
|
| 144 |
+
from ai_engine import engine
|
| 145 |
+
result = await engine.think(text)
|
| 146 |
+
return f"🤖 *JARVIS:*\n\n{result['response']}\n\n_via {result['provider']}_"
|
| 147 |
+
|
| 148 |
+
async def start_polling(self):
|
| 149 |
+
self.running = True
|
| 150 |
+
print("🤖 Telegram Bot polling started...")
|
| 151 |
+
if MASTER_CHAT_ID:
|
| 152 |
+
await self.notify_master("🟢 *JARVIS EMPIRE ONLINE*\n\nSistem aktif, Master!")
|
| 153 |
+
while self.running:
|
| 154 |
+
try:
|
| 155 |
+
updates = await self.get_updates()
|
| 156 |
+
for update in updates:
|
| 157 |
+
self.offset = update["update_id"] + 1
|
| 158 |
+
message = update.get("message", {})
|
| 159 |
+
if not message:
|
| 160 |
+
continue
|
| 161 |
+
chat_id = str(message["chat"]["id"])
|
| 162 |
+
text = message.get("text", "")
|
| 163 |
+
if not text:
|
| 164 |
+
continue
|
| 165 |
+
if MASTER_CHAT_ID and chat_id != MASTER_CHAT_ID:
|
| 166 |
+
await self.send_message(chat_id, "⛔ Unauthorized.")
|
| 167 |
+
continue
|
| 168 |
+
response = await self.process_command(chat_id, text)
|
| 169 |
+
if response:
|
| 170 |
+
for i in range(0, len(response), 4000):
|
| 171 |
+
await self.send_message(chat_id, response[i:i+4000])
|
| 172 |
+
except Exception as e:
|
| 173 |
+
print(f"Bot error: {e}")
|
| 174 |
+
await asyncio.sleep(1)
|
| 175 |
+
|
| 176 |
+
def stop(self):
|
| 177 |
+
self.running = False
|
| 178 |
+
|
| 179 |
+
bot = JarvisTelegramBot()
|