File size: 6,000 Bytes
a571bd0 ef6b17d a571bd0 c737d78 a571bd0 3a6c05b 217c89a 3a6c05b a571bd0 3a6c05b ceca536 3a6c05b a571bd0 3a6c05b 217c89a 3a6c05b 217c89a 3a6c05b a571bd0 3a6c05b a571bd0 ceca536 a571bd0 3a6c05b a571bd0 3a6c05b ef6b17d 3a6c05b ef6b17d 3a6c05b ef6b17d c737d78 ceca536 217c89a ceca536 3a6c05b ef6b17d ceca536 217c89a 3a6c05b ef6b17d 3a6c05b ceca536 217c89a | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 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 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 | 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,
}
@asynccontextmanager
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)
@app.get("/")
async def healthcheck() -> dict[str, str]:
return {"status": "ok", "bot_ready": str(startup_state["ready"]).lower()}
@app.post(WEBHOOK_PATH)
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,
)
|