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

Viewed 5691

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)
4 Answers

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!

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

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)

def command_start(update: Update, context: CallbackContext):
  bot = context.bot
  cid = update.message.chat_id
  bot.send_message(cid, "Bot para aprender")

def repeat_test(context: CallbackContext): 
  usuarios = ['1732411248','1284725300']
  job = context.job
  for usuario in usuarios:
   context.bot.send_message(chat_id=usuario, text=job.context)
        
def bot_main():
  updater = Updater(BOT_TOKEN, use_context=True)
  dp = updater.dispatcher
  dp.add_handler(CommandHandler("start", command_start))

  job_que = updater.job_queue

  morning = datetime.time(2, 21, 1, 1, tzinfo=pytz.timezone("Cuba"))
  
  job_que.run_daily(repeat_test, morning25, context="sense")
  job_que.start()   

  updater.start_polling(timeout=30) 
  updater.idle()` 
Related