Skip to content

Commit

Permalink
feat: add all imports and configurations to bot file
Browse files Browse the repository at this point in the history
  • Loading branch information
TimNekk committed Aug 6, 2022
1 parent 951572d commit 7fcae0c
Showing 1 changed file with 30 additions and 36 deletions.
66 changes: 30 additions & 36 deletions bot.py
Original file line number Diff line number Diff line change
@@ -1,64 +1,58 @@
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 loguru import logger

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)
from tgbot.filters import register_filters
from tgbot.handlers import register_handlers
from tgbot.middlewares import register_middlewares
from tgbot.misc import logging
from tgbot.models import db
from tgbot.models.user_tg import UserTG
from tgbot.services.broadcasting import send_to_admins
from tgbot.services.setting_commands import set_bot_command


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()
logging.setup(config.misc.log_file_name)
logger.info("Starting bot")

if config.tg_bot.use_redis:
storage = RedisStorage2(host=config.redis.host, port=config.redis.port, password=config.redis.password)
else:
storage = MemoryStorage()

bot = Bot(token=config.tg_bot.token, parse_mode='HTML')
bot['config'] = config
dp = Dispatcher(bot, storage=storage)

bot['config'] = config
await db.on_startup(config.db.uri)
UserTG.bot = bot

register_middlewares(dp, config)
register_filters(dp)
register_handlers(dp)

register_all_middlewares(dp, config)
register_all_filters(dp)
register_all_handlers(dp)
await set_bot_command(bot, config)
await send_to_admins(bot, "Бот запущен")

# start
try:
await dp.start_polling()
finally:
await dp.storage.close()
await dp.storage.wait_closed()
await bot.session.close()
await (await bot.get_session()).close()
await db.on_shutdown()


if __name__ == '__main__':
try:
asyncio.run(main())
except (KeyboardInterrupt, SystemExit):
logger.error("Bot stopped!")
logger.info("Bot stopped!")
raise SystemExit(0)

0 comments on commit 7fcae0c

Please sign in to comment.