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)
Here are some examples of 403 error messages: Often, 403 forbidden errors are caused by an access misconfiguration on the client-side, which means you can usually resolve the issue yourself. A common cause of these errors is the file or folder permission settings, which control who can read, write, and execute the file or folder.
If the user (here scraper) exceeds it, it gets some kind of error, for instance, urllib.error.httperror: http error 403: forbidden. Resolving urllib.error.httperror: http error 403: forbidden? This error is caused due to mod security detecting the scraping bot of the urllib and blocking it.
Access is “forbidden” and the message “Error 403 – Forbidden” appears in the browser window. If a client such as a browser wants to retrieve a URL from a server via http, the server first verifies this request.
It is an HTTP status code. When you encounter this error message, you are basically trying to reach an address or a website that is forbidden to access. Here are examples of some these errors that are commonly thrown: Forbidden: You don't have permission to access [directory] on this server
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With