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

在aiogram中注册多个消息处理器的方式是否合规?

多消息处理器注册方式可行性验证

问题描述

我尝试创建多个不同的消息处理器,请问以下这种注册方式是否可行?

import asyncio

from aiogram import Bot, Dispatcher, types
from settings import BOT_TOKEN


async def start_handler(event: types.Message):
    await event.answer(
        f"Hello, {event.from_user.get_mention(as_html=True)} 👋!",
        parse_mode=types.ParseMode.HTML,
    )

async def echo_answer(event: types.Message):
    await event.answer(event.text, parse_mode=types.ParseMode.HTML
    )


async def main():
    bot = Bot(token=BOT_TOKEN)
    try:
        disp = Dispatcher(bot=bot)
        disp.register_message_handler(start_handler, commands={"start", "restart"})
        disp.register_message_handler(echo_answer, lambda msg: msg.text)
        await disp.start_polling()
    finally:
        await bot.close()

asyncio.run(main())

配置文件(settings.py)

import os

BOT_TOKEN = os.getenv('BOT_TOKEN')
if not BOT_TOKEN:
    print('You have forgot to set BOT_TOKEN')
    BOT_TOKEN = 'missing'
    quit()

运行效果与前置条件

  • 代码运行正常,功能符合预期:
    • 收到/start或/restart命令时,回复带用户提及的问候语
    • 收到其他任意文本消息时,原样返回消息内容(回声响应)
  • 运行前置要求:
    • 已注册Telegram机器人账号
    • 环境变量中正确配置BOT_TOKEN

结论

这种注册方式完全可行。aiogram的Dispatcher支持多处理器注册,处理器按注册顺序依次匹配:

  1. 优先匹配start_handler,仅当消息为指定命令时触发
  2. 若第一个处理器未匹配,才会匹配echo_answer,只要消息包含文本内容就会执行

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 17:25:25