首页 > 解决方案 > error_code":403,"description":"Forbidden: bot 被用户屏蔽。python中的错误句柄

问题描述

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

403,"description":"Forbidden: 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)

标签: pythontelegramtelegram-bot

解决方案


您可以通过多种方式处理这些类型的错误。当然,您需要在您认为会引发此异常的任何地方使用 try/except 。

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

from telebot.apihelper import ApiTelegramException

然后,如果您查看此类的属性,您将看到haserror_code和。当然,当您收到错误消息时,Telegram 也会提出同样的问题。descriptionresult_jsondescription

所以你可以用这种方式重写你的处理程序:

@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))

另一种方法可能是使用 exception_handler,pyTelegramBotApi 中的内置函数当你初始化你的机器人类时,tb = TeleBot(token)你也可以传递参数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")

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


推荐阅读