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

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 22:25:19