Skip to content

Instantly share code, notes, and snippets.

@MasterGroosha
Last active January 8, 2023 07:06
Show Gist options
  • Save MasterGroosha/9d7661e83e5e2b64072afae47ae9c03e to your computer and use it in GitHub Desktop.
Save MasterGroosha/9d7661e83e5e2b64072afae47ae9c03e to your computer and use it in GitHub Desktop.
Set only needed updates (aiogram 2.20+)
import asyncio
import logging
from aiogram import Bot, Dispatcher
from aiogram.types import BotCommand
from bot.config_reader import load_config
from bot.middlewares.config import ConfigMiddleware
from bot.handlers.main_group_events import register_group_events
from bot.handlers.callbacks_reports import register_callbacks_reports
logger = logging.getLogger(__name__)
async def set_bot_commands(bot: Bot):
commands = [
BotCommand(command="help", description="help"),
]
await bot.set_my_commands(commands)
def get_updates_in_use(dp: Dispatcher):
available_updates = (
"callback_query_handlers", "channel_post_handlers", "chat_member_handlers",
"chosen_inline_result_handlers", "edited_channel_post_handlers", "edited_message_handlers",
"inline_query_handlers", "message_handlers", "my_chat_member_handlers", "poll_answer_handlers",
"poll_handlers", "pre_checkout_query_handlers", "shipping_query_handlers", "chat_join_request_handlers"
)
return [item.replace("_handlers", "") for item in available_updates if len(dp.__getattribute__(item).handlers) > 0]
async def main():
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s - %(levelname)s - %(name)s - %(message)s",
)
# Reading config from env vars
config = load_config()
bot = Bot(token=config.token)
dp = Dispatcher(bot)
# Register handlers
register_group_events(dp, main_group_id=config.group.main)
register_callbacks_reports(dp)
# Register middlewares
dp.middleware.setup(ConfigMiddleware(config))
# Register /-commands in UI
await set_bot_commands(bot)
logger.info("Starting bot")
# Start polling
# await dp.skip_updates() # skip pending updates (optional)
try:
await dp.start_polling(allowed_updates=get_updates_in_use(dp))
finally:
await bot.close()
if __name__ == '__main__':
asyncio.run(main())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment