musta21
musta21

Reputation: 53

How to catch errors and send responses in discord.py?

I want my bot to send a message to the chat when someone types a non-existent command. I tried this but nothing happened. Here is the code:

import discord
from discord.ext import commands

bot = commands.Bot(command_prefix=BOT_PREFIX)

@bot.event
async def on_ready():
    print("Logged in as: " + bot.user.name + "\n")

@bot.command()
async def asdasd(ctx):
    try:
        if asdasd:
            await ctx.send('asd')
    except discord.ext.commands.errors.CommandNotFound:
        await ctx.send('error')

bot.run('My Token Here')

Upvotes: 2

Views: 4913

Answers (1)

Diggy.
Diggy.

Reputation: 6944

There's an exception handler event specifically for this!

Example:

@bot.event
async def on_command_error(ctx, error):
    if isinstance(error, discord.ext.commands.errors.CommandNotFound):
        await ctx.send("That command wasn't found! Sorry :(")

Read up more about it here. All the different errors can be found here.

Good luck!

Upvotes: 3

Related Questions