refactoring
This commit is contained in:
31
lifespan.py
31
lifespan.py
@@ -1,10 +1,14 @@
|
||||
from aiogram.types import BotCommand
|
||||
from contextlib import asynccontextmanager
|
||||
from .main import QBotApp
|
||||
from logging import getLogger
|
||||
|
||||
logger = getLogger(__name__)
|
||||
|
||||
@asynccontextmanager
|
||||
async def default_lifespan(app: QBotApp):
|
||||
|
||||
app.logger.debug("starting qbot app")
|
||||
logger.debug("starting qbot app")
|
||||
|
||||
if app.config.USE_NGROK:
|
||||
try:
|
||||
@@ -12,18 +16,35 @@ async def default_lifespan(app: QBotApp):
|
||||
from pyngrok.conf import PyngrokConfig
|
||||
|
||||
except ImportError:
|
||||
app.logger.error("pyngrok is not installed")
|
||||
logger.error("pyngrok is not installed")
|
||||
raise
|
||||
|
||||
tunnel = ngrok.connect(app.config.API_PORT, pyngrok_config = PyngrokConfig(auth_token = app.config.NGROK_AUTH_TOKEN))
|
||||
app.config.NGROK_URL = tunnel.public_url
|
||||
|
||||
commands_captions = dict[str, list[tuple[str, str]]]()
|
||||
|
||||
for command_name, command in app.bot_commands.items():
|
||||
if isinstance(command.caption, str):
|
||||
if "default" not in commands_captions:
|
||||
commands_captions["default"] = []
|
||||
commands_captions["default"].append((command_name, command.caption))
|
||||
for locale, description in command.caption.items():
|
||||
if locale not in commands_captions:
|
||||
commands_captions[locale] = []
|
||||
commands_captions[locale].append((command_name, description))
|
||||
|
||||
for locale, commands in commands_captions.items():
|
||||
await app.bot.set_my_commands([BotCommand(command = command[0], description=command[1]) for command in commands],
|
||||
language_code = None if locale == "default" else locale)
|
||||
|
||||
|
||||
await app.bot.set_webhook(url = f"{app.config.API_URL}/api/telegram/webhook",
|
||||
drop_pending_updates = True,
|
||||
allowed_updates = ['message', 'callback_query', 'pre_checkout_query'],
|
||||
secret_token = app.bot_auth_token)
|
||||
|
||||
app.logger.info("qbot app started")
|
||||
logger.info("qbot app started")
|
||||
|
||||
if app.lifespan:
|
||||
async with app.lifespan(app):
|
||||
@@ -31,10 +52,10 @@ async def default_lifespan(app: QBotApp):
|
||||
else:
|
||||
yield
|
||||
|
||||
app.logger.info("stopping qbot app")
|
||||
logger.info("stopping qbot app")
|
||||
|
||||
await app.bot.delete_webhook()
|
||||
if app.config.USE_NGROK:
|
||||
ngrok.disconnect(app.config.NGROK_URL)
|
||||
ngrok.kill()
|
||||
app.logger.info("qbot app stopped")
|
||||
logger.info("qbot app stopped")
|
||||
Reference in New Issue
Block a user