Lucas
Lucas

Reputation: 41

How to send a message when a command is not found?

I am trying to send a message when a command is not found but it is not working:

@client.event
async def on_ready():
    change_status.start()
    print("----------------------")
    print("Logged In As")
    print("Username: %s" % client.user.name)
    print("ID: %s" % client.user.id)
    print("----------------------")
async def on_message(ctx, error):
    if isinstance(error, commands.CommandNotFound):
        text = ('Sorry {}, this command does not exist check $help for a more detailed list of').format(ctx.author.mention)
        msg = await ctx.send(text)
        await ctx.message.delete()
        await asyncio.sleep(5)
        await msg.delete()
    else:
        pass
    raise error

Upvotes: 0

Views: 953

Answers (3)

Billy
Billy

Reputation: 1207

The on_command_error event is called when an error happens on any command. and inside the on_command_error event you can check whether the error is an instance of CommandNotFound, which is thrown when the typed command is not found, or it doesn't exist. And if so, you can send a message to the channel, where the command was used.

@client.event
async def on_command_error(ctx, error):
    """Command error handler"""
    embed = discord.Embed(color=discord.Color.red())
    if isinstance(error, commands.CommandNotFound):
        embed.title = "Command not Found"
        embed.description = "Recheck what you've typed."
        #await ctx.send(embed=embed)

Upvotes: 0

Lucas
Lucas

Reputation: 41

I have found an answer to my issue instead of running it through a client.event decorator, I have ran it through a client.listen, decorator:

@client.event
async def on_ready():
    change_status.start()
    print("----------------------")
    print("Logged In As")
    print("Username: %s" % client.user.name)
    print("ID: %s" % client.user.id)
    print("----------------------")
@client.listen()
async def on_command_error(ctx, error):
    if isinstance(error, commands.CommandNotFound):
        text = ('Sorry {}, this command does not exist check $help for a more detailed list of').format(ctx.author.mention)
        msg = await ctx.send(text)
        await ctx.message.delete()
        await asyncio.sleep(5)
        await msg.delete()

Upvotes: 0

Łukasz Kwieciński
Łukasz Kwieciński

Reputation: 15689

You're looking for on_command_error event

@client.event
async def on_command_error(ctx, error):
    if isinstance(error, commands.CommandNotFound):
        await ctx.send("Command does not exist.")

Reference:

Upvotes: 1

Related Questions