pythonrouteraiogram

How to connect routers in Aiogram


I have directory structure:

├── src
│   ├── admin.py
│   ├── main.py
│   ├── handlers.py

I wanted to add router inside admin.py and handlers.py but I have a problem. I initialized router inside handlers.py and admin.py

Then have this code inside main.py

import asyncio
import logging

from aiogram import Bot, Dispatcher
from aiogram.enums.parse_mode import ParseMode
from aiogram.fsm.storage.memory import MemoryStorage

import config
from admin import router1
from handlers import router2


async def main():
    bot = Bot(token=config.BOT_TOKEN, parse_mode=ParseMode.HTML)
    dp = Dispatcher(storage=MemoryStorage())
    dp.include_routers(router1, router2)
    await bot.delete_webhook(drop_pending_updates=True)
    await dp.start_polling(bot, allowed_updates=dp.resolve_used_update_types())


if __name__ == "__main__":
    logging.basicConfig(level=logging.INFO)
    asyncio.run(main())

But when I run code only router inside handlers work.

My admin.py code:

from aiogram import F, Router, Bot
from aiogram.types import Message, CallbackQuery
from aiogram.filters import Command
import handlers

import kb
import config
import text

global admin_flag
admin_flag = False
global user_id

router1 = Router()
router1.include_router1(handlers.router1)


@router1.message(Command("admin"))
async def admin_handler(msg: Message):
    global user_id
    user_id = int(msg.from_user.id)
    if user_id in config.admins:
        await msg.answer(text.greet_admin, reply_markup=kb.admin_main_menu_kb)

and handlers.py code:

from aiogram import Router, F, Bot
from aiogram.types import Message, CallbackQuery
from aiogram.filters import Command

import kb
import config
import text

global user, flag
flag = False

router2 = Router()


@router2.message(Command("start"))
async def start_handler(msg: Message):
    user_id = int(msg.from_user.id)
    if user_id not in config.admins:
        await msg.answer(text.greet, reply_markup=kb.main_menu_kb)

Solution

  • This is incorrect: router1.include_router1(handlers.router1)

    It should be router.include_router()

    Like this: router1.include_router(router2)

    IMPORTANT NOTE:

    Note that you should'nt register any handler or router after you start receiveng of the incoming events. All handlers in routers tree should be registered when you construct the application.