-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmain.py
More file actions
74 lines (63 loc) · 2.39 KB
/
Copy pathmain.py
File metadata and controls
74 lines (63 loc) · 2.39 KB
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
import asyncio
import logging
import structlog
from aiogram import Bot
from aiogram.exceptions import TelegramNetworkError
from aiogram.types import BotCommand
from app.bot import get_bot, get_dispatcher
from app.config import settings
from app.core.logging import configure_logging
from app.database.base import engine
from app.services.notifications import notify_admins_bot_started
async def set_commands(bot: Bot) -> None:
logger = structlog.get_logger(__name__)
commands = [
BotCommand(command="start", description="Главное меню"),
BotCommand(command="help", description="Помощь"),
BotCommand(command="cancel", description="Отменить текущее действие"),
]
for attempt in range(1, 4):
try:
await bot.set_my_commands(commands)
return
except TelegramNetworkError as exc:
if attempt == 3:
logger.warning(
"set_commands_skipped_network_error",
attempt=attempt,
error=str(exc),
)
return
await asyncio.sleep(attempt * 2)
async def on_shutdown(bot: Bot) -> None:
"""Graceful shutdown hook called by Dispatcher on SIGTERM/SIGINT."""
logger = structlog.get_logger(__name__)
logger.info("bot_shutdown_started")
try:
await bot.session.close()
except Exception as exc:
logger.warning("bot_session_close_failed", error=str(exc))
try:
await engine.dispose()
except Exception as exc:
logger.warning("engine_dispose_failed", error=str(exc))
logger.info("bot_shutdown_complete")
async def main() -> None:
configure_logging(log_level=settings.LOG_LEVEL)
logger = structlog.get_logger(__name__)
bot = get_bot()
dp = get_dispatcher()
dp.shutdown.register(on_shutdown)
try:
await set_commands(bot)
await notify_admins_bot_started(bot, settings.ADMIN_IDS, startup_source="main.py/polling")
logger.info("bot_starting", admin_ids=len(settings.ADMIN_IDS))
await dp.start_polling(bot, allowed_updates=dp.resolve_used_update_types())
except Exception as exc:
logger.exception("bot_polling_crashed", error=str(exc))
raise
if __name__ == "__main__":
try:
asyncio.run(main())
except KeyboardInterrupt:
logging.getLogger(__name__).info("bot_stopped")