Aiogram中message_handler仅响应/开头消息的问题求助
解决方案
要让这个handler接收任意文本消息并仅在匹配时响应,只需做以下修改:
关键调整
- 为
@dp.message_handler()添加filters.TEXT过滤器,使其捕获所有文本类型消息(不再局限于/开头的命令) - 保留内部匹配逻辑,不匹配时直接返回,不产生任何响应
修改后的完整代码
from telegram import types from telegram.ext import filters # 确保导入filters模块 @dp.message_handler(filters.TEXT) async def on_right_word(message: types.Message): chat = get_current_chat(message.chat.id) # 避免chat字典中无current_word键时抛出异常 if 'current_word' not in chat: return if chat['current_word'] == message.text.lower(): sender = message.from_user await message.reply(text='123')
说明
filters.TEXT是python-telegram-bot提供的过滤器,会让该handler接收所有文本类消息(包括普通文本、命令消息)- 新增的
'current_word' not in chat判断,用于处理聊天状态未初始化的情况,避免程序报错 - 当消息文本与
chat['current_word']不匹配时,函数直接返回,不会对消息做出任何响应,完全符合需求
内容的提问来源于stack exchange,提问作者Dmitry Oleshko
相关产品推荐
相关产品推荐

