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

Telebot(pyTelegramBotAPI):如何实现等待单次回复后停止机器人

问题:Telegram机器人函数重复接收旧回复的解决办法

我尝试在Python中实现一个函数,要求通过Telegram机器人发送消息,等待用户的单次回复后停止机器人,并返回该回复。以下代码仅能正常运行一次:第二次调用时,telebot会接收到相同的回复。请问有什么简单的方法可以实现我的需求?

def get_answer(question: str) -> str:
    bot = telebot.TeleBot('TOKEN')
    result = ''

    @bot.message_handler(func=lambda _: True)
    def handle_reply(message):
        nonlocal result
        result = message.text
        bot.stop_polling()

    bot.send_message(TELEGRAM_ID, question)
    bot.infinity_polling()

    return result

问题原因

每次调用get_answer都会创建新的TeleBot实例,但装饰器注册的消息处理器不会自动清理,加上infinity_polling的残留状态,会导致下次调用时读取到历史未处理的消息,或者重复触发旧处理器。

解决方案

改用单次轮询模式,主动清理消息处理器,并跳过历史未处理消息:

import telebot

def get_answer(question: str) -> str:
    bot = telebot.TeleBot('TOKEN')
    result = None

    def handle_reply(message):
        nonlocal result
        result = message.text
        # 移除当前处理器,避免下次调用重复触发
        bot.remove_message_handler(handle_reply)
        bot.stop_polling()

    # 手动注册处理器,方便后续移除
    bot.register_message_handler(handle_reply, func=lambda _: True)
    
    bot.send_message(TELEGRAM_ID, question)
    # 使用单次轮询,skip_pending跳过历史未处理消息
    bot.polling(none_stop=False, skip_pending=True)

    return result

关键调整说明

  • 用bot.register_message_handler替代装饰器,便于后续主动移除处理器
  • 获取回复后调用bot.remove_message_handler清理处理器,防止重复触发
  • 替换infinity_polling为bot.polling(none_stop=False),单次轮询完成后自动停止
  • 添加skip_pending=True参数,跳过函数调用前的历史未处理消息,避免读取旧回复

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 02:05:25