我在python中使用telebot有问题。如果用户向bot发送消息,等待响应,同时阻止bot。我得到了这个错误,而bot不会对其他用户做出响应:
403,“描述”:“禁止: bot被用户阻止。
尝试,catch块不是为我处理这个错误。
还有其他办法来摆脱这种情况吗?如何发现bot被用户阻塞,并避免回复此消息?
这是我的密码:
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)
发布于 2021-12-14 07:57:57
您可以以多种方式处理这些类型的错误。当然,您需要使用try/,除非您认为会引发此异常。
因此,首先,导入异常类,即:
from telebot.apihelper import ApiTelegramException
然后,如果您查看这个类的属性,您将看到它有error_code
、description
和result_json
。当然,当您收到错误时,description
也是由电报提出的。
因此,您可以这样修改您的处理程序:
@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))
另一种方法是使用exception_handler,这是pyTelegramBotApi中内置的函数,当您用tb = TeleBot(token)
初始化bot类时,您还可以传递参数exception_handler
。
exception_handler
必须是一个具有handle(e: Exception)
方法的类。就像这样:
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")
让我知道你会用哪种解决方案。第二,我从来没有诚实地使用过它,但它非常有趣,我将在我的下一个机器人中使用它。应该管用的!
发布于 2021-08-27 07:58:49
这看起来并不是一个错误,因此try
catch
将无法为您处理它。您可能需要获得返回代码并使用if
else
语句来处理它(在本例中,开关语句会更好地工作,但我认为python没有相应的语法)。
编辑
在方法调用这里之后,它看起来像是reply_to()
返回send_message()
,它返回一个Message
对象,其中包含在__init__()
方法中设置为self.json
的json
字符串。在该字符串中,您可能会找到状态代码(400s和500s,您可以根据需要捕获和处理)。
发布于 2021-08-27 18:03:36
您还没有指定机器人是在一个组中还是在个人中。
对我来说,尝试和尝试是没有问题的。
这是我的密码:
@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)
https://stackoverflow.com/questions/68912583
复制相似问题