python - error_code":403,"description":"Forbidden: bot 被用户屏蔽。python中的错误句柄
问题描述
我在 python 中使用 Telebot API 时遇到问题。如果用户向机器人发送消息并等待响应,同时他会阻止机器人。我收到此错误,机器人不会响应其他用户:
403,"description":"Forbidden: bot被用户屏蔽
试试,catch 块没有为我处理这个错误
摆脱这种情况的任何其他想法?如何发现该机器人被用户阻止并避免回复此消息?
这是我的代码:
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)
解决方案
您可以通过多种方式处理这些类型的错误。当然,您需要在您认为会引发此异常的任何地方使用 try/except 。
所以,首先,导入异常类,即:
from telebot.apihelper import ApiTelegramException
然后,如果您查看此类的属性,您将看到haserror_code
和。当然,当您收到错误消息时,Telegram 也会提出同样的问题。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)
你也可以传递参数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")
让我知道您将使用哪种解决方案。关于第二个,我从来没有诚实地使用过它,但它非常有趣,我将在我的下一个机器人中使用它。它应该工作!
推荐阅读
- mongodb - java.lang.NoSuchFieldException:使用播放框架处理嵌入式 MongoDB
- gitlab - 无法在 GitLab 管道中到达 SONAR_HOST_URL
- python - 使用 python flask_socketio 处理传入请求
- python - 地理 - 具有相同省名的两个句子返回不同的结果
- javascript - 如何在 Cloud Functions 中的 Firebase 实时数据库中循环浏览多个用户 ID
- c# - 检查文件名是否与特定模式匹配
- ruby-on-rails - 如何使用 ruby 从给定数组生成或创建最大数
- c# - 通过 PushSharp.Core 发送 Apple 推送通知停止工作
- gnuplot - 使用 gnuplot 的直方图
- python - 如何在 python 中使用双击出价管理器(DBM)API