Hfzune commited on
Commit
c943a09
·
verified ·
1 Parent(s): c7985ee

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +15 -15
app.py CHANGED
@@ -299,23 +299,25 @@ async def health_handler(request: Request):
299
  return JSONResponse({"status": "ok"})
300
 
301
  # =========================================================
302
- # Initialize Telegram on a dedicated loop and set webhook
303
  # =========================================================
304
- def init_telegram_blocking():
305
- async def _init():
306
- init_db()
307
- await telegram_app.initialize()
308
- await telegram_app.start()
309
- webhook_url = f"{WEBHOOK_URL}/webhook/{TELEGRAM_BOT_TOKEN}"
310
- await telegram_app.bot.set_webhook(url=webhook_url, drop_pending_updates=True)
311
- logger.info(f"✅ Webhook set: {webhook_url}")
312
- asyncio.run(_init())
 
 
313
 
314
  # =========================================================
315
  # Main
316
  # =========================================================
317
  if __name__ == "__main__":
318
- # 1. Launch Gradio: no SSR (avoids Node proxy on 7860), no threading lock (so we can inject routes)
319
  demo.launch(
320
  server_name="0.0.0.0",
321
  server_port=7860,
@@ -334,8 +336,6 @@ if __name__ == "__main__":
334
  )
335
  live_app.build_middleware_stack()
336
 
337
- # 3. Initialize Telegram + set webhook (safe: no polling thread)
338
- init_telegram_blocking()
339
-
340
- # 4. Keep process alive
341
  demo.block_thread()
 
299
  return JSONResponse({"status": "ok"})
300
 
301
  # =========================================================
302
+ # Async startup handler — runs on FastAPI's own event loop
303
  # =========================================================
304
+ async def on_startup():
305
+ """Initialize Telegram on the same loop that Uvicorn uses."""
306
+ init_db()
307
+ await telegram_app.initialize()
308
+ await telegram_app.start()
309
+ webhook_url = f"{WEBHOOK_URL}/webhook/{TELEGRAM_BOT_TOKEN}"
310
+ await telegram_app.bot.set_webhook(url=webhook_url, drop_pending_updates=True)
311
+ logger.info(f"✅ Webhook set: {webhook_url}")
312
+
313
+ # Register the startup handler on the underlying FastAPI app
314
+ demo.app.add_event_handler("startup", on_startup)
315
 
316
  # =========================================================
317
  # Main
318
  # =========================================================
319
  if __name__ == "__main__":
320
+ # 1. Launch Gradio: no SSR (avoids Node proxy on 7860), no threading lock
321
  demo.launch(
322
  server_name="0.0.0.0",
323
  server_port=7860,
 
336
  )
337
  live_app.build_middleware_stack()
338
 
339
+ # 3. Keep process alive — the startup handler (on_startup) will fire
340
+ # automatically on Uvicorn's event loop and set the webhook.
 
 
341
  demo.block_thread()