Python Discord bot 在异常时发送文本

Posted

技术标签:

【中文标题】Python Discord bot 在异常时发送文本【英文标题】:Python Discord bot send text upon exception 【发布时间】:2021-04-05 01:01:41 【问题描述】:

我的 Discord 机器人中有一个功能,它充当一个魔术 8 球,您可以在其中提出问题并给出随机答复。调用该函数但未询问任何问题时会发生异常,我希望将某种错误消息打印到调用它的通道,以通知用户此错误已发生。这是我尝试过的:

@client.command(aliases=['8ball', 'eightball'])
async def _8ball(ctx, *,question):
    responses = ['yes', 'no', 'maybe so']
    response = random.choice(responses)
    try:
        await ctx.send(f'Question: question\n\
        Answer: response')
    except MissingRequiredArgument:
        await ctx.send("Please ask a question")
        pass

但除了终端,什么都没有打印出来。 有什么建议吗?

【问题讨论】:

【参考方案1】:
@client.event
async def on_command_error(ctx, error):
    if isinstance(error, commands.MissingRequiredArgument) and "replace me" in str(error):
        await ctx.send("You're missing a required argument idiot.¯\_(ツ)_/¯")

使用 discord.py,你不能真正使用 try 和 except。您需要检查 on_command_error 事件。将 "replace me" 替换为 MissingRequiredArgument 错误后出现的任何内容。例如MissingRequiredArgument: arg is a required argument that is missing. 然后将"replace me" 替换为"arg is a required argument that is missing"

顺便说一句,下次当您在代码中收到错误时,请将它们添加到您的问题中。它可以帮助我们了解出了什么问题。

【讨论】:

感谢您的帮助!而且我假设这对于其他错误也是相同的想法?这是否意味着这是将处理所有其他 MissingRequiredArgument 的事件 是的,其他错误也一样。至于多个 MissingRequiredArguments 的处理,这取决于 str(error) 中的消息。只要确保参数名称不同,错误就会不同。

以上是关于Python Discord bot 在异常时发送文本的主要内容,如果未能解决你的问题,请参考以下文章