error_code":403,"description":"禁止:机器人被用户阻止。python 中的错误处理

Ehs*_*san 9 python telegram telegram-bot

我在 python 中使用远程机器人 API 时遇到问题。如果用户向机器人发送消息并等待响应,同时阻止机器人。我收到此错误,机器人不会响应其他用户:

403,"description":"禁止:机器人被用户阻止

尝试,catch 块没有为我处理这个错误

还有其他想法可以摆脱这种情况吗?如何发现机器人被用户阻止并避免回复此消息?

这是我的代码:

import telebot
import time


@tb.message_handler(func=lambda m: True)
def echo_all(message):
    try:
           time.sleep(20) # to make delay 
           ret_msg=tb.reply_to(message, "response message") 
           print(ret_msg)
           assert ret_msg.content_type == 'text'
    except TelegramResponseException  as e:
            print(e) # do not handle error #403
    except Exception as e:
            print(e) # do not handle error #403
    except AssertionError:
            print( "!!!!!!! user has been blocked !!!!!!!" ) # do not handle error #403
     

tb.polling(none_stop=True, timeout=123)
Run Code Online (Sandbox Code Playgroud)

Cha*_*ony 3

这似乎实际上并不是一个错误,因此try catch无法为您处理它。您必须获取返回代码并if else可能用语句处理它(在这种情况下 switch 语句会更好,但我不认为 python 有它的语法)。

编辑

在方法调用之后,看起来像reply_to()returns send_message(),它返回一个Message对象,其中包含在方法中json设置的字符串。在该字符串中,您可能会找到状态代码(您可以根据需要捕获和处理 400 和 500)。self.json__init__()