如何从电报机器人控制台记录错误

2024-04-28 10:50:38 发布

您现在位置:Python中文网/ 问答频道 /正文

电报机器人中不时出现错误,我想把它们记录下来。在所有的“try:except”中,我设置了日志记录,但由于某些原因,这些错误会在控制台中弹出,我找不到一个地方来获取它们

我需要找到的不是问题的原因,而是如何从控制台记录问题

(__init__.py:445 MainThread) ERROR - TeleBot: "A request to the Telegram API was unsuccessful. The server returned HTTP 400 Bad Request. Response body:
[b'{"ok":false,"error_code":400,"description":"Bad Request: message can\'t be edited"}']"

enter image description here


在文件末尾,我有这样一个构造,但由于某些原因,它没有捕获我上面指出的错误

while True:
    try:
        bot.polling(none_stop=True, interval=1, timeout=20)
    except Exception as E:
        log(E)

Tags: pytrueinitrequest地方错误记录机器人
1条回答
网友
1楼 · 发布于 2024-04-28 10:50:38

有他自己的Exception Handling

榜样

from telegram.error import (TelegramError, Unauthorized, BadRequest, 
                            TimedOut, ChatMigrated, NetworkError)

def error_callback(update, context):
    try:
        raise context.error
    except Unauthorized:
        # remove update.message.chat_id from conversation list
    except BadRequest:
        # handle malformed requests - read more below!
    except TimedOut:
        # handle slow connection problems
    except NetworkError:
        # handle other connection problems
    except ChatMigrated as e:
        # the chat_id of a group has changed, use e.new_chat_id instead
    except TelegramError:
        # handle all other telegram related errors

dispatcher.add_error_handler(error_callback)

调度员将捕获并记录任何其他错误。(如git页面中所述)

配置调度器的小示例

logging.basicConfig(
        format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
        level=logging.INFO)

相关问题 更多 >