Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

543
Vistas
error_code":403,"description":"Forbidden: bot was blocked by the user. error handle in python

I have a problem using telebot API in python. If the user sends a message to the bot and waits for the response and at the same time he blocks the bot. I get this error and the bot will not respond for other users:

403,"description":"Forbidden: bot was blocked by the user

Try, catch block is not handling this error for me

any other idea to get rid of this situation? how to find out that the bot is blocked by the user and avoid replying to this message?

this is my code:

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)
over 4 years ago · Santiago Trujillo
3 Respuestas
Responde la pregunta

0

This doesn't appear to actually be an error and thus try catch won't be able to handle it for you. You'll have to get the return code and handle it with if else statements probably (switch statements would work better in this case, but I don't think python has the syntax for it).

EDIT

Following the method calls here it looks like reply_to() returns send_message(), which returns a Message object, which contains a json string set to self.json in the __init__() method. In that string you can likely find the status code (400s and 500s you can catch and deal with as you need).

over 4 years ago · Santiago Trujillo Denunciar

0

You can handle these types of error in a lot of way. For sure you need to use try/except everywhere you think this exception would be raised.

So, first, import the exception class, that is:

from telebot.apihelper import ApiTelegramException

Then, if you look at attributes of this class, you will see that has error_code, description and result_json. The description is, of course, the same raised by Telegram when you get the error.

So you can revrite your handler in this way:

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

Another way could be to use an exception_handler, a built-in function in pyTelegramBotApi When you initialize your bot class with tb = TeleBot(token) you can also pass the parameter exception_handler

exception_handler must be a class with handle(e: Exception) method. Something like this:

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

Let me know which solution will you use. About the second, I've never used it honestly, but it's pretty interesting and I'll use it in my next bot. It should work!

over 4 years ago · Santiago Trujillo Denunciar

0

You haven't specified whether the bot is in a group or for individuals.
For me there were no problems with try and except.

This is my code:

@tb.message_handler(func=lambda message: True)
def echo_message(message):

    try:
        tb.reply_to(message, message.text)
    except Exception as e:
        print(e)

tb.polling(none_stop=True, timeout=123)
over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda