python - discord.py 对 cog 中每个命令的错误处理

标签 python error-handling discord.py

我想向我的 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 的错误处理可以通过覆盖 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}")

关于python - discord.py 对 cog 中每个命令的错误处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71473890/

相关文章:

python - Discord.py on_guild_join 事件

python - Django Haystack搜索html标签会返回所有帖子

python - 如何将多个数据框列添加到基本 mplfinance 图中()

ruby-on-rails - 如何在Rails的表单外显示错误

swift - 无法构建模块

discord.py - 如何创建一个 Discord 机器人来创建包含视频预览的嵌入内容

python-3.7 - 我怎样才能成功加载这个json文件?

python - Scrapy 显示 notImplementedError 我不知道为什么

python - BeautifulSoup 无法工作,出现 NoneType 错误

ruby-on-rails - Rails救援无效或无法到达