Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

discord.py error handling for every command in a cog

I would like to add some error handling to my cog, as all the commands require an argument of a user. However, the only way I have found to do this would require each command to have its own error handle, which is very time consuming as I have 50+ commands all with this format.

If possible, I would like to be able to create an error handler, that only works for the commands in that one cog. How would I go about this?

Example commands:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

Cog-specific error handling can be done by overriding cog_command_error in the cog class:

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}")
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading