'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:
@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 1:[1]
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}")
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Jonathan Feenstra |