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

在aiogram模块化开发中,如何向handlers.py传入bot实例?

解决aiogram模块化机器人中显示“正在输入”状态的问题

在模块化的aiogram项目里,handlers.py中无需单独导入bot实例,直接利用message对象自带的bot属性即可实现需求,以下是两种可行方案:

方案一:使用ChatActionSender上下文管理器(推荐)

直接将官方示例中的bot参数替换为message.bot,无需额外导入:

from aiogram.utils.chat_action import ChatActionSender

async def your_handler(message: types.Message):
    # 模拟耗时操作
    async with ChatActionSender.typing(bot=message.bot, chat_id=message.chat.id):
        # 执行你的计算或业务逻辑
        result = "处理完成的结果"
        await message.answer(result)

方案二:直接调用send_chat_action方法

如果不需要上下文管理器的自动结束机制,也可以直接调用bot的send_chat_action方法:

async def your_handler(message: types.Message):
    await message.bot.send_chat_action(message.chat.id, "typing")
    # 执行耗时操作
    result = "处理完成的结果"
    await message.answer(result)

关键说明

  • 模块化项目中避免直接导入main.py中的bot实例,否则容易引发循环导入错误(ImportError),而message.bot是aiogram自动绑定到消息对象的bot实例,安全且便捷。
  • 除了typing,还可以传递其他动作类型,比如upload_photo、record_video等,对应不同的输入状态提示。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.20 16:32:05