Update app.py
Browse files
app.py
CHANGED
|
@@ -17,24 +17,12 @@ if not hasattr(huggingface_hub, "HfFolder"):
|
|
| 17 |
# -------------------------------------------------------------------
|
| 18 |
import spaces
|
| 19 |
import os
|
| 20 |
-
import time
|
| 21 |
-
import json
|
| 22 |
-
import asyncio
|
| 23 |
import httpx
|
| 24 |
import gradio as gr
|
| 25 |
from fastapi import Request
|
| 26 |
from fastapi.responses import JSONResponse
|
| 27 |
from starlette.routing import Route as StarletteRoute
|
| 28 |
-
from telegram import Update, InlineKeyboardButton, InlineKeyboardMarkup
|
| 29 |
-
from telegram.ext import (
|
| 30 |
-
Application,
|
| 31 |
-
CommandHandler,
|
| 32 |
-
MessageHandler,
|
| 33 |
-
filters,
|
| 34 |
-
ContextTypes,
|
| 35 |
-
ConversationHandler,
|
| 36 |
-
CallbackQueryHandler,
|
| 37 |
-
)
|
| 38 |
|
| 39 |
# -------------------------------------------------------------------
|
| 40 |
# 2. CONFIGURATION
|
|
@@ -47,6 +35,9 @@ ADMIN_ID = int(os.getenv("ADMIN_ID", "0"))
|
|
| 47 |
API_BASE = "https://costum-boomber-api.vercel.app/api"
|
| 48 |
API_HEALTH = "https://costum-boomber-api.vercel.app/api/health"
|
| 49 |
|
|
|
|
|
|
|
|
|
|
| 50 |
# In-Memory Database
|
| 51 |
USER_DB = {}
|
| 52 |
|
|
@@ -63,16 +54,15 @@ def _zerogpu_register():
|
|
| 63 |
# -------------------------------------------------------------------
|
| 64 |
# 4. HELPER FUNCTIONS
|
| 65 |
# -------------------------------------------------------------------
|
| 66 |
-
async def send_log(
|
| 67 |
try:
|
| 68 |
-
await
|
| 69 |
except Exception as e:
|
| 70 |
print(f"Failed to send log: {e}")
|
| 71 |
|
| 72 |
-
async def check_channel_membership(
|
| 73 |
-
user_id = update.effective_user.id
|
| 74 |
try:
|
| 75 |
-
member = await
|
| 76 |
return member.status not in ['left', 'kicked', 'restricted']
|
| 77 |
except Exception as e:
|
| 78 |
print(f"Channel check error: {e}")
|
|
@@ -91,245 +81,179 @@ def get_join_keyboard():
|
|
| 91 |
])
|
| 92 |
|
| 93 |
# -------------------------------------------------------------------
|
| 94 |
-
# 5.
|
| 95 |
# -------------------------------------------------------------------
|
| 96 |
-
async def
|
| 97 |
user = update.effective_user
|
|
|
|
| 98 |
user_id = user.id
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
if not is_member:
|
| 107 |
-
USER_DB[user_id]["verified"] = False
|
| 108 |
-
await update.message.reply_text(
|
| 109 |
-
"🔒 <b>Access Denied</b>\n\nYou must join our official channel to use this bot.",
|
| 110 |
-
parse_mode="HTML",
|
| 111 |
-
reply_markup=get_join_keyboard()
|
| 112 |
-
)
|
| 113 |
-
return ConversationHandler.END
|
| 114 |
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
if not USER_DB[user_id]["accepted"]:
|
| 118 |
-
await update.message.reply_text(
|
| 119 |
-
"⚠️ <b>IMPORTANT DISCLAIMER</b>\n\n"
|
| 120 |
-
"This bot is for <b>educational and testing purposes only</b>. "
|
| 121 |
-
"You agree not to use this tool to harass, threaten, or spam individuals. "
|
| 122 |
-
"You confirm you have consent to test the target number. "
|
| 123 |
-
"All requests are logged.\n\n"
|
| 124 |
-
"By clicking 'I Accept', you agree to these terms.",
|
| 125 |
-
parse_mode="HTML",
|
| 126 |
-
reply_markup=get_disclaimer_keyboard()
|
| 127 |
-
)
|
| 128 |
-
return ConversationHandler.END
|
| 129 |
|
| 130 |
-
|
| 131 |
-
|
| 132 |
-
|
| 133 |
-
|
| 134 |
-
|
| 135 |
|
| 136 |
-
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
|
| 141 |
-
if query.data == "check_join":
|
| 142 |
-
is_member = await check_channel_membership(update, context)
|
| 143 |
-
if is_member:
|
| 144 |
-
USER_DB[user_id]["verified"] = True
|
| 145 |
-
if USER_DB[user_id]["accepted"]:
|
| 146 |
-
await query.edit_message_text("✅ Channel verified! Use /send to begin.")
|
| 147 |
-
else:
|
| 148 |
-
await query.edit_message_text("⚠️ Please accept the disclaimer to continue.", reply_markup=get_disclaimer_keyboard())
|
| 149 |
-
else:
|
| 150 |
-
await query.edit_message_text("❌ You have not joined the channel yet.", reply_markup=get_join_keyboard())
|
| 151 |
-
|
| 152 |
-
elif query.data == "accept_disclaimer":
|
| 153 |
-
USER_DB[user_id]["accepted"] = True
|
| 154 |
-
await query.edit_message_text("✅ Disclaimer accepted! Use /send to begin.")
|
| 155 |
-
await send_log(context, f"✅ <b>DISCLAIMER ACCEPTED</b>\nID: <code>{user_id}</code>")
|
| 156 |
|
| 157 |
-
|
| 158 |
-
|
| 159 |
-
await send_log(context, f"🚫 <b>DISCLAIMER DECLINED</b>\nID: <code>{user_id}</code>")
|
| 160 |
-
|
| 161 |
-
# -------------------------------------------------------------------
|
| 162 |
-
# 6. MAIN BOT FLOW
|
| 163 |
-
# -------------------------------------------------------------------
|
| 164 |
-
async def send_command(update: Update, context: ContextTypes.DEFAULT_TYPE) -> int:
|
| 165 |
-
user_id = update.effective_user.id
|
| 166 |
-
if user_id not in USER_DB or not USER_DB[user_id]["accepted"] or not USER_DB[user_id]["verified"]:
|
| 167 |
-
await update.message.reply_text("❌ You must /start and verify first.")
|
| 168 |
-
return ConversationHandler.END
|
| 169 |
-
|
| 170 |
-
await update.message.reply_text("📱 Please enter the 10-digit target phone number:")
|
| 171 |
-
return ASK_NUMBER
|
| 172 |
-
|
| 173 |
-
async def receive_number(update: Update, context: ContextTypes.DEFAULT_TYPE) -> int:
|
| 174 |
-
number = update.message.text.strip()
|
| 175 |
-
if not number.isdigit() or len(number) != 10:
|
| 176 |
-
await update.message.reply_text("❌ Invalid number. Please enter exactly 10 digits:")
|
| 177 |
-
return ASK_NUMBER
|
| 178 |
-
|
| 179 |
-
context.user_data['target_number'] = number
|
| 180 |
-
await update.message.reply_text("💬 Enter the message you want to send:")
|
| 181 |
-
return ASK_MESSAGE
|
| 182 |
-
|
| 183 |
-
async def receive_message(update: Update, context: ContextTypes.DEFAULT_TYPE) -> int:
|
| 184 |
-
msg = update.message.text
|
| 185 |
-
if not msg:
|
| 186 |
-
await update.message.reply_text("❌ Message cannot be empty. Try again:")
|
| 187 |
-
return ASK_MESSAGE
|
| 188 |
-
|
| 189 |
-
context.user_data['target_msg'] = msg
|
| 190 |
-
await update.message.reply_text("🔢 How many times? (Min: 1, Max: 10):")
|
| 191 |
-
return ASK_COUNT
|
| 192 |
-
|
| 193 |
-
async def receive_count(update: Update, context: ContextTypes.DEFAULT_TYPE) -> int:
|
| 194 |
-
try:
|
| 195 |
-
count = int(update.message.text.strip())
|
| 196 |
-
if count < 1 or count > 10:
|
| 197 |
-
await update.message.reply_text("❌ Count must be between 1 and 10. Try again:")
|
| 198 |
-
return ASK_COUNT
|
| 199 |
-
except ValueError:
|
| 200 |
-
await update.message.reply_text("❌ Please enter a valid number between 1 and 10.")
|
| 201 |
-
return ASK_COUNT
|
| 202 |
|
| 203 |
-
|
| 204 |
-
msg
|
| 205 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 206 |
|
| 207 |
-
|
| 208 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 209 |
|
| 210 |
-
|
| 211 |
-
|
| 212 |
-
|
| 213 |
-
|
| 214 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 215 |
|
| 216 |
-
|
| 217 |
-
|
| 218 |
-
|
| 219 |
-
|
| 220 |
-
f"Failed: {data.get('failed')}\n"
|
| 221 |
-
f"Time: {data.get('elapsedSec')}s\n"
|
| 222 |
-
f"Devices Used: {data.get('devicesAvailable')}"
|
| 223 |
-
)
|
| 224 |
-
await update.message.reply_text(reply, parse_mode="HTML")
|
| 225 |
-
await send_log(context, f"✅ <b>SUCCESS</b>\nSent: {data.get('sent')} | Failed: {data.get('failed')}")
|
| 226 |
-
else:
|
| 227 |
-
await update.message.reply_text("❌ API returned an error. Please try again later.")
|
| 228 |
-
await send_log(context, f"❌ <b>API ERROR</b>\nStatus: {resp.status_code}\nBody: {resp.text[:100]}")
|
| 229 |
-
except Exception as e:
|
| 230 |
-
await update.message.reply_text("❌ Network Error. Please try again.")
|
| 231 |
-
await send_log(context, f"❌ <b>NETWORK ERROR</b>\n{str(e)[:100]}")
|
| 232 |
|
| 233 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 234 |
|
| 235 |
-
|
| 236 |
-
|
| 237 |
-
|
| 238 |
-
|
| 239 |
-
|
| 240 |
-
async with httpx.AsyncClient() as client:
|
| 241 |
-
try:
|
| 242 |
-
resp = await client.get(API_HEALTH, timeout=10.0)
|
| 243 |
-
data = resp.json()
|
| 244 |
-
if data.get("ok"):
|
| 245 |
-
config = data.get("config", {})
|
| 246 |
-
text = (
|
| 247 |
-
f"**📡 SYSTEM STATUS**\n"
|
| 248 |
-
f"Status: 🟢 OPERATIONAL\n"
|
| 249 |
-
f"Cache Age: {data.get('cacheAgeSec')}s\n"
|
| 250 |
-
f"Cached Devices: {data.get('cachedDevices')}\n"
|
| 251 |
-
f"DB Nodes: {data.get('dbs')}\n"
|
| 252 |
-
f"Config: Retry:{config.get('default_retry')} | Shotgun:{config.get('default_shotgun')} | Workers:{config.get('max_workers')}"
|
| 253 |
-
)
|
| 254 |
-
await update.message.reply_text(text, parse_mode="Markdown")
|
| 255 |
-
else:
|
| 256 |
-
await update.message.reply_text("🔴 API is down or returned invalid data.")
|
| 257 |
-
except Exception:
|
| 258 |
-
await update.message.reply_text("🔴 Failed to reach API.")
|
| 259 |
|
| 260 |
-
|
| 261 |
-
|
| 262 |
-
|
| 263 |
-
|
| 264 |
-
|
| 265 |
-
|
| 266 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 267 |
return
|
| 268 |
-
|
| 269 |
-
message = " ".join(context.args)
|
| 270 |
-
success = 0
|
| 271 |
-
for uid in USER_DB.keys():
|
| 272 |
-
try:
|
| 273 |
-
await context.bot.send_message(chat_id=uid, text=message)
|
| 274 |
-
success += 1
|
| 275 |
-
except:
|
| 276 |
-
pass
|
| 277 |
-
await update.message.reply_text(f"✅ Broadcast sent to {success} users.")
|
| 278 |
|
| 279 |
-
|
| 280 |
-
|
| 281 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 282 |
|
| 283 |
# -------------------------------------------------------------------
|
| 284 |
-
#
|
| 285 |
# -------------------------------------------------------------------
|
| 286 |
-
|
| 287 |
-
|
| 288 |
-
|
| 289 |
-
|
| 290 |
-
|
| 291 |
-
|
| 292 |
-
|
| 293 |
-
|
| 294 |
-
|
| 295 |
-
},
|
| 296 |
-
fallbacks=[CommandHandler("cancel", cancel)],
|
| 297 |
-
)
|
| 298 |
-
|
| 299 |
-
ptb_app.add_handler(CommandHandler("start", start))
|
| 300 |
-
ptb_app.add_handler(CommandHandler("health", health_command))
|
| 301 |
-
ptb_app.add_handler(CommandHandler("broadcast", broadcast_command))
|
| 302 |
-
ptb_app.add_handler(CallbackQueryHandler(button_callback))
|
| 303 |
-
ptb_app.add_handler(conv_handler)
|
| 304 |
-
|
| 305 |
-
# Initialize Telegram App (but don't start polling yet)
|
| 306 |
-
loop = asyncio.new_event_loop()
|
| 307 |
-
asyncio.set_event_loop(loop)
|
| 308 |
-
loop.run_until_complete(ptb_app.initialize())
|
| 309 |
|
| 310 |
-
|
| 311 |
-
|
| 312 |
-
loop.create_task(ptb_app.updater.start_polling())
|
| 313 |
|
| 314 |
# -------------------------------------------------------------------
|
| 315 |
-
#
|
| 316 |
# -------------------------------------------------------------------
|
| 317 |
with gr.Blocks(title="Telegram Bot Host") as demo:
|
| 318 |
gr.Markdown("# 🤖 Telegram Bot is Running!")
|
| 319 |
-
gr.Markdown("This Space is hosting your Telegram Bot
|
| 320 |
|
| 321 |
-
# ZeroGPU required dummy button
|
| 322 |
_zerogpu_btn = gr.Button("init-gpu", visible=False)
|
| 323 |
_zerogpu_btn.click(fn=_zerogpu_register, inputs=None, outputs=None)
|
| 324 |
|
| 325 |
# -------------------------------------------------------------------
|
| 326 |
-
#
|
| 327 |
# -------------------------------------------------------------------
|
| 328 |
-
async def health_check(request: Request):
|
| 329 |
-
return JSONResponse({"status": "ok", "bot": "running"})
|
| 330 |
-
|
| 331 |
if __name__ == "__main__":
|
| 332 |
-
# Launch Gradio
|
| 333 |
demo.launch(
|
| 334 |
server_name="0.0.0.0",
|
| 335 |
server_port=7860,
|
|
@@ -338,10 +262,11 @@ if __name__ == "__main__":
|
|
| 338 |
prevent_thread_lock=True
|
| 339 |
)
|
| 340 |
|
| 341 |
-
# Inject
|
| 342 |
live_app = demo.app
|
|
|
|
| 343 |
live_app.router.routes.insert(0, StarletteRoute("/health", health_check, methods=["GET"]))
|
| 344 |
live_app.build_middleware_stack()
|
| 345 |
|
| 346 |
-
# Block
|
| 347 |
demo.block_thread()
|
|
|
|
| 17 |
# -------------------------------------------------------------------
|
| 18 |
import spaces
|
| 19 |
import os
|
|
|
|
|
|
|
|
|
|
| 20 |
import httpx
|
| 21 |
import gradio as gr
|
| 22 |
from fastapi import Request
|
| 23 |
from fastapi.responses import JSONResponse
|
| 24 |
from starlette.routing import Route as StarletteRoute
|
| 25 |
+
from telegram import Update, InlineKeyboardButton, InlineKeyboardMarkup, Bot
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 26 |
|
| 27 |
# -------------------------------------------------------------------
|
| 28 |
# 2. CONFIGURATION
|
|
|
|
| 35 |
API_BASE = "https://costum-boomber-api.vercel.app/api"
|
| 36 |
API_HEALTH = "https://costum-boomber-api.vercel.app/api/health"
|
| 37 |
|
| 38 |
+
# Initialize Bot
|
| 39 |
+
bot = Bot(token=BOT_TOKEN)
|
| 40 |
+
|
| 41 |
# In-Memory Database
|
| 42 |
USER_DB = {}
|
| 43 |
|
|
|
|
| 54 |
# -------------------------------------------------------------------
|
| 55 |
# 4. HELPER FUNCTIONS
|
| 56 |
# -------------------------------------------------------------------
|
| 57 |
+
async def send_log(text: str):
|
| 58 |
try:
|
| 59 |
+
await bot.send_message(chat_id=LOG_CHANNEL_ID, text=text, parse_mode="HTML")
|
| 60 |
except Exception as e:
|
| 61 |
print(f"Failed to send log: {e}")
|
| 62 |
|
| 63 |
+
async def check_channel_membership(user_id: int) -> bool:
|
|
|
|
| 64 |
try:
|
| 65 |
+
member = await bot.get_chat_member(chat_id=CHANNEL_ID, user_id=user_id)
|
| 66 |
return member.status not in ['left', 'kicked', 'restricted']
|
| 67 |
except Exception as e:
|
| 68 |
print(f"Channel check error: {e}")
|
|
|
|
| 81 |
])
|
| 82 |
|
| 83 |
# -------------------------------------------------------------------
|
| 84 |
+
# 5. RAW TELEGRAM UPDATE HANDLER (Replaces PTB Polling)
|
| 85 |
# -------------------------------------------------------------------
|
| 86 |
+
async def process_update(update: Update):
|
| 87 |
user = update.effective_user
|
| 88 |
+
if not user: return
|
| 89 |
user_id = user.id
|
| 90 |
+
msg = update.message
|
| 91 |
+
cb_query = update.callback_query
|
| 92 |
+
|
| 93 |
+
# Handle /start
|
| 94 |
+
if msg and msg.text and msg.text.startswith("/start"):
|
| 95 |
+
if user_id not in USER_DB:
|
| 96 |
+
USER_DB[user_id] = {"accepted": False, "verified": False, "state": None}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 97 |
|
| 98 |
+
await send_log(f"👤 <b>NEW USER</b>\nID: <code>{user_id}</code>\nUsername: @{user.username or 'None'}")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 99 |
|
| 100 |
+
is_member = await check_channel_membership(user_id)
|
| 101 |
+
if not is_member:
|
| 102 |
+
USER_DB[user_id]["verified"] = False
|
| 103 |
+
await bot.send_message(chat_id=user_id, text="🔒 <b>Access Denied</b>\n\nYou must join our channel.", parse_mode="HTML", reply_markup=get_join_keyboard())
|
| 104 |
+
return
|
| 105 |
|
| 106 |
+
USER_DB[user_id]["verified"] = True
|
| 107 |
+
if not USER_DB[user_id]["accepted"]:
|
| 108 |
+
await bot.send_message(chat_id=user_id, text="⚠️ <b>DISCLAIMER</b>\n\nEducational use only. No spam/harassment. All requests are logged. By clicking 'I Accept', you agree.", parse_mode="HTML", reply_markup=get_disclaimer_keyboard())
|
| 109 |
+
return
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 110 |
|
| 111 |
+
await bot.send_message(chat_id=user_id, text="✅ <b>Welcome back!</b>\nUse /send to start.", parse_mode="HTML")
|
| 112 |
+
return
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 113 |
|
| 114 |
+
# Handle /health
|
| 115 |
+
if msg and msg.text and msg.text.startswith("/health"):
|
| 116 |
+
await bot.send_message(chat_id=user_id, text="📡 Pinging API...")
|
| 117 |
+
try:
|
| 118 |
+
async with httpx.AsyncClient() as client:
|
| 119 |
+
resp = await client.get(API_HEALTH, timeout=10.0)
|
| 120 |
+
data = resp.json()
|
| 121 |
+
if data.get("ok"):
|
| 122 |
+
config = data.get("config", {})
|
| 123 |
+
text = (
|
| 124 |
+
f"**📡 SYSTEM STATUS**\n"
|
| 125 |
+
f"Status: 🟢 OPERATIONAL\n"
|
| 126 |
+
f"Cache Age: {data.get('cacheAgeSec')}s\n"
|
| 127 |
+
f"Cached Devices: {data.get('cachedDevices')}\n"
|
| 128 |
+
f"DB Nodes: {data.get('dbs')}\n"
|
| 129 |
+
f"Config: Retry:{config.get('default_retry')} | Shotgun:{config.get('default_shotgun')} | Workers:{config.get('max_workers')}"
|
| 130 |
+
)
|
| 131 |
+
await bot.send_message(chat_id=user_id, text=text, parse_mode="Markdown")
|
| 132 |
+
else:
|
| 133 |
+
await bot.send_message(chat_id=user_id, text="🔴 API is down.")
|
| 134 |
+
except Exception:
|
| 135 |
+
await bot.send_message(chat_id=user_id, text="🔴 Failed to reach API.")
|
| 136 |
+
return
|
| 137 |
|
| 138 |
+
# Handle /send (State Machine)
|
| 139 |
+
if msg and msg.text and msg.text.startswith("/send"):
|
| 140 |
+
if user_id not in USER_DB or not USER_DB[user_id]["accepted"] or not USER_DB[user_id]["verified"]:
|
| 141 |
+
await bot.send_message(chat_id=user_id, text="❌ You must /start and verify first.")
|
| 142 |
+
return
|
| 143 |
+
USER_DB[user_id]["state"] = ASK_NUMBER
|
| 144 |
+
await bot.send_message(chat_id=user_id, text="📱 Enter the 10-digit target phone number:")
|
| 145 |
+
return
|
| 146 |
|
| 147 |
+
# Handle text inputs based on state
|
| 148 |
+
if msg and msg.text and user_id in USER_DB and USER_DB[user_id].get("state") is not None:
|
| 149 |
+
state = USER_DB[user_id]["state"]
|
| 150 |
+
|
| 151 |
+
if state == ASK_NUMBER:
|
| 152 |
+
number = msg.text.strip()
|
| 153 |
+
if not number.isdigit() or len(number) != 10:
|
| 154 |
+
await bot.send_message(chat_id=user_id, text="❌ Invalid number. Enter 10 digits:")
|
| 155 |
+
return
|
| 156 |
+
USER_DB[user_id]["target_number"] = number
|
| 157 |
+
USER_DB[user_id]["state"] = ASK_MESSAGE
|
| 158 |
+
await bot.send_message(chat_id=user_id, text="💬 Enter the message:")
|
| 159 |
|
| 160 |
+
elif state == ASK_MESSAGE:
|
| 161 |
+
USER_DB[user_id]["target_msg"] = msg.text
|
| 162 |
+
USER_DB[user_id]["state"] = ASK_COUNT
|
| 163 |
+
await bot.send_message(chat_id=user_id, text="🔢 How many times? (1-10):")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 164 |
|
| 165 |
+
elif state == ASK_COUNT:
|
| 166 |
+
try:
|
| 167 |
+
count = int(msg.text.strip())
|
| 168 |
+
if count < 1 or count > 10:
|
| 169 |
+
await bot.send_message(chat_id=user_id, text="❌ Must be 1-10. Try again:")
|
| 170 |
+
return
|
| 171 |
+
except ValueError:
|
| 172 |
+
await bot.send_message(chat_id=user_id, text="❌ Enter a valid number 1-10.")
|
| 173 |
+
return
|
| 174 |
|
| 175 |
+
number = USER_DB[user_id]["target_number"]
|
| 176 |
+
t_msg = USER_DB[user_id]["target_msg"]
|
| 177 |
+
|
| 178 |
+
await bot.send_message(chat_id=user_id, text="⏳ Sending request...")
|
| 179 |
+
await send_log(f"🚀 <b>NEW ATTACK</b>\nUser: <code>{user_id}</code>\nTarget: <code>{number}</code>\nMsg: {t_msg}\nCount: {count}")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 180 |
|
| 181 |
+
url = f"{API_BASE}?count={count}&msg={t_msg}&number={number}"
|
| 182 |
+
async with httpx.AsyncClient(timeout=30.0) as client:
|
| 183 |
+
try:
|
| 184 |
+
resp = await client.get(url)
|
| 185 |
+
data = resp.json()
|
| 186 |
+
if resp.status_code == 200 and data.get("ok"):
|
| 187 |
+
reply = f"✅ <b>Success!</b>\nSent: {data.get('sent')}\nFailed: {data.get('failed')}\nTime: {data.get('elapsedSec')}s\nDevices: {data.get('devicesAvailable')}"
|
| 188 |
+
await bot.send_message(chat_id=user_id, text=reply, parse_mode="HTML")
|
| 189 |
+
await send_log(f"✅ <b>SUCCESS</b>\nSent: {data.get('sent')} | Failed: {data.get('failed')}")
|
| 190 |
+
else:
|
| 191 |
+
await bot.send_message(chat_id=user_id, text="❌ API error. Try later.")
|
| 192 |
+
await send_log(f"❌ <b>API ERROR</b>\nStatus: {resp.status_code}")
|
| 193 |
+
except Exception as e:
|
| 194 |
+
await bot.send_message(chat_id=user_id, text="❌ Network Error.")
|
| 195 |
+
await send_log(f"❌ <b>NETWORK ERROR</b>\n{str(e)[:100]}")
|
| 196 |
+
|
| 197 |
+
USER_DB[user_id]["state"] = None # Reset state
|
| 198 |
return
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 199 |
|
| 200 |
+
# Handle Callback Queries (Inline Buttons)
|
| 201 |
+
if cb_query:
|
| 202 |
+
await bot.answer_callback_query(callback_query_id=cb_query.id)
|
| 203 |
+
data = cb_query.data
|
| 204 |
+
|
| 205 |
+
if data == "check_join":
|
| 206 |
+
is_member = await check_channel_membership(user_id)
|
| 207 |
+
if is_member:
|
| 208 |
+
USER_DB[user_id]["verified"] = True
|
| 209 |
+
if USER_DB[user_id]["accepted"]:
|
| 210 |
+
await bot.edit_message_text(chat_id=user_id, message_id=cb_query.message.message_id, text="✅ Channel verified! Use /send to begin.")
|
| 211 |
+
else:
|
| 212 |
+
await bot.edit_message_text(chat_id=user_id, message_id=cb_query.message.message_id, text="⚠️ Please accept the disclaimer.", reply_markup=get_disclaimer_keyboard())
|
| 213 |
+
else:
|
| 214 |
+
await bot.edit_message_text(chat_id=user_id, message_id=cb_query.message.message_id, text="❌ You have not joined yet.", reply_markup=get_join_keyboard())
|
| 215 |
+
|
| 216 |
+
elif data == "accept_disclaimer":
|
| 217 |
+
USER_DB[user_id]["accepted"] = True
|
| 218 |
+
await bot.edit_message_text(chat_id=user_id, message_id=cb_query.message.message_id, text="✅ Disclaimer accepted! Use /send to begin.")
|
| 219 |
+
await send_log(f"✅ <b>DISCLAIMER ACCEPTED</b>\nID: <code>{user_id}</code>")
|
| 220 |
+
|
| 221 |
+
elif data == "decline_disclaimer":
|
| 222 |
+
await bot.edit_message_text(chat_id=user_id, message_id=cb_query.message.message_id, text="❌ You declined the disclaimer.")
|
| 223 |
+
await send_log(f"🚫 <b>DISCLAIMER DECLINED</b>\nID: <code>{user_id}</code>")
|
| 224 |
+
return
|
| 225 |
|
| 226 |
# -------------------------------------------------------------------
|
| 227 |
+
# 6. FASTAPI WEBHOOK ENDPOINT
|
| 228 |
# -------------------------------------------------------------------
|
| 229 |
+
async def telegram_webhook(request: Request):
|
| 230 |
+
try:
|
| 231 |
+
data = await request.json()
|
| 232 |
+
update = Update.de_json(data, bot)
|
| 233 |
+
await process_update(update)
|
| 234 |
+
return JSONResponse({"status": "ok"})
|
| 235 |
+
except Exception as e:
|
| 236 |
+
print(f"Webhook error: {e}")
|
| 237 |
+
return JSONResponse({"status": "error"}, status_code=500)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 238 |
|
| 239 |
+
async def health_check(request: Request):
|
| 240 |
+
return JSONResponse({"status": "ok", "bot": "running"})
|
|
|
|
| 241 |
|
| 242 |
# -------------------------------------------------------------------
|
| 243 |
+
# 7. GRADIO UI
|
| 244 |
# -------------------------------------------------------------------
|
| 245 |
with gr.Blocks(title="Telegram Bot Host") as demo:
|
| 246 |
gr.Markdown("# 🤖 Telegram Bot is Running!")
|
| 247 |
+
gr.Markdown("This Space is hosting your Telegram Bot via Webhooks. You can close this tab.")
|
| 248 |
|
|
|
|
| 249 |
_zerogpu_btn = gr.Button("init-gpu", visible=False)
|
| 250 |
_zerogpu_btn.click(fn=_zerogpu_register, inputs=None, outputs=None)
|
| 251 |
|
| 252 |
# -------------------------------------------------------------------
|
| 253 |
+
# 8. LAUNCH & ROUTE INJECTION
|
| 254 |
# -------------------------------------------------------------------
|
|
|
|
|
|
|
|
|
|
| 255 |
if __name__ == "__main__":
|
| 256 |
+
# Launch Gradio but prevent thread lock
|
| 257 |
demo.launch(
|
| 258 |
server_name="0.0.0.0",
|
| 259 |
server_port=7860,
|
|
|
|
| 262 |
prevent_thread_lock=True
|
| 263 |
)
|
| 264 |
|
| 265 |
+
# Inject routes BEFORE blocking the thread
|
| 266 |
live_app = demo.app
|
| 267 |
+
live_app.router.routes.insert(0, StarletteRoute("/webhook", telegram_webhook, methods=["POST"]))
|
| 268 |
live_app.router.routes.insert(0, StarletteRoute("/health", health_check, methods=["GET"]))
|
| 269 |
live_app.build_middleware_stack()
|
| 270 |
|
| 271 |
+
# Block thread to keep Space alive
|
| 272 |
demo.block_thread()
|