forked from Tishka17/tgbot_template
-
Notifications
You must be signed in to change notification settings - Fork 128
/
bot.py
64 lines (46 loc) · 1.63 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
import asyncio
import logging
from aiogram import Bot, Dispatcher
from aiogram.contrib.fsm_storage.memory import MemoryStorage
from aiogram.contrib.fsm_storage.redis import RedisStorage2
from tgbot.config import load_config
from tgbot.filters.admin import AdminFilter
from tgbot.handlers.admin import register_admin
from tgbot.handlers.echo import register_echo
from tgbot.handlers.user import register_user
from tgbot.middlewares.environment import EnvironmentMiddleware
logger = logging.getLogger(__name__)
def register_all_middlewares(dp, config):
dp.setup_middleware(EnvironmentMiddleware(config=config))
def register_all_filters(dp):
dp.filters_factory.bind(AdminFilter)
def register_all_handlers(dp):
register_admin(dp)
register_user(dp)
register_echo(dp)
async def main():
logging.basicConfig(
level=logging.INFO,
format=u'%(filename)s:%(lineno)d #%(levelname)-8s [%(asctime)s] - %(name)s - %(message)s',
)
logger.info("Starting bot")
config = load_config(".env")
storage = RedisStorage2() if config.tg_bot.use_redis else MemoryStorage()
bot = Bot(token=config.tg_bot.token, parse_mode='HTML')
dp = Dispatcher(bot, storage=storage)
bot['config'] = config
register_all_middlewares(dp, config)
register_all_filters(dp)
register_all_handlers(dp)
# start
try:
await dp.start_polling()
finally:
await dp.storage.close()
await dp.storage.wait_closed()
await bot.session.close()
if __name__ == '__main__':
try:
asyncio.run(main())
except (KeyboardInterrupt, SystemExit):
logger.error("Bot stopped!")