refactoring

This commit is contained in:
Alexander Kalinovsky
2025-01-09 13:11:10 +01:00
parent 7793a0cb77
commit 3898a333fa
29 changed files with 1065 additions and 381 deletions

52
main.py
View File

@@ -1,5 +1,11 @@
from functools import wraps
from typing import Annotated, Callable, Any, Union, override
from typing_extensions import Doc
from aiogram import Bot, Dispatcher
from aiogram.filters import CommandStart
from aiogram.client.default import DefaultBotProperties
from aiogram.types import Message, BotCommand
from aiogram.utils.keyboard import InlineKeyboardBuilder
from aiogram.utils.callback_answer import CallbackAnswerMiddleware
from aiogram.utils.i18n import I18n
from fastapi import FastAPI
@@ -12,19 +18,25 @@ from .fsm.db_storage import DbStorage
from .middleware.telegram import AuthMiddleware, I18nMiddleware, ResetStateMiddleware
from .model.user import UserBase
from .model.entity_metadata import EntityMetadata
from .bot.handlers.user_handlers import Command, CommandCallbackContext
class QBotApp(FastAPI):
bot: Bot
dp: Dispatcher
config: Config
logger = getLogger(__name__)
"""
Main class for the QBot application
"""
def __init__[UserType: UserBase](self,
user_class: type[UserType] | None = None,
user_class: Annotated[type[UserType], Doc(
"User class that will be used in the application"
)] | None = None,
config: Config | None = None,
bot_start: Annotated[Callable[[Annotated[Callable[[Message, Any], None], Doc(
"Default handler for the start command"
)], Message, Any], None], Doc(
"Handler for the start command"
)] | None = None,
bot_commands: list[Command] | None = None,
lifespan: Lifespan[AppType] | None = None,
*args,
**kwargs):
@@ -63,6 +75,9 @@ class QBotApp(FastAPI):
self.bot_auth_token = token_hex(128)
self.start_handler = bot_start
self.bot_commands = {c.name: c for c in bot_commands or []}
from .lifespan import default_lifespan
super().__init__(lifespan = default_lifespan, *args, **kwargs)
@@ -70,3 +85,26 @@ class QBotApp(FastAPI):
from .api_route.telegram import router as telegram_router
self.include_router(telegram_router, prefix = "/api/telegram", tags = ["telegram"])
@override
def bot_command(self, command: Command): ...
@override
def bot_command(self, command: str, caption: str | dict[str, str] | None = None): ...
def bot_command(self, command: str | Command, caption: str | dict[str, str] | None = None):
"""
Decorator for registering bot commands
"""
def decorator(func: Callable[[CommandCallbackContext], None]):
if isinstance(command, str):
command = Command(name = command, handler = func, caption = caption)
self.bot_commands[command.name] = command
wraps(func)
def wrapper(*args, **kwargs):
return func(*args, **kwargs)
return wrapper
return decorator