Search code examples
discordpycharmdiscord.py

Discord commands error: Command cannot be found


I'm trying to make a leveling feature to my discord bot but I'm facing some issues. Here's the code. Comes with an error when I type !xp it comes with this, not sure how to fix.

Ignoring exception in command None:
discord.ext.commands.errors.CommandNotFound: Command "xp" is not found.

I also have a separate file named 'lvldb.json'.

import discord
from discord.ext import commands

import asyncio
import json

bot = commands.Bot(command_prefix='!')

client = discord.Client()

m = {}

@client.event
async def on_ready():
    global m
    with open("lvldb.json", "r") as j:
        m = json.load(j)
        j.close()
    if len(m) == 0:
        m = {}
        for member in client.get_guild(GUILDTOKEN).members:
            m[str(member.id)] = {"xp": 0, "messageCountdown": 0}
    print("ready")
    while True:
        try:
            for member in client.get_guild(GUILDOTOKEN).members:
                m[str(member.id)]["messageCountdown"] -= 1
        except:
            pass
        await asyncio.sleep(1)


@client.event
async def on_message(message):
    global m
    if message.content == "!stop" and message.author.id == ID:
        with open("lvldb.json", "w") as j:
            j.write(json.dumps(m))
            j.close()
        await client.close()
    elif message.content == "!xp":
        await message.channel.send(str( m[str(message.author.id)]["xp"]))
    elif message.author != client.user:
        if m[str(message.author.id)]["messageCountdown"] <= 0:
            m[str(message.author.id)]["xp"] += 10
            m[str(message.author.id)]["messageCountdown"] = 10


@client.event
async def on_member_join(member):
    m[str(member.id)] = {"xp": 0, "messageCountdown": 0}

Solution

  • You're creating both a commands.Bot and discord.Client. You don't want to do this; Bot is already a subclass of the generic client and can do everything it needs to do. Only make one, such as

    bot = commands.Bot(command_prefix='!')
    
    @bot.event
    async def on_message(message):
        ...
    @bot.event
    async def on_member_join(member):
        ...
    

    You're also getting the error because discord.py thinks the user is trying to invoke a command when it starts with the prefix. It tries to get the command but then raises exception when it can't. You can silently ignore it (see here):

    @bot.event
    async def on_command_error(ctx, err):
        if err.__class__ is commands.errors.CommandNotFound:
            # who cares?
            return
        print('oh no, an error occured, printing it:', file=sys.stderr)
        traceback.print_exception(type(err), err, err.__traceback__, file=sys.stderr)