我想在cog中添加一些错误处理,因为所有命令都需要用户的参数.然而,我发现实现这一点的唯一方法是每个命令都有自己的错误句柄,这非常耗时,因为我有50多个命令都使用这种格式.

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

命令示例:

  @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类中重写cog_command_error可以完成Cog特定的错误处理:

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}")

Python相关问答推荐

Python无法在已导入的目录中看到新模块

根据网格和相机参数渲染深度

在Python中对分层父/子列表进行排序

类型错误:输入类型不支持ufuncisnan-在执行Mann-Whitney U测试时[SOLVED]

将图像拖到另一个图像

如何让Flask 中的请求标签发挥作用

按顺序合并2个词典列表

如何在solve()之后获得症状上的等式的值

如果条件不满足,我如何获得掩码的第一个索引并获得None?

Pandas GroupBy可以分成两个盒子吗?

如何从列表框中 Select 而不出错?

numpy.unique如何消除重复列?

如何使用使用来自其他列的值的公式更新一个rabrame列?

如何创建引用列表并分配值的Systemrame列

基于Scipy插值法的三次样条系数

将链中的矩阵乘法应用于多组值

如何使用matplotlib查看并列直方图

Pandas在rame中在组内洗牌行,保持相对组的顺序不变,

如何写一个polars birame到DuckDB

我怎么才能用拉夫分拣呢?