morington

Untitled

Feb 19th, 2024 (edited)
680
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 4.30 KB | None | 0 0
  1. from contextlib import asynccontextmanager
  2. from datetime import datetime
  3.  
  4. import alembic
  5. import structlog
  6. from aiogram import Bot, Dispatcher
  7. from aiogram.client.session.aiohttp import AiohttpSession
  8. from aiogram.enums import ParseMode
  9. from aiogram.fsm.storage.redis import RedisStorage, DefaultKeyBuilder
  10. from aiogram.webhook.aiohttp_server import setup_application, SimpleRequestHandler
  11. from aiohttp import web
  12. from aiohttp.web_request import Request
  13. from aiohttp.web_response import Response
  14. from alembic.config import Config
  15. from dynaconf import LazySettings
  16. from faststream import FastStream
  17. from faststream.rabbit import RabbitBroker
  18.  
  19. from WebApp import handlers
  20. from WebApp.middlewares.database import SessionMiddleware
  21. from WebApp.middlewares.user import UserDetectMiddleware
  22. from config.configuration import Configuration
  23. from database.build import PostgresBuild
  24.  
  25.  
  26. logger: structlog.BoundLogger = structlog.getLogger(__name__)
  27. broker = RabbitBroker("amqp://morington:qwer@localhost:5672/")
  28.  
  29.  
  30. class WebhookConstructor:
  31.     def __init__(self, domain: str):
  32.         self.URL = domain
  33.         self.WEBHOOK_PATH = "/bot{bot_token}"
  34.  
  35.     def webhook_url(self, token: str) -> str:
  36.         return f"{self.URL}{self.WEBHOOK_PATH.format(bot_token=token)}"
  37.  
  38.  
  39. async def ping(request: Request) -> Response:
  40.     """
  41.    Checking the application's functionality `/ping`.
  42.  
  43.    :param request: Request object
  44.    :return: { status": "OK", "datetime": "22.11.2023 17:46:00" }
  45.    """
  46.     now = datetime.now()
  47.     data = {"status": "OK", "datetime": now.strftime("%d.%m.%Y %H:%M:%S")}
  48.     logger.debug("Application ping", data=data)
  49.     return web.json_response(data)
  50.  
  51.  
  52. @broker.subscriber("routing_key")
  53. async def handle(msg):
  54.     print(msg, type(msg))
  55.  
  56.  
  57. class Initializing:
  58.     def __init__(self, configuration: LazySettings):
  59.         self.configuration = configuration
  60.  
  61.         self.postgres = PostgresBuild(url=self.configuration.postgres_url)
  62.  
  63.         self.webhook = WebhookConstructor(domain=self.configuration.web.domain)
  64.  
  65.         redis_storage = RedisStorage.from_url(
  66.             url=self.configuration.redis_url,
  67.             key_builder=DefaultKeyBuilder(with_destiny=True, with_bot_id=True),
  68.         )
  69.  
  70.         self.session = AiohttpSession()
  71.         self.app = web.Application()
  72.  
  73.         self.bot_settings = {
  74.             "session": self.session,
  75.             "parse_mode": ParseMode.HTML,
  76.             "disable_web_page_preview": True,
  77.         }
  78.         bot = Bot(token=self.configuration.telegrambot.key, **self.bot_settings)
  79.  
  80.         main_dp = Dispatcher(storage=redis_storage)
  81.         main_dp.startup.register(self.on_startup)
  82.  
  83.         SimpleRequestHandler(dispatcher=main_dp, bot=bot).register(self.app, path=self.webhook.WEBHOOK_PATH)
  84.  
  85.         setup_application(self.app, main_dp, bot=bot)
  86.  
  87.         self.app.router.add_get("/ping", ping)
  88.         self.app.on_cleanup.append(self.shutdown_server)
  89.  
  90.     async def on_startup(self, dispatcher: Dispatcher, bot: Bot):
  91.         _url: str = self.webhook.webhook_url(token=self.configuration.telegrambot.key)
  92.  
  93.         await bot.delete_webhook(drop_pending_updates=True)
  94.         await bot.set_webhook(_url)
  95.         logger.debug(f"Installed WebHook at: {_url[:-10] + '*' * 10}")
  96.  
  97.         await self.dispatcher_installer(dispatcher)
  98.  
  99.         dispatcher.include_router(handlers.router)
  100.  
  101.         await broker.start()
  102.  
  103.     async def dispatcher_installer(self, dispatcher: Dispatcher):
  104.         dispatcher.update.middleware(SessionMiddleware(session=self.postgres.session()))
  105.         dispatcher.update.middleware(UserDetectMiddleware())
  106.  
  107.     async def shutdown_server(self, app):
  108.         await self.postgres.completion()
  109.         logger.debug("Application stopped")
  110.  
  111.  
  112. if __name__ == "__main__":
  113.     logger.debug("Launching the application")
  114.  
  115.     # configuration
  116.     cfg = Configuration()
  117.     config = cfg.all_configuration()
  118.  
  119.     #  Alembic upgrade
  120.     alembic_config = Config(file_="alembic.ini", attributes={"configure_logger": False})
  121.     alembic.command.upgrade(alembic_config, "head")
  122.     logger.debug("Alembic updates the database")
  123.  
  124.     #  TelegramBot
  125.     logger.debug("Telegram bot initialization")
  126.     telegrambot = Initializing(configuration=config)
  127.  
  128.     web.run_app(telegrambot.app, host=config.web.host, port=config.web.port)
  129.  
Advertisement
Add Comment
Please, Sign In to add comment