使用Discord API处理错误(on_error)

时间:2017-03-08 19:56:31

标签: python discord

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

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提出的异常,例如" Permissions denied"当机器人试图在没有权限的情况下发送消息时。

Discord API中有一个内置函数来处理:

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

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

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

现在,我尝试使用event*args**kwargs执行某些操作,但我需要一些帮助,以便我可以使用logging.warning()格式。由于object,我所能得到的只有print(*args)而且我不知道如何正确格式化。

1 个答案:

答案 0 :(得分:3)

好的,所以这段代码会记录,并且还会向导致错误的频道发送消息。

如果您不希望发送消息,可以删除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.