Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

544
Views
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 answers
Answer question

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 Report

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!