1# This will be a quick example of how to handle errors in discord.py
2import discord
3from discord.ext import commands
4# make sure to import these ^
5
6# Let's say we have a kick command
7@client.command()
8@commands.has_any_role('Admin')
9async def kick(ctx, member : discord.Member, *, reason=None):
10 await member.kick(reason=reason)
11 await ctx.send('''
12Kicked user: {}
13Reason: {}'''.format(member, reason))
14
15# Okay, so it works. But what if someone does !kick without the arguments
16# We will get an error. So let's handle that.
17
18# I will show 2 ways
19
20# Here is the first one.
21# This way will handle EVERY missing arguments error
22@client.event
23async def on_command_error(ctx, error):
24
25 if isinstance(error, commands.MissingRequiredArgument):
26 await ctx.send('Make sure you put the required arguments.')
27 # Now, if someone uses any command and doesn't put the
28 # Required arguments, then this event will occur
29
30# Here is the second one
31# This way will handle one command's error
32@kick.error
33async def kick_error(ctx, error):
34 if isinstance(error, commands.MissingRequiredArgument):
35 await ctx.send('To use the kick command do: !kick <member>')
36 # Using this method we can account for all our commands individually
37 # I recommend using this method, however both methods work basically the same
38 # For example if we had a ban command, we could do the same
39 # Doing @ban.error and accounting for that one as well!