【问题标题】:Handling errors with the Discord API (on_error)使用 Discord API 处理错误 (on_error)
【发布时间】:2017-07-29 13:53:11
【问题描述】:

我从 Python 开始,目前正在使用 API 开发 Discord 机器人。到目前为止一切顺利,一切正常。现在,我希望在没有控制台的服务器上托管脚本,这意味着我希望输出进入文件而不是控制台。我目前有以下工作:

import discord
import logging

logging.basicConfig(filename='.\output.log', filemode='w', level=logging.INFO, format='%(asctime)s:%(levelname)s:%(message)s')

xzbot = discord.Client()

# logging when the bot starts
@xzbot.event
async def on_ready():
 logging.info('Logged in as ' + xzbot.user.name + ' (' + xzbot.user.id + ')\n')

因此,此代码会将任何警告和信息放在 output.log 中。话虽如此,当机器人尝试在没有权限的情况下发送消息时,它不适用于 Discord.py 引发的异常,例如“权限被拒绝”。

Discord API 中有一个内置函数可以处理这个问题:

discord.on_error(event, *args, **kwargs)

所以我可以这样调用这个函数:

async def xzbot.on_error(event, *args, **kwargs):
 pass

现在,我尝试使用 event*args**kwargs 做一些事情,但我需要一些帮助才能以我可以使用 logging.warning() 的格式获得它。由于print(*args),我所能得到的只是object,我不知道如何正确格式化。

【问题讨论】:

    标签: python discord


    【解决方案1】:

    好的,所以这段sn-p的代码会记录下来,并且还会向导致错误的通道发送一条消息。

    如果您不希望 await xzbot.send_message 发送消息,可以删除它。

    import traceback
    @xzbot.event
    async def on_error(event, *args, **kwargs):
        message = args[0] #Gets the message object
        logging.warning(traceback.format_exc()) #logs the error
        await xzbot.send_message(message.channel, "You caused an error!") #send the message to the channel
    

    traceback.format_exc() 格式化最后一个错误,因此它看起来像是打印到控制台的正常错误。

    Here's info on the traceback module.

    【讨论】:

      猜你喜欢
      • 2021-05-28
      • 2022-01-09
      • 2021-06-14
      • 1970-01-01
      • 1970-01-01
      • 2011-05-26
      • 1970-01-01
      • 1970-01-01
      • 2021-12-27
      相关资源
      最近更新 更多