ERROR_CODE&QOOT;:403,&QOOT;DESCRIPTION&QOOT;:&QOOT:BOT已被用户阻止。Python中的错误句柄 [英] error_code":403,"description":"Forbidden: bot was blocked by the user. error handle in python

查看:20
本文介绍了ERROR_CODE&QOOT;:403,&QOOT;DESCRIPTION&QOOT;:&QOOT:BOT已被用户阻止。Python中的错误句柄的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

403,";Description";:";Formitted:bot被用户阻止

尝试,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)

推荐答案

您可以通过多种方式处理这些类型的错误。 您肯定需要使用Try/,除非您认为会引发此异常。

所以,首先导入异常类,即:

from telebot.apihelper import ApiTelegramException
然后,如果您查看这个类的属性,您会发现它有error_codedescriptionresult_json。 当然,当您收到错误时,Telegram发出的description是相同的。

这样您就可以通过以下方式重新编写处理程序:

@tb.message_handler() # "func=lambda m: True" isn't needed
def echo_all(message):
    time.sleep(20) # to make delay
    try:
           ret_msg=tb.reply_to(message, "response message")
    except ApiTelegramException as e:
           if e.description == "Forbidden: bot was blocked by the user":
                   print("Attention please! The user {} has blocked the bot. I can't send anything to them".format(message.chat.id))
另一种方法是使用异常处理程序,这是pyTelegram BotApi中的内置函数 当您使用tb = TeleBot(token)初始化bot类时,您还可以传递参数exception_handler

exception_handler必须是具有handle(e: Exception)方法的类。 大概是这样的:

class Exception_Handler:
    def handle(self, e: Exception):
        # Here you can write anything you want for every type of exceptions
        if isinstance(e, ApiTelegramException):
            if e.description == "Forbidden: bot was blocked by the user":
                # whatever you want

tg = TeleBot(token, exception_handler = Exception_Handler())
@tb.message_handler()
def echo_all(message):
    time.sleep(20) # to make delay
    ret_msg = tb.reply_to(message, "response message")

让我知道您将使用哪种解决方案。关于第二个,我从来没有诚实地使用过它,但它非常有趣,我会在我的下一个机器人中使用它。应该行得通!

这篇关于ERROR_CODE&QOOT;:403,&QOOT;DESCRIPTION&QOOT;:&QOOT:BOT已被用户阻止。Python中的错误句柄的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆