Fra*_*ran 4 python exception handle telegram
我正在努力避免电报错误。当消息未修改时会出现此错误:
telegram.error.BadRequest: Message is not modified
Run Code Online (Sandbox Code Playgroud)
我想创建一个函数来在发生此错误时打印消息,而不是打印原始错误消息电报。我尝试过类似的方法但不起作用:
def error_callback(bot, update, error):
try:
raise error
except BadRequest:
# handle malformed requests - read more below!
print('Same message')
Run Code Online (Sandbox Code Playgroud)
首先,如果没有明显的错误,如果用户单击按钮太快,则可能会发生此错误。在这种情况下,它很容易被忽略。
假设您正在使用python-telegram-bot 库查看您的代码,您可以遵循两种方法:
1.全局忽略错误:
def error(bot, update, error):
if not (error.message == "Message is not modified"):
logger.warning('Update "%s" caused error "%s"' % (update, error))
但您仍然会在控制台上收到:
2017-11-03 17:16:41,405 - telegram.ext.dispatcher - WARNING - A TelegramError was raised while processing the Update
您唯一能做的就是禁用该字符串以防止任何类型的错误执行此操作:
updater.dispatcher.logger.addFilter((lambda s: not s.msg.endswith('A TelegramError was raised while processing the Update')))
在你的 main() 中。学分
2. 忽略您调用的方法中的错误:
您可以忽略您正在调用的方法中的错误:
try:
# the method causing the error
except TelegramError as e:
if str(e) != "Message is not modified": print(e)
第二种方法将在控制台上完全忽略错误,而不修改错误回调函数,但您必须在导致该异常的每个方法中使用它。
打印“文本”而不是忽略:
我建议您忽略该错误,但是如果您想按照您所说的那样打印字符串:您可以非常轻松地修改这两种方法来打印字符串。
第一种方法的示例:
def error(bot, update, error):
if error.message == "Message is not modified":
# print your string
return
logger.warning('Update "%s" caused error "%s"' % (update, error))
第二种方法的示例:
try:
# the method causing the error
except TelegramError as e:
if str(e) == "Message is not modified": print(your_string)
| 归档时间: |
|
| 查看次数: |
12749 次 |
| 最近记录: |