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

pyTelegramBotAPI实现用户回复yes后机器人即时响应无需额外发消息

pyTelegramBotAPI 多轮对话键盘延迟/流程错乱问题修复

问题根因

  • 第一版异常原因:register_next_step_handler 仅负责绑定下一条收到的用户消息要执行的回调函数,不会主动运行回调里的业务逻辑。你在判断用户回复yes后,仅把another_test_step绑定为下一个回调,没有执行这个函数里发键盘、发选数字提示的代码,必须等用户再发一条消息触发another_test_step运行,才会弹出键盘,因此多了一步用户额外发消息的环节。
  • 第二版异常原因:手动调用another_test_step(message)时,该函数内部已经完成了after_key回调的绑定,你在函数外又重复写了一次相同的绑定语句,导致用户选完数字后after_key会被连续触发两次,流程完全错乱。

正确实现代码

import telebot
from telebot import types

API_TOKEN = 'place_token_here'
bot = telebot.TeleBot(API_TOKEN)

@bot.message_handler(func=lambda m: True)
def send_welcome(message):
    msg = bot.send_message(
        message.from_user.id,
        "Hi there, I am Example bot.\nWhat's your name?",
        allow_sending_without_reply=True
    )
    bot.register_next_step_handler(msg, another_test_step)

def another_test_step(message):
    markup = types.ReplyKeyboardMarkup(one_time_keyboard=True)
    markup.add('1', '2', '3')
    # 发送带键盘的选数字提示,保存发送的消息对象用于注册下一步
    num_prompt_msg = bot.send_message(
        message.from_user.id,
        'Choose your number',
        reply_markup=markup,
        allow_sending_without_reply=True
    )
    bot.register_next_step_handler(num_prompt_msg, after_key)

def after_key(message):
    # 发送重复询问提示,保存消息对象注册下一步
    repeat_prompt_msg = bot.send_message(
        message.from_user.id,
        f'You chose {message.text}. Do you want to repeat?'
    )
    bot.register_next_step_handler(repeat_prompt_msg, yet2_test_step)

def yet2_test_step(message):
    if message.text == "yes":
        # 直接调用选数字逻辑,函数内部已经自行注册了后续处理器,无需额外注册
        another_test_step(message)
    elif message.text == 'no':
        # 重置流程,直接调用欢迎逻辑即可
        send_welcome(message)

bot.enable_save_next_step_handlers(delay=2)
bot.load_next_step_handlers()
bot.infinity_polling()

优化说明

  • 所有register_next_step_handler统一传入机器人刚发送的提示消息对象作为第一个参数,而不是传入上一轮用户发送的消息,避免多轮对话下handler绑定错乱,这也是pyTelegramBotAPI官方推荐的写法。
  • 所有流程跳转直接调用对应步骤的处理函数,而不是仅用register_next_step_handler绑定,确保需要即时发送的消息、键盘能立刻推送给用户,不需要等待用户额外发消息触发。
  • 去掉了重复的handler注册逻辑,避免同一个用户消息触发多次处理函数导致流程异常。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.27 04:24:16