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
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 withif
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()
returnssend_message()
, which returns aMessage
object, which contains ajson
string set toself.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:
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:
Then, if you look at attributes of this class, you will see that has
error_code
,description
andresult_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:
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 parameterexception_handler
exception_handler
must be a class withhandle(e: Exception)
method.Something like this:
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!