【问题标题】:How can I know the command used? - Discord.py我怎么知道使用的命令? - 不和谐.py
【发布时间】:2021-05-04 18:01:50
【问题描述】:

我正在尝试对我的 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

我可以使用任何属性吗?

【问题讨论】:

    标签: error-handling discord discord.py embed


    【解决方案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)
    

    【讨论】:

    • 我不使用齿轮。
    【解决方案2】:

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

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

    @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 之前,如果它产生错误,则会为该命令创建一个错误侦听器。

    【讨论】:

    • 我真的不想为我的所有命令都这样做,因为我有很多。我只想使用错误具有的属性(如果有的话)。似乎在文档中找不到任何内容。
    • 您可以只将这些特定错误添加到可能引发错误的命令中
    • 不是命令,只有在触发-dwadwa等命令时才会出现此错误。所以我可以将它添加到特定的命令中,除非我想要数十亿行。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-12-16
    • 2021-09-27
    • 1970-01-01
    • 1970-01-01
    • 2021-09-26
    • 2021-01-18
    • 2016-09-02
    相关资源
    最近更新 更多