Update app.py
Browse files
app.py
CHANGED
|
@@ -17,334 +17,331 @@ if not hasattr(huggingface_hub, "HfFolder"):
|
|
| 17 |
# -------------------------------------------------------------------
|
| 18 |
import spaces
|
| 19 |
import os
|
| 20 |
-
import json
|
| 21 |
import time
|
| 22 |
-
import
|
| 23 |
-
import
|
| 24 |
-
import
|
| 25 |
-
import pyarrow.parquet as pq
|
| 26 |
import gradio as gr
|
| 27 |
-
from huggingface_hub import HfApi, hf_hub_download
|
| 28 |
from fastapi import Request
|
| 29 |
from fastapi.responses import JSONResponse
|
| 30 |
from starlette.routing import Route as StarletteRoute
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 31 |
|
| 32 |
# -------------------------------------------------------------------
|
| 33 |
-
# 2. CONFIGURATION
|
| 34 |
# -------------------------------------------------------------------
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
|
| 40 |
-
|
|
|
|
| 41 |
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
"current_file": "",
|
| 45 |
-
"total_records": 0,
|
| 46 |
-
"success_count": 0,
|
| 47 |
-
"fail_count": 0,
|
| 48 |
-
"start_time": 0,
|
| 49 |
-
"eta": "Calculating...",
|
| 50 |
-
"speed": 0,
|
| 51 |
-
"logs": []
|
| 52 |
-
}
|
| 53 |
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
def add_log(msg):
|
| 58 |
-
timestamp = time.strftime("%H:%M:%S")
|
| 59 |
-
PROCESSING_STATE["logs"].append(f"[{timestamp}] {msg}")
|
| 60 |
-
if len(PROCESSING_STATE["logs"]) > 8:
|
| 61 |
-
PROCESSING_STATE["logs"].pop(0)
|
| 62 |
|
| 63 |
# -------------------------------------------------------------------
|
| 64 |
-
# 3. DUMMY
|
| 65 |
# -------------------------------------------------------------------
|
| 66 |
@spaces.GPU(duration=10)
|
| 67 |
def _zerogpu_register():
|
| 68 |
return "gpu-ready"
|
| 69 |
|
| 70 |
# -------------------------------------------------------------------
|
| 71 |
-
# 4.
|
| 72 |
# -------------------------------------------------------------------
|
| 73 |
-
def
|
| 74 |
-
"""Removes the credit block."""
|
| 75 |
-
if "credit" in raw_json:
|
| 76 |
-
del raw_json["credit"]
|
| 77 |
-
return raw_json
|
| 78 |
-
|
| 79 |
-
def upload_to_hf(df_chunk, target_repo, work_dir, part_num):
|
| 80 |
-
if df_chunk.empty: return True
|
| 81 |
-
|
| 82 |
-
filename = f"data/enriched_part_{part_num:05d}.parquet"
|
| 83 |
-
local_path = os.path.join(work_dir, "enriched_upload.parquet")
|
| 84 |
-
|
| 85 |
try:
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
api.upload_file(
|
| 90 |
-
path_or_fileobj=local_path,
|
| 91 |
-
path_in_repo=filename,
|
| 92 |
-
repo_id=target_repo,
|
| 93 |
-
repo_type="dataset",
|
| 94 |
-
token=HF_TOKEN
|
| 95 |
-
)
|
| 96 |
-
add_log(f"📤 Uploaded {len(df_chunk)} records to {filename}")
|
| 97 |
-
return True
|
| 98 |
-
except Exception as e:
|
| 99 |
-
if attempt == 2:
|
| 100 |
-
add_log(f"❌ Upload failed after 3 tries: {str(e)[:30]}")
|
| 101 |
-
return False
|
| 102 |
-
time.sleep(5)
|
| 103 |
-
finally:
|
| 104 |
-
if os.path.exists(local_path):
|
| 105 |
-
os.remove(local_path)
|
| 106 |
|
| 107 |
-
def
|
| 108 |
-
|
| 109 |
-
|
| 110 |
try:
|
| 111 |
-
|
| 112 |
-
|
| 113 |
except Exception as e:
|
| 114 |
-
|
| 115 |
-
return
|
| 116 |
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
|
|
|
|
|
|
|
| 126 |
|
| 127 |
-
|
| 128 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 129 |
|
| 130 |
-
|
| 131 |
-
|
|
|
|
|
|
|
| 132 |
|
| 133 |
-
|
| 134 |
-
|
| 135 |
-
|
| 136 |
-
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
|
|
|
|
| 141 |
|
| 142 |
-
|
| 143 |
-
|
| 144 |
-
|
| 145 |
-
|
| 146 |
-
|
| 147 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 148 |
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
|
| 152 |
-
|
| 153 |
-
|
| 154 |
-
|
| 155 |
-
|
| 156 |
-
|
| 157 |
-
|
| 158 |
-
if not aadhaar_col:
|
| 159 |
-
add_log(f"⚠️ No Aadhaar column found in {filename}")
|
| 160 |
-
break
|
| 161 |
|
| 162 |
-
|
| 163 |
-
|
| 164 |
-
|
| 165 |
-
|
| 166 |
-
|
| 167 |
-
|
| 168 |
-
|
| 169 |
-
|
| 170 |
-
|
| 171 |
-
|
| 172 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 173 |
|
| 174 |
-
|
| 175 |
-
|
| 176 |
-
|
| 177 |
-
|
| 178 |
-
|
| 179 |
-
|
| 180 |
-
|
| 181 |
-
|
| 182 |
-
|
| 183 |
-
try:
|
| 184 |
-
response = session.get(API_URL + aadhaar, timeout=25)
|
| 185 |
-
|
| 186 |
-
if response.status_code == 200:
|
| 187 |
-
raw_data = response.json()
|
| 188 |
-
if raw_data.get("status") is True:
|
| 189 |
-
cleaned_data = clean_response(raw_data)
|
| 190 |
-
cleaned_data["_source_file"] = filename
|
| 191 |
-
cleaned_data["_aadhaar_input"] = aadhaar
|
| 192 |
-
output_buffer.append(cleaned_data)
|
| 193 |
-
PROCESSING_STATE["success_count"] += 1
|
| 194 |
-
api_success = True
|
| 195 |
-
else:
|
| 196 |
-
PROCESSING_STATE["fail_count"] += 1
|
| 197 |
-
api_success = True # It returned a valid JSON, just status:false
|
| 198 |
-
break
|
| 199 |
-
|
| 200 |
-
elif response.status_code in [500, 502, 504]:
|
| 201 |
-
# Backend crashed, wait and retry
|
| 202 |
-
add_log(f"⚠️ API 500 Error. Retrying in 5s...")
|
| 203 |
-
time.sleep(5)
|
| 204 |
-
else:
|
| 205 |
-
add_log(f"⚠️ HTTP {response.status_code} for {aadhaar}")
|
| 206 |
-
break
|
| 207 |
-
|
| 208 |
-
except requests.exceptions.Timeout:
|
| 209 |
-
add_log(f"⚠️ Timeout. Retrying in 5s...")
|
| 210 |
-
time.sleep(5)
|
| 211 |
-
except Exception as e:
|
| 212 |
-
add_log(f"⚠️ API Error: {str(e)[:30]}")
|
| 213 |
-
time.sleep(2)
|
| 214 |
|
| 215 |
-
|
| 216 |
-
|
| 217 |
-
|
| 218 |
-
|
| 219 |
-
|
| 220 |
-
|
| 221 |
-
|
| 222 |
-
|
| 223 |
-
|
| 224 |
-
with open(checkpoint_file, "w") as f:
|
| 225 |
-
json.dump(checkpoint, f)
|
| 226 |
|
| 227 |
-
|
| 228 |
-
|
| 229 |
-
|
| 230 |
-
if upload_to_hf(df_out, target_repo, work_dir, checkpoint["part_num"]):
|
| 231 |
-
output_buffer = []
|
| 232 |
-
checkpoint["part_num"] += 1
|
| 233 |
-
with open(checkpoint_file, "w") as f:
|
| 234 |
-
json.dump(checkpoint, f)
|
| 235 |
|
| 236 |
-
|
| 237 |
-
|
| 238 |
-
# This guarantees the backend never crashes.
|
| 239 |
-
elapsed_req = time.time() - req_start
|
| 240 |
-
if elapsed_req < 4.0:
|
| 241 |
-
time.sleep(4.0 - elapsed_req)
|
| 242 |
|
| 243 |
-
|
| 244 |
-
|
| 245 |
-
|
| 246 |
-
|
| 247 |
-
|
| 248 |
-
os.remove(local_path)
|
| 249 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 250 |
except Exception as e:
|
| 251 |
-
|
| 252 |
-
|
| 253 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 254 |
|
| 255 |
-
|
| 256 |
-
|
| 257 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 258 |
|
| 259 |
-
|
| 260 |
-
|
|
|
|
| 261 |
|
| 262 |
# -------------------------------------------------------------------
|
| 263 |
-
#
|
| 264 |
# -------------------------------------------------------------------
|
| 265 |
-
|
| 266 |
-
if PROCESSING_STATE["status"] == "running":
|
| 267 |
-
return "Already running!"
|
| 268 |
-
|
| 269 |
-
STOP_FLAG.clear()
|
| 270 |
-
PAUSE_FLAG.clear()
|
| 271 |
-
|
| 272 |
-
try:
|
| 273 |
-
files = api.list_repo_files(repo_id=SOURCE_DATASET, repo_type="dataset")
|
| 274 |
-
parquet_files = sorted([f for f in files if f.endswith('.parquet')])
|
| 275 |
-
selected_files = parquet_files[int(start_idx):int(end_idx)]
|
| 276 |
-
except Exception as e:
|
| 277 |
-
return f"Failed to get file list: {e}"
|
| 278 |
|
| 279 |
-
|
| 280 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 281 |
|
| 282 |
-
|
| 283 |
-
|
| 284 |
-
|
| 285 |
-
|
| 286 |
-
|
| 287 |
-
thread.start()
|
| 288 |
-
return "Started!"
|
| 289 |
|
| 290 |
-
|
| 291 |
-
|
| 292 |
-
|
| 293 |
-
|
| 294 |
-
succ = PROCESSING_STATE.get("success_count", 0)
|
| 295 |
-
fail = PROCESSING_STATE.get("fail_count", 0)
|
| 296 |
-
speed = PROCESSING_STATE.get("speed", 0)
|
| 297 |
-
|
| 298 |
-
recent_logs = "\n".join(PROCESSING_STATE.get("logs", []))
|
| 299 |
-
|
| 300 |
-
header = f"### STATUS: {status}\n"
|
| 301 |
-
header += f"**Records Processed:** {rows:,} | **Success:** {succ:,} | **Failed:** {fail:,}\n"
|
| 302 |
-
header += f"**Speed:** {speed:.2f} rec/sec\n"
|
| 303 |
-
header += f"**Current File:** `{file}`\n\n"
|
| 304 |
-
header += f"**Live Logs:**\n{recent_logs}"
|
| 305 |
-
|
| 306 |
-
return header
|
| 307 |
|
| 308 |
-
|
| 309 |
-
|
| 310 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 311 |
|
|
|
|
| 312 |
_zerogpu_btn = gr.Button("init-gpu", visible=False)
|
| 313 |
_zerogpu_btn.click(fn=_zerogpu_register, inputs=None, outputs=None)
|
| 314 |
|
| 315 |
-
with gr.Row():
|
| 316 |
-
with gr.Column():
|
| 317 |
-
target_input = gr.Textbox(label="Target Repo ID", value=TARGET_DATASET)
|
| 318 |
-
with gr.Row():
|
| 319 |
-
start_idx = gr.Number(label="Start File Index", value=0)
|
| 320 |
-
end_idx = gr.Number(label="End File Index", value=1)
|
| 321 |
-
|
| 322 |
-
with gr.Row():
|
| 323 |
-
start_btn = gr.Button("▶️ Start", variant="primary")
|
| 324 |
-
pause_btn = gr.Button("⏸️ Pause")
|
| 325 |
-
resume_btn = gr.Button("⏯️ Resume")
|
| 326 |
-
stop_btn = gr.Button("⏹️ Stop", variant="stop")
|
| 327 |
-
|
| 328 |
-
with gr.Column():
|
| 329 |
-
status_box = gr.Markdown("Waiting to start...")
|
| 330 |
-
|
| 331 |
-
start_btn.click(start_processing, [target_input, start_idx, end_idx], status_box)
|
| 332 |
-
pause_btn.click(lambda: PAUSE_FLAG.set() or "Pausing...", None, status_box)
|
| 333 |
-
resume_btn.click(lambda: PAUSE_FLAG.clear() or "Resuming...", None, status_box)
|
| 334 |
-
stop_btn.click(lambda: STOP_FLAG.set() or "Stopping...", None, status_box)
|
| 335 |
-
|
| 336 |
-
timer = gr.Timer(3.0)
|
| 337 |
-
timer.tick(get_status, None, status_box)
|
| 338 |
-
|
| 339 |
# -------------------------------------------------------------------
|
| 340 |
-
#
|
| 341 |
# -------------------------------------------------------------------
|
| 342 |
async def health_check(request: Request):
|
| 343 |
-
return JSONResponse({"status": "ok", "
|
| 344 |
|
| 345 |
if __name__ == "__main__":
|
| 346 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 347 |
live_app = demo.app
|
| 348 |
-
live_app.routes.insert(0, StarletteRoute("/health", health_check, methods=["GET"]))
|
| 349 |
live_app.build_middleware_stack()
|
|
|
|
|
|
|
| 350 |
demo.block_thread()
|
|
|
|
| 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
|
| 41 |
# -------------------------------------------------------------------
|
| 42 |
+
BOT_TOKEN = os.getenv("BOT_TOKEN")
|
| 43 |
+
CHANNEL_ID = os.getenv("CHANNEL_ID")
|
| 44 |
+
LOG_CHANNEL_ID = os.getenv("LOG_CHANNEL_ID")
|
| 45 |
+
ADMIN_ID = int(os.getenv("ADMIN_ID", "0"))
|
| 46 |
|
| 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 |
|
| 53 |
+
# Conversation States
|
| 54 |
+
ASK_NUMBER, ASK_MESSAGE, ASK_COUNT = range(3)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 55 |
|
| 56 |
# -------------------------------------------------------------------
|
| 57 |
+
# 3. ZEROGPU DUMMY HANDLER
|
| 58 |
# -------------------------------------------------------------------
|
| 59 |
@spaces.GPU(duration=10)
|
| 60 |
def _zerogpu_register():
|
| 61 |
return "gpu-ready"
|
| 62 |
|
| 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}")
|
| 79 |
+
return False
|
| 80 |
|
| 81 |
+
def get_disclaimer_keyboard():
|
| 82 |
+
return InlineKeyboardMarkup([
|
| 83 |
+
[InlineKeyboardButton("✅ I Accept & Agree", callback_data="accept_disclaimer")],
|
| 84 |
+
[InlineKeyboardButton("❌ I Decline", callback_data="decline_disclaimer")]
|
| 85 |
+
])
|
| 86 |
+
|
| 87 |
+
def get_join_keyboard():
|
| 88 |
+
return InlineKeyboardMarkup([
|
| 89 |
+
[InlineKeyboardButton("📢 Join Channel", url=f"https://t.me/{CHANNEL_ID.replace('@', '')}")],
|
| 90 |
+
[InlineKeyboardButton("✅ I Have Joined", callback_data="check_join")]
|
| 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,
|
| 336 |
+
share=False,
|
| 337 |
+
ssr_mode=False,
|
| 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()
|