Spaces:
Running
Running
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,61 +1,163 @@
|
|
| 1 |
-
from fastapi import FastAPI, HTTPException,
|
| 2 |
-
import
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3 |
from contextlib import asynccontextmanager
|
| 4 |
|
| 5 |
-
#
|
| 6 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 7 |
|
| 8 |
-
# Lifespan use karke app start hote hi heavy initialization ek baar karenge
|
| 9 |
@asynccontextmanager
|
| 10 |
async def lifespan(app: FastAPI):
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
PARQUET_URL = "https://huggingface.co/datasets/tfqdeadlo/Inddatainonefile/resolve/main/users_data.parquet"
|
| 16 |
|
| 17 |
-
#
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 21 |
yield
|
| 22 |
-
con.close()
|
| 23 |
|
| 24 |
-
app = FastAPI(title="
|
| 25 |
|
| 26 |
@app.get("/")
|
| 27 |
def home():
|
| 28 |
-
return {"
|
| 29 |
|
| 30 |
-
|
| 31 |
-
|
| 32 |
try:
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 40 |
|
| 41 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 42 |
|
| 43 |
-
if
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
|
|
|
|
|
|
| 52 |
|
| 53 |
-
|
| 54 |
-
"
|
| 55 |
-
|
| 56 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 57 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 58 |
except Exception as e:
|
| 59 |
-
|
| 60 |
-
|
| 61 |
|
|
|
|
| 1 |
+
from fastapi import FastAPI, HTTPException, Request, BackgroundTasks
|
| 2 |
+
import telebot
|
| 3 |
+
from telebot import apihelper
|
| 4 |
+
import httpx
|
| 5 |
+
import os
|
| 6 |
+
import time
|
| 7 |
from contextlib import asynccontextmanager
|
| 8 |
|
| 9 |
+
# β‘ PRODUCTION TIMEOUTS: Safe values proxy networks ke liye
|
| 10 |
+
apihelper.CONNECT_TIMEOUT = 30
|
| 11 |
+
apihelper.READ_TIMEOUT = 30
|
| 12 |
+
|
| 13 |
+
BOT_TOKEN = os.environ.get("BOT_TOKEN")
|
| 14 |
+
API_URL = os.environ.get("API_URL", "https://tfqdeadlo-1-78bapi.hf.space/search")
|
| 15 |
+
BOT_SPACE_URL = "https://tfqdeadlo-tgbotc.hf.space"
|
| 16 |
+
|
| 17 |
+
# threaded=False zaroori hai jab hum FastAPI background tasks use karte hain
|
| 18 |
+
bot = telebot.TeleBot(BOT_TOKEN, threaded=False)
|
| 19 |
|
|
|
|
| 20 |
@asynccontextmanager
|
| 21 |
async def lifespan(app: FastAPI):
|
| 22 |
+
if not BOT_TOKEN:
|
| 23 |
+
print("β ERROR: BOT_TOKEN Missing!")
|
| 24 |
+
yield
|
| 25 |
+
return
|
|
|
|
| 26 |
|
| 27 |
+
# Webhook set karne ke liye retry mechanism
|
| 28 |
+
for attempt in range(3):
|
| 29 |
+
try:
|
| 30 |
+
webhook_url = f"{BOT_SPACE_URL}/telegram-webhook"
|
| 31 |
+
bot.remove_webhook()
|
| 32 |
+
bot.set_webhook(url=webhook_url, timeout=30)
|
| 33 |
+
print("β
Webhook successfully set ho gaya startup par!")
|
| 34 |
+
break
|
| 35 |
+
except Exception as e:
|
| 36 |
+
print(f"β οΈ Webhook attempt {attempt+1} fail hua: {e}")
|
| 37 |
+
time.sleep(2)
|
| 38 |
yield
|
|
|
|
| 39 |
|
| 40 |
+
app = FastAPI(title="Lakhs-Users Production Bot", lifespan=lifespan)
|
| 41 |
|
| 42 |
@app.get("/")
|
| 43 |
def home():
|
| 44 |
+
return {"status": "running", "message": "Master-Handler Production Bot Active!"}
|
| 45 |
|
| 46 |
+
# --- BACKGROUND WORKER ---
|
| 47 |
+
def process_telegram_update(json_string: dict):
|
| 48 |
try:
|
| 49 |
+
update = telebot.types.Update.de_json(json_string)
|
| 50 |
+
bot.process_new_updates([update])
|
| 51 |
+
except Exception as e:
|
| 52 |
+
print(f"β Processing me error: {e}")
|
| 53 |
+
|
| 54 |
+
# --- TELEGRAM WEBHOOK ENDPOINT ---
|
| 55 |
+
@app.post("/telegram-webhook")
|
| 56 |
+
async def telegram_webhook(request: Request, background_tasks: BackgroundTasks):
|
| 57 |
+
if request.headers.get("content-type") == "application/json":
|
| 58 |
+
json_string = await request.json()
|
| 59 |
+
# Telegram ko turant 200 OK dekar free karo, taaki request line me na fase
|
| 60 |
+
background_tasks.add_task(process_telegram_update, json_string)
|
| 61 |
+
return {"status": "ok"}
|
| 62 |
+
else:
|
| 63 |
+
raise HTTPException(status_code=403, detail="Bad Request")
|
| 64 |
+
|
| 65 |
+
# --- HELPER: RETRY DRIVEN SEND MESSAGE ---
|
| 66 |
+
def send_message_with_retry(chat_id, text, parse_mode=None):
|
| 67 |
+
"""Network failure se bachne ke liye automatic 3-times retry system"""
|
| 68 |
+
for attempt in range(3):
|
| 69 |
+
try:
|
| 70 |
+
return bot.send_message(chat_id, text, parse_mode=parse_mode)
|
| 71 |
+
except Exception as e:
|
| 72 |
+
print(f"β οΈ Message send attempt {attempt+1} fail hua: {e}")
|
| 73 |
+
if attempt < 2:
|
| 74 |
+
time.sleep(1)
|
| 75 |
+
else:
|
| 76 |
+
print("β Saare attempts fail ho gaye.")
|
| 77 |
+
|
| 78 |
+
# --- π― MASTER HANDLER (Unbreakable Routing) ---
|
| 79 |
+
@bot.message_handler(func=lambda message: True)
|
| 80 |
+
def handle_all_messages(message):
|
| 81 |
+
if not message.text:
|
| 82 |
+
return
|
| 83 |
+
|
| 84 |
+
raw_input = message.text.strip()
|
| 85 |
+
chat_id = message.chat.id
|
| 86 |
+
|
| 87 |
+
# β 1. Check if it is a command (/start or /help)
|
| 88 |
+
if raw_input.startswith('/start') or raw_input.startswith('/help'):
|
| 89 |
+
print(f"βοΈ [COMMAND] /start received for Chat ID: {chat_id}")
|
| 90 |
+
welcome_text = (
|
| 91 |
+
"π **Welcome to Search Bot!**\n\n"
|
| 92 |
+
"Mujhe koi bhi mobile number bhejiye, mai backend se data nikal kar dunga.\n"
|
| 93 |
+
"β‘ *Safe, Secure & Fast*"
|
| 94 |
+
)
|
| 95 |
+
send_message_with_retry(chat_id, welcome_text, parse_mode="Markdown")
|
| 96 |
+
print(f"β‘οΈ [COMMAND] /start reply successfully sent to Chat ID: {chat_id}")
|
| 97 |
+
return # Yahin se process khatam, aage mobile search par nahi jayega
|
| 98 |
+
|
| 99 |
+
# β 2. If it's NOT a command, process it as a Mobile Number Search
|
| 100 |
+
print(f"π₯ [SEARCH] Mobile search request: '{raw_input}' | Chat ID: {chat_id}")
|
| 101 |
+
|
| 102 |
+
if len(raw_input) > 20:
|
| 103 |
+
send_message_with_retry(chat_id, "β Input bohot lamba hai! Kripya sirf ek valid mobile number bhejein.")
|
| 104 |
+
return
|
| 105 |
+
|
| 106 |
+
cleaned_mobile = "".join(c for c in raw_input if c.isdigit())
|
| 107 |
+
|
| 108 |
+
if len(cleaned_mobile) == 12 and cleaned_mobile.startswith("91"):
|
| 109 |
+
mobile = cleaned_mobile[-10:]
|
| 110 |
+
elif len(cleaned_mobile) == 10:
|
| 111 |
+
mobile = cleaned_mobile
|
| 112 |
+
else:
|
| 113 |
+
mobile = cleaned_mobile
|
| 114 |
+
|
| 115 |
+
if not mobile or len(mobile) < 10 or len(mobile) > 11:
|
| 116 |
+
send_message_with_retry(chat_id, "β Kripya ek sahi 10-digit ka mobile number bhejein.")
|
| 117 |
+
return
|
| 118 |
|
| 119 |
+
try:
|
| 120 |
+
bot.send_chat_action(chat_id, 'typing')
|
| 121 |
+
except Exception:
|
| 122 |
+
pass
|
| 123 |
+
|
| 124 |
+
send_message_with_retry(chat_id, f"π Searching for `{mobile}`... Please wait...")
|
| 125 |
+
|
| 126 |
+
try:
|
| 127 |
+
# Backend API hit karna
|
| 128 |
+
response = httpx.get(f"{API_URL}?mobile={mobile}", timeout=15.0)
|
| 129 |
|
| 130 |
+
if response.status_code != 200:
|
| 131 |
+
send_message_with_retry(chat_id, "β οΈ Main API se sampark nahi ho paya. Kripya thodi der baad try karein.")
|
| 132 |
+
return
|
| 133 |
+
|
| 134 |
+
res_data = response.json()
|
| 135 |
|
| 136 |
+
if res_data.get("status") == "error":
|
| 137 |
+
send_message_with_retry(chat_id, f"β {res_data.get('message', 'Mobile number nahi mila.')}")
|
| 138 |
+
return
|
| 139 |
+
|
| 140 |
+
row_dict = res_data.get("data", {})
|
| 141 |
|
| 142 |
+
if not row_dict or not isinstance(row_dict, dict):
|
| 143 |
+
send_message_with_retry(chat_id, f"β Mobile number `{mobile}` ka koi valid record nahi mila.")
|
| 144 |
+
return
|
| 145 |
+
|
| 146 |
+
response_msg = f"β
**Record Found for {mobile}!**\n\n"
|
| 147 |
+
for key, value in row_dict.items():
|
| 148 |
+
display_value = value if value else "N/A"
|
| 149 |
+
response_msg += f"πΉ **{key.upper()}**: `{display_value}`\n"
|
| 150 |
+
|
| 151 |
+
send_message_with_retry(chat_id, response_msg, parse_mode="Markdown")
|
| 152 |
+
print(f"β‘οΈ Success: Data reply successfully sent for {mobile}")
|
| 153 |
|
| 154 |
+
except (httpx.ConnectTimeout, httpx.ReadTimeout):
|
| 155 |
+
send_message_with_retry(
|
| 156 |
+
chat_id,
|
| 157 |
+
"β³ **Main Data API sleep mode se jaag rahi hai.**\n\n"
|
| 158 |
+
"Kripya 5 seconds baad wapas se wahi number bhejein, data aa jayega!"
|
| 159 |
+
)
|
| 160 |
except Exception as e:
|
| 161 |
+
print(f"β Main logic crash prevented: {e}")
|
| 162 |
+
send_message_with_retry(chat_id, "β οΈ Kuch temporary dikkat aayi hai. Baad me try karein.")
|
| 163 |
|