使用Discord API处理错误(on_error)

问题描述:

我开始使用Python,我目前正在使用API​​处理Discord bot。到目前为止好,一切正常。现在,我正在寻找在没有控制台的服务器上托管脚本,这意味着我希望输出在文件中而不是在控制台中。我有以下工作:使用Discord API处理错误(on_error)

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引发的异常,例如当僵尸程序尝试发送邮件而没有权限时,“权限被拒绝”。

还有就是不和谐的API中内置的函数来处理:

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

这样我就可以调用这个函数是这样的:

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

现在,我试图做一些与event*args**kwargs,但我需要一些帮助来获得这种格式,我可以只使用logging.warning()。我能够得到的是object作为print(*args)的结果,我不知道如何正确格式化。

好的,所以这段代码会记录下来,并且还会向发生错误的通道发送消息。

如果您不想发送邮件,您可以删除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.