Spaces:
Sleeping
Sleeping
Update main.py
Browse files
main.py
CHANGED
|
@@ -395,6 +395,20 @@ async def background_worker(queue: asyncio.Queue, bot: Bot):
|
|
| 395 |
queue.task_done()
|
| 396 |
logger.info(f"Finished processing job for URL: {url}")
|
| 397 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 398 |
# FastAPI lifecycles
|
| 399 |
@asynccontextmanager
|
| 400 |
async def lifespan(app: FastAPI):
|
|
@@ -434,6 +448,9 @@ async def lifespan(app: FastAPI):
|
|
| 434 |
# Run the background worker task
|
| 435 |
worker_task = asyncio.create_task(background_worker(processing_queue, tg_app.bot))
|
| 436 |
|
|
|
|
|
|
|
|
|
|
| 437 |
# Sync any offline cached rows from SQLite to Sheets on startup
|
| 438 |
asyncio.create_task(sheets.sync_pending_rows())
|
| 439 |
|
|
@@ -444,8 +461,10 @@ async def lifespan(app: FastAPI):
|
|
| 444 |
if polling_mode:
|
| 445 |
await tg_app.updater.stop()
|
| 446 |
worker_task.cancel()
|
|
|
|
| 447 |
try:
|
| 448 |
await worker_task
|
|
|
|
| 449 |
except asyncio.CancelledError:
|
| 450 |
pass
|
| 451 |
|
|
|
|
| 395 |
queue.task_done()
|
| 396 |
logger.info(f"Finished processing job for URL: {url}")
|
| 397 |
|
| 398 |
+
async def keep_telegram_alive(bot: Bot):
|
| 399 |
+
"""
|
| 400 |
+
Pings the Telegram API every 60 seconds to prevent the HTTPX connection pool
|
| 401 |
+
from going stale, which causes httpx.ConnectError when using a Cloudflare proxy
|
| 402 |
+
that drops idle connections after ~100 seconds.
|
| 403 |
+
"""
|
| 404 |
+
logger.info("Starting Telegram keep-alive ping task...")
|
| 405 |
+
while True:
|
| 406 |
+
try:
|
| 407 |
+
await bot.get_me()
|
| 408 |
+
except Exception as e:
|
| 409 |
+
logger.warning(f"Telegram keep-alive ping failed (transient): {e}")
|
| 410 |
+
await asyncio.sleep(60)
|
| 411 |
+
|
| 412 |
# FastAPI lifecycles
|
| 413 |
@asynccontextmanager
|
| 414 |
async def lifespan(app: FastAPI):
|
|
|
|
| 448 |
# Run the background worker task
|
| 449 |
worker_task = asyncio.create_task(background_worker(processing_queue, tg_app.bot))
|
| 450 |
|
| 451 |
+
# Start the keep-alive task to prevent connection drops on the proxy
|
| 452 |
+
keep_alive_task = asyncio.create_task(keep_telegram_alive(tg_app.bot))
|
| 453 |
+
|
| 454 |
# Sync any offline cached rows from SQLite to Sheets on startup
|
| 455 |
asyncio.create_task(sheets.sync_pending_rows())
|
| 456 |
|
|
|
|
| 461 |
if polling_mode:
|
| 462 |
await tg_app.updater.stop()
|
| 463 |
worker_task.cancel()
|
| 464 |
+
keep_alive_task.cancel()
|
| 465 |
try:
|
| 466 |
await worker_task
|
| 467 |
+
await keep_alive_task
|
| 468 |
except asyncio.CancelledError:
|
| 469 |
pass
|
| 470 |
|