except Exception as error: discord.py code example
Example: errors in discord.py
# This will be a quick example of how to handle errors in discord.py
import discord
from discord.ext import commands
# make sure to import these ^
# Let's say we have a kick command
@client.command()
@commands.has_any_role('Admin')
async def kick(ctx, member : discord.Member, *, reason=None):
await member.kick(reason=reason)
await ctx.send('''
Kicked user: {}
Reason: {}'''.format(member, reason))
# Okay, so it works. But what if someone does !kick without the arguments
# We will get an error. So let's handle that.
# I will show 2 ways
# Here is the first one.
# This way will handle EVERY missing arguments error
@client.event
async def on_command_error(ctx, error):
if isinstance(error, commands.MissingRequiredArgument):
await ctx.send('Make sure you put the required arguments.')
# Now, if someone uses any command and doesn't put the
# Required arguments, then this event will occur
# Here is the second one
# This way will handle one command's error
@kick.error
async def kick_error(ctx, error):
if isinstance(error, commands.MissingRequiredArgument):
await ctx.send('To use the kick command do: !kick <member>')
# Using this method we can account for all our commands individually
# I recommend using this method, however both methods work basically the same
# For example if we had a ban command, we could do the same
# Doing @ban.error and accounting for that one as well!