diff --git a/src/quickbot/api_route/telegram.py b/src/quickbot/api_route/telegram.py index 4758e2a..bee8440 100644 --- a/src/quickbot/api_route/telegram.py +++ b/src/quickbot/api_route/telegram.py @@ -1,10 +1,11 @@ -from fastapi import APIRouter, Request, Response, BackgroundTasks -from fastapi.datastructures import State +from aiogram.types import Update +from fastapi import APIRouter, Request, Response, Depends +from sqlmodel.ext.asyncio.session import AsyncSession +from typing import Annotated + +from ..db import get_db from ..main import QBotApp - -from ..db import async_session -from aiogram.types import Update from logging import getLogger @@ -14,13 +15,15 @@ router = APIRouter() @router.post("/webhook") async def telegram_webhook( - # db_session: Annotated[AsyncSession, Depends(get_db)], + db_session: Annotated[AsyncSession, Depends(get_db)], request: Request, - background_tasks: BackgroundTasks, ): logger.debug("Webhook request %s", await request.json()) app: QBotApp = request.app + if app.webhook_handler: + return await app.webhook_handler(app=app, request=request) + request_token = request.headers.get("X-Telegram-Bot-Api-Secret-Token") if request_token != app.config.TELEGRAM_WEBHOOK_AUTH_KEY: logger.warning("Unauthorized request %s", request) @@ -31,25 +34,31 @@ async def telegram_webhook( logger.error("Invalid request", exc_info=True) return Response(status_code=400) - background_tasks.add_task( - feed_bot_update, - app=app, - update=update, - app_state=request.state, - ) - return Response(status_code=200) - - -async def feed_bot_update( - app: QBotApp, - update: Update, - app_state: State, -): - async with async_session() as db_session: - await app.dp.feed_webhook_update( + try: + app.dp.feed_webhook_update( bot=app.bot, update=update, db_session=db_session, app=app, - app_state=app_state, + app_state=request.state, ) + except Exception: + logger.error("Error processing update", exc_info=True) + return Response(status_code=500) + + return Response(status_code=200) + + +# async def feed_bot_update( +# app: QBotApp, +# update: Update, +# app_state: State, +# ): +# async with async_session() as db_session: +# await app.dp.feed_webhook_update( +# bot=app.bot, +# update=update, +# db_session=db_session, +# app=app, +# app_state=app_state, +# ) diff --git a/src/quickbot/main.py b/src/quickbot/main.py index 4561e91..41e39cc 100644 --- a/src/quickbot/main.py +++ b/src/quickbot/main.py @@ -7,7 +7,7 @@ from aiogram.client.default import DefaultBotProperties from aiogram.types import Message, BotCommand as AiogramBotCommand from aiogram.utils.callback_answer import CallbackAnswerMiddleware from aiogram.utils.i18n import I18n -from fastapi import FastAPI +from fastapi import FastAPI, Request from fastapi.applications import Lifespan, AppType from fastapi.datastructures import State from logging import getLogger @@ -78,6 +78,7 @@ class QBotApp(Generic[UserType, ConfigType], FastAPI): lifespan: Lifespan[AppType] | None = None, lifespan_bot_init: bool = True, lifespan_set_webhook: bool = True, + webhook_handler: Callable[["QBotApp", Request], Any] = None, allowed_updates: list[str] | None = None, **kwargs, ): @@ -126,6 +127,7 @@ class QBotApp(Generic[UserType, ConfigType], FastAPI): self.dp = dp self.start_handler = bot_start + self.webhook_handler = webhook_handler self.bot_commands = dict[str, BotCommand]() self.lifespan_bot_init = lifespan_bot_init