Hfzune commited on
Commit
3bf908e
·
verified ·
1 Parent(s): eb1767f

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +152 -227
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(context: ContextTypes.DEFAULT_TYPE, text: str):
67
  try:
68
- await context.bot.send_message(chat_id=LOG_CHANNEL_ID, text=text, parse_mode="HTML")
69
  except Exception as e:
70
  print(f"Failed to send log: {e}")
71
 
72
- async def check_channel_membership(update: Update, context: ContextTypes.DEFAULT_TYPE) -> bool:
73
- user_id = update.effective_user.id
74
  try:
75
- member = await context.bot.get_chat_member(chat_id=CHANNEL_ID, user_id=user_id)
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. ONBOARDING HANDLERS
95
  # -------------------------------------------------------------------
96
- async def start(update: Update, context: ContextTypes.DEFAULT_TYPE) -> int:
97
  user = update.effective_user
 
98
  user_id = user.id
99
-
100
- if user_id not in USER_DB:
101
- USER_DB[user_id] = {"accepted": False, "verified": False}
102
-
103
- await send_log(context, f"👤 <b>NEW USER INTERACTION</b>\nID: <code>{user_id}</code>\nUsername: @{user.username or 'None'}")
104
-
105
- is_member = await check_channel_membership(update, context)
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
- USER_DB[user_id]["verified"] = True
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
- await update.message.reply_text(
131
- "✅ <b>Welcome back!</b>\nUse /send to start a new request, or /health to check API status.",
132
- parse_mode="HTML"
133
- )
134
- return ConversationHandler.END
135
 
136
- async def button_callback(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
137
- query = update.callback_query
138
- await query.answer()
139
- user_id = query.from_user.id
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
- elif query.data == "decline_disclaimer":
158
- await query.edit_message_text("❌ You declined the disclaimer. You cannot use this bot.")
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
- number = context.user_data.get('target_number')
204
- msg = context.user_data.get('target_msg')
205
- user_id = update.effective_user.id
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
206
 
207
- await update.message.reply_text("⏳ Sending request...")
208
- await send_log(context, f"🚀 <b>NEW ATTACK INITIATED</b>\nUser ID: <code>{user_id}</code>\nTarget: <code>{number}</code>\nMessage: {msg}\nCount: {count}")
 
 
 
 
 
 
209
 
210
- url = f"{API_BASE}?count={count}&msg={msg}&number={number}"
211
- async with httpx.AsyncClient(timeout=30.0) as client:
212
- try:
213
- resp = await client.get(url)
214
- data = resp.json()
 
 
 
 
 
 
 
215
 
216
- if resp.status_code == 200 and data.get("ok"):
217
- reply = (
218
- f"✅ <b>Success!</b>\n"
219
- f"Sent: {data.get('sent')}\n"
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
- return ConversationHandler.END
 
 
 
 
 
 
 
 
234
 
235
- # -------------------------------------------------------------------
236
- # 7. HEALTH & ADMIN COMMANDS
237
- # -------------------------------------------------------------------
238
- async def health_command(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
239
- await update.message.reply_text("📡 Pinging API...")
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
- async def broadcast_command(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
261
- if update.effective_user.id != ADMIN_ID:
262
- await update.message.reply_text("⛔ Unauthorized.")
263
- return
264
-
265
- if not context.args:
266
- await update.message.reply_text("Usage: /broadcast <message>")
 
 
 
 
 
 
 
 
 
 
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
- async def cancel(update: Update, context: ContextTypes.DEFAULT_TYPE) -> int:
280
- await update.message.reply_text("❌ Operation cancelled.")
281
- return ConversationHandler.END
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
282
 
283
  # -------------------------------------------------------------------
284
- # 8. TELEGRAM APP & GRADIO SETUP
285
  # -------------------------------------------------------------------
286
- ptb_app = Application.builder().token(BOT_TOKEN).build()
287
-
288
- # Add Handlers
289
- conv_handler = ConversationHandler(
290
- entry_points=[CommandHandler("send", send_command)],
291
- states={
292
- ASK_NUMBER: [MessageHandler(filters.TEXT & ~filters.COMMAND, receive_number)],
293
- ASK_MESSAGE: [MessageHandler(filters.TEXT & ~filters.COMMAND, receive_message)],
294
- ASK_COUNT: [MessageHandler(filters.TEXT & ~filters.COMMAND, receive_count)],
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
- # Start polling in the background
311
- loop.create_task(ptb_app.start())
312
- loop.create_task(ptb_app.updater.start_polling())
313
 
314
  # -------------------------------------------------------------------
315
- # 9. GRADIO UI (To keep the Space alive & satisfy ZeroGPU)
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 in the background. You can close this tab, the bot will keep running as long as the Space is awake.")
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
- # 10. HEALTH ENDPOINT & LAUNCH
327
  # -------------------------------------------------------------------
328
- async def health_check(request: Request):
329
- return JSONResponse({"status": "ok", "bot": "running"})
330
-
331
  if __name__ == "__main__":
332
- # Launch Gradio with SSR disabled and thread lock prevented
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 /health route at index 0 (before Gradio's catch-all)
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 the main thread to keep the Space running
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()