discord.py 齿轮中每个命令的错误处理

discord.py error handling for every command in a cog

我想为我的 cog 添加一些错误处理,因为所有命令都需要用户的参数。但是,我发现这样做的唯一方法是要求每个命令都有自己的错误句柄,这非常耗时,因为我有 50 多个命令都采用这种格式。

如果可能的话,我希望能够创建一个错误处理程序,它只适用于那个齿轮中的命令。我该怎么做?

示例命令:

  @commands.command()
  async def poke(self, ctx, tag: Optional[discord.Member]=None, *args):
    self.poke = False
    await ctx.send(f"{tag.mention} Has been poked by {ctx.author.mention}")

  @commands.command()
  async def fight(self, ctx, tag: Optional[discord.Member]=None, *args):
    self.fight = False
    await ctx.send(f"{tag.mention} Has been fought by {ctx.author.mention}")
  

Cog-specific 错误处理可以通过在 cog class:

中覆盖 cog_command_error 来完成
class Test(commands.Cog):
    def __init__(self, bot):
        self.bot = bot

    @commands.command()
    async def poke(self, ctx, tag: Optional[discord.Member] = None, *args):
        self.poke = False
        await ctx.send(f"{tag.mention} Has been poked by {ctx.author.mention}")

    @commands.command()
    async def fight(self, ctx, tag: Optional[discord.Member]=None, *args):
        self.fight = False
        await ctx.send(f"{tag.mention} Has been fought by {ctx.author.mention}")

    # Cog error handler
    async def cog_command_error(self, ctx, error):
        await ctx.send(f"An error occurred in the Test cog: {error}")