我怎么知道使用的命令? - 不和谐.py

时间:2021-01-31 10:03:14

标签: error-handling discord discord.py embed

我正在尝试对我的 Discord.py 进行错误处理,我怎么知道使用什么命令来弹出错误?

@bot.event
async def on_command_error(ctx, error):
    print("error: ",error)

    if search("not found", str(error)):
        c_f = random.choice([f"`{command used}` was not found, silly.", "Ehm.. Since when do we have `{command used}`?", "I don't know what `{command used}` is?"])
        embed=discord.Embed(title=c_f, description=f"Please use existing commands. {ctx.author.mention}", color=error_color)
        embed.timestamp = datetime.utcnow()
        embed.set_footer(text=bot_name, icon_url=icon_uri)
        await ctx.send(embed=embed)
    elif search("cooldown", str(error)):
        c_d = random.choice(["Did you drink energy drinks!?", "Why are you stressing, buddy.", "Duhh, wait, you're on cooldown!"])
        second_remain = round(error.retry_after, 1)
        embed=discord.Embed(title=c_d, description=f"Try again after {second_remain}s. {ctx.author.mention}", color=error_color)
        embed.timestamp = datetime.utcnow()
        embed.set_footer(text=bot_name, icon_url=icon_uri)
        await ctx.send(embed=embed)
    else:
        raise error

我可以使用任何属性吗?

2 个答案:

答案 0 :(得分:1)

您可以使用ctx.command

    @bot.event
    async def on_command_error(ctx, exception):
        error = getattr(exception, "original", exception)

        if hasattr(ctx.command, "on_error"):  # If a command has it's own handler
            return

        elif isinstance(error, CommandNotFound):
            return

        if isinstance(error, discord.CommandInvokeError):
            print(ctx.command)

答案 1 :(得分:0)

您的解决方案是将它们专门添加到命令中,这也意味着它可以帮助更准确地诊断命令的问题。

您还可以将任何错误事件添加到特定侦听器,就像您为所有命令所做的那样,而是单独添加它们。

@bot.command()
async def command_name(ctx):
    # ...


@command_name.error 
async def command_name_error(ctx, error):
    if isinstance(error, commands.CommandInvokeError):
        await ctx.send("An error from this command" + error)

使用 @command_name.error 将您的命令名称放在 .error 之前,如果该命令产生错误,则会生成该命令的错误侦听器。