在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支持多处理器注册,处理器按注册顺序依次匹配:
- 优先匹配
start_handler,仅当消息为指定命令时触发 - 若第一个处理器未匹配,才会匹配
echo_answer,只要消息包含文本内容就会执行
内容的提问来源于stack exchange,提问作者Kirill Setdekov
相关产品推荐
相关产品推荐

