aiogram:通过提及调用Telegram机器人外部聊天命令的方法
可以创建这类跨聊天调用的Telegram机器人命令
你当前的代码只响应不带机器人用户名的/hello命令,而在外部聊天(如群聊)中用户通常会输入/hello@your_bot_username(比如/hello@gamebot),所以默认的命令处理器无法识别。以下是两种修改方案:
方案1:使用CommandHandler(推荐)
CommandHandler默认支持匹配带@机器人用户名的命令,替换你的代码为:
from telegram.ext import CommandHandler async def hello_callback(update, context): await update.message.reply_text('Hello World!') # 注册命令处理器 dp.add_handler(CommandHandler('hello', hello_callback))
方案2:给message_handler添加正则匹配过滤器
如果你坚持使用message_handler装饰器,可以通过正则过滤器同时匹配两种命令格式:
from telegram import types from telegram.ext import filters # 替换为你的机器人用户名 BOT_USERNAME = "gamebot" @dp.message_handler( commands=['hello'], filters=filters.Regex(rf'^/hello(@{BOT_USERNAME})?$') ) async def hello_callback(message: types.Message): await message.reply('Hello World!')
额外注意事项
- 确保机器人已被添加到目标聊天群,且拥有发送消息的权限
- 测试时需使用完整的命令格式(如
/hello@gamebot)触发
内容的提问来源于stack exchange,提问作者tpadev
相关产品推荐
相关产品推荐

