Download src/botik/webhook_app.py from AnataBak/Botik: direct link, hf CLI and curl.
- Browser
- Download file 6 kB
-
https://huggingface.co/spaces/AnataBak/Botik/resolve/main/src/botik/webhook_app.py
- Command line
-
hf download hf://spaces/AnataBak/Botik/src/botik/webhook_app.py
-
curl -L -o webhook_app.py https://huggingface.co/spaces/AnataBak/Botik/resolve/main/src/botik/webhook_app.py
6 kB
| from __future__ import annotations | |
| import asyncio | |
| import logging | |
| from contextlib import asynccontextmanager | |
| import uvicorn | |
| from fastapi import FastAPI, Header, HTTPException, Request | |
| from telegram import Update | |
| from telegram.ext import Application | |
| from botik.config import Settings | |
| from botik.telegram_app import _cache_bot_info | |
| logger = logging.getLogger(__name__) | |
| WEBHOOK_PATH = "/telegram/webhook" | |
| def run_webhook_server(application: Application, settings: Settings) -> None: | |
| app = create_webhook_app(application=application, settings=settings) | |
| uvicorn.run(app, host="0.0.0.0", port=settings.port) | |
| def create_webhook_app(application: Application, settings: Settings) -> FastAPI: | |
| startup_state = { | |
| "ready": False, | |
| "task": None, | |
| "watchdog_task": None, | |
| } | |
| async def lifespan(_: FastAPI): | |
| startup_state["task"] = asyncio.create_task( | |
| _startup_until_ready(application, settings, startup_state) | |
| ) | |
| try: | |
| yield | |
| finally: | |
| task = startup_state["task"] | |
| if task is not None: | |
| task.cancel() | |
| try: | |
| await task | |
| except asyncio.CancelledError: | |
| pass | |
| watchdog_task = startup_state["watchdog_task"] | |
| if watchdog_task is not None: | |
| watchdog_task.cancel() | |
| try: | |
| await watchdog_task | |
| except asyncio.CancelledError: | |
| pass | |
| if startup_state["ready"]: | |
| await application.bot.delete_webhook() | |
| if application.updater is not None: | |
| await application.updater.stop() | |
| await application.stop() | |
| await application.shutdown() | |
| app = FastAPI(lifespan=lifespan) | |
| async def healthcheck() -> dict[str, str]: | |
| return {"status": "ok", "bot_ready": str(startup_state["ready"]).lower()} | |
| async def telegram_webhook( | |
| request: Request, | |
| x_telegram_bot_api_secret_token: str | None = Header(default=None), | |
| ) -> dict[str, bool]: | |
| if settings.run_mode != "webhook": | |
| raise HTTPException(status_code=404, detail="Webhook mode is disabled") | |
| expected_secret = settings.webhook_secret | |
| if expected_secret and x_telegram_bot_api_secret_token != expected_secret: | |
| raise HTTPException(status_code=401, detail="Invalid secret token") | |
| if not startup_state["ready"]: | |
| raise HTTPException(status_code=503, detail="Bot is still starting") | |
| payload = await request.json() | |
| update = Update.de_json(payload, application.bot) | |
| await application.process_update(update) | |
| return {"ok": True} | |
| return app | |
| async def _startup_until_ready( | |
| application: Application, | |
| settings: Settings, | |
| startup_state: dict[str, object], | |
| ) -> None: | |
| attempt = 0 | |
| while True: | |
| attempt += 1 | |
| try: | |
| await application.initialize() | |
| await application.start() | |
| await _cache_bot_info(application) | |
| if settings.run_mode == "webhook": | |
| webhook_url = _build_webhook_url(settings) | |
| await application.bot.set_webhook( | |
| url=webhook_url, | |
| secret_token=settings.webhook_secret, | |
| allowed_updates=Update.ALL_TYPES, | |
| ) | |
| logger.info("Webhook is set to %s", webhook_url) | |
| else: | |
| await application.bot.delete_webhook(drop_pending_updates=False) | |
| if application.updater is None: | |
| raise RuntimeError("Polling mode requires an updater") | |
| await application.updater.start_polling( | |
| poll_interval=1.0, | |
| timeout=5, | |
| bootstrap_retries=-1, | |
| allowed_updates=Update.ALL_TYPES, | |
| drop_pending_updates=False, | |
| error_callback=_polling_error_callback, | |
| ) | |
| startup_state["watchdog_task"] = asyncio.create_task( | |
| _polling_watchdog(application) | |
| ) | |
| logger.info("Polling mode started") | |
| startup_state["ready"] = True | |
| return | |
| except Exception as error: | |
| logger.warning("Startup attempt %s failed: %s", attempt, error) | |
| if application.updater is not None: | |
| try: | |
| await application.updater.stop() | |
| except Exception: | |
| pass | |
| try: | |
| if application.updater is not None: | |
| await application.updater.stop() | |
| except Exception: | |
| pass | |
| try: | |
| await application.stop() | |
| except Exception: | |
| pass | |
| try: | |
| await application.shutdown() | |
| except Exception: | |
| pass | |
| await asyncio.sleep(min(30, 5 * attempt)) | |
| def _build_webhook_url(settings: Settings) -> str: | |
| assert settings.app_base_url is not None | |
| return f"{settings.app_base_url.rstrip('/')}{WEBHOOK_PATH}" | |
| def _polling_error_callback(error: Exception) -> None: | |
| logger.warning("Polling error: %s", error) | |
| async def _polling_watchdog(application: Application) -> None: | |
| if application.updater is None: | |
| return | |
| while True: | |
| await asyncio.sleep(15) | |
| if application.updater.running: | |
| continue | |
| logger.warning("Polling watchdog: updater stopped, restarting polling") | |
| await application.updater.start_polling( | |
| poll_interval=1.0, | |
| timeout=5, | |
| bootstrap_retries=-1, | |
| allowed_updates=Update.ALL_TYPES, | |
| drop_pending_updates=False, | |
| error_callback=_polling_error_callback, | |
| ) | |