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

Python开发Telegram机器人时ReplyKeyboardMarkup Selective参数生效异常问题

问题定位与修复方案

问题原因

Telegram Bot API对ReplyKeyboardMarkup的selective参数生效有强制要求,必须满足以下两个条件的其中一个:

  • 发送的消息是回复触发用户的原始消息,传入reply_to_message_id参数指向用户发送的触发消息
  • 消息文本里@了对应用户的用户名

你当前的代码没有满足上述条件,所以selective=True没有生效,自定义键盘还是对全群可见。

修复代码

只需在send_message参数中新增reply_to_message_id指向用户的原始触发消息即可:

if message.text == "Tesla Bot":
    ye = random.choice(["I'm here, as always:(", "Did you call me?"])
    bot_answers = random.choice(["something important or bored?", "what you wanted?"])
    item1 = types.KeyboardButton("Bot who are you?")
    item2 = types.KeyboardButton("Bot why are you here?")
    item3 = types.KeyboardButton("Let's really talk next time")

    markup = types.ReplyKeyboardMarkup(resize_keyboard=True, selective=True).add(item1, item2, item3)

    bot.send_message(
        message.chat.id, 
        "{0} <b>{1.first_name}</b> {2}".format(ye, message.from_user, bot_answers),
        parse_mode='html', 
        reply_markup=markup,
        # 新增本行,回复用户的原始触发消息,满足selective生效条件
        reply_to_message_id=message.message_id
    )

可选方案

如果不想用回复消息的形式,也可以在发送的文本里加上@{message.from_user.username},同样可以触发selective效果。注意如果用户没有设置用户名的话这个方法不生效,推荐使用新增reply_to_message_id的方案,兼容性更强。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.23 22:45:04