This repository has been archived by the owner on Jul 18, 2023. It is now read-only.
generated from rin-gil/aiogram-v2-template
-
Notifications
You must be signed in to change notification settings - Fork 4
/
bot.py
67 lines (54 loc) · 2.01 KB
/
bot.py
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
"""Launches the bot"""
from asyncio import run
from aiogram import Bot, Dispatcher
from aiogram.contrib.fsm_storage.memory import MemoryStorage
from tgbot.config import load_config, Config
from tgbot.filters.admin import AdminFilter
from tgbot.handlers.admin import register_admin_handlers
from tgbot.handlers.commands import register_commands_handlers
from tgbot.handlers.error import register_errors_handlers
from tgbot.handlers.messages import register_messages_handlers
from tgbot.middlewares.localization import i18n
from tgbot.misc.commands import set_default_commands
from tgbot.misc.logger import logger
from tgbot.services.database import database
def register_all_middlewares(dp: Dispatcher) -> None:
"""Registers middlewares"""
dp.middleware.setup(i18n)
def register_all_filters(dp: Dispatcher) -> None:
"""Registers filters"""
dp.filters_factory.bind(AdminFilter)
def register_all_handlers(dp: Dispatcher) -> None:
"""Registers handlers"""
register_admin_handlers(dp)
register_commands_handlers(dp)
register_messages_handlers(dp)
register_errors_handlers(dp)
async def main() -> None:
"""Launches the bot"""
config: Config = load_config(path=".env")
bot: Bot = Bot(token=config.tg_bot.token, parse_mode="HTML")
dp: Dispatcher = Dispatcher(bot, storage=MemoryStorage())
bot["config"] = config
register_all_middlewares(dp)
register_all_filters(dp)
register_all_handlers(dp)
try: # On starting bot
await database.init()
await set_default_commands(dp)
await dp.skip_updates()
await dp.start_polling()
finally: # On stopping bot
await dp.storage.close()
await dp.storage.wait_closed()
session = await bot.get_session()
await session.close()
if __name__ == "__main__":
logger.info("Starting bot")
try:
run(main())
except (KeyboardInterrupt, SystemExit):
pass
except Exception as ex:
logger.critical("Unknown error: %s", repr(ex))
logger.info("Bot stopped!")