You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在多文件架构下传递aiogram的dp对象至其他模块

在aiogram中拆分多文件代码时传递Dispatcher(dp)对象的方案

单文件场景下,先初始化dp = Dispatcher(bot)再用@dp.xxx_handler装饰器绑定处理器完全没问题,但拆分到多文件时,确实需要特殊处理dp的传递,以下是几种实用方案:

方案一:在主模块初始化dp,其他模块直接导入

创建主文件初始化dp后,处理器模块直接导入这个已初始化的dp对象来使用装饰器。需要注意避免循环导入,建议主文件最后导入处理器模块,或者调整导入顺序。

示例代码:
主文件main.py:

from aiogram import Bot, Dispatcher
import asyncio

BOT_TOKEN = "你的机器人Token"

# 先初始化bot和dp
bot = Bot(token=BOT_TOKEN)
dp = Dispatcher(bot)

# 最后导入处理器模块,避免循环导入
from handlers import start_handler

async def main():
    await dp.start_polling(bot)

if __name__ == "__main__":
    asyncio.run(main())

处理器文件handlers/start_handler.py:

from aiogram import types
from main import dp

@dp.message_handler(commands=['start', 'help'])
async def send_welcome(message: types.Message):
    await message.reply("你好!欢迎使用机器人")

方案二:用工厂函数注册处理器(你提到的函数构造器方式)

在处理器模块中定义一个接收dp参数的函数,函数内部完成处理器的装饰和绑定,主文件初始化dp后调用该函数传入dp即可。这种方式彻底避免循环导入,适合大型项目。

示例代码:
处理器文件handlers/start_handler.py:

from aiogram import types

def register_handlers(dp):
    @dp.message_handler(commands=['start', 'help'])
    async def send_welcome(message: types.Message):
        await message.reply("你好!欢迎使用机器人")

主文件main.py:

from aiogram import Bot, Dispatcher
import asyncio
from handlers.start_handler import register_handlers

BOT_TOKEN = "你的机器人Token"

bot = Bot(token=BOT_TOKEN)
dp = Dispatcher(bot)

# 传入dp注册处理器
register_handlers(dp)

async def main():
    await dp.start_polling(bot)

if __name__ == "__main__":
    asyncio.run(main())

方案三:使用Router(aiogram 3.x官方推荐)

如果使用aiogram 3.x版本,官方推荐用Router来拆分处理器,每个模块创建独立的Router,最后在主文件中将所有Router整合到Dispatcher中,完全不需要手动传递dp。

示例代码:
处理器文件handlers/start_handler.py:

from aiogram import Router, types

router = Router()

@router.message_handler(commands=['start', 'help'])
async def send_welcome(message: types.Message):
    await message.reply("你好!欢迎使用机器人")

主文件main.py:

from aiogram import Bot, Dispatcher
import asyncio
from handlers.start_handler import router

BOT_TOKEN = "你的机器人Token"

bot = Bot(token=BOT_TOKEN)
dp = Dispatcher()

# 将子Router添加到主Dispatcher
dp.include_router(router)

async def main():
    await dp.start_polling(bot)

if __name__ == "__main__":
    asyncio.run(main())

内容的提问来源于stack exchange,提问作者Igor

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.21 22:23:32