Search code examples
pythondiscord.pykeyerror

Making custom prefix command for my discord bot


I am getting the following error

Ignoring exception in on_message
Traceback (most recent call last):
  File "C:\python\lib\site-packages\discord\client.py", line 343, in _run_event
    await coro(*args, **kwargs)
  File "d:\VS CODE ALL FILES\cn utility\main.py", line 1034, in on_message     
    await client.process_commands(message)
  File "C:\python\lib\site-packages\discord\ext\commands\bot.py", line 975, in process_commands
    ctx = await self.get_context(message)
  File "C:\python\lib\site-packages\discord\ext\commands\bot.py", line 886, in get_context
    prefix = await self.get_prefix(message)
  File "C:\python\lib\site-packages\discord\ext\commands\bot.py", line 831, in get_prefix
    ret = await discord.utils.maybe_coroutine(prefix, self, message)
  File "C:\python\lib\site-packages\discord\utils.py", line 341, in maybe_coroutine
    value = f(*args, **kwargs)
  File "d:\VS CODE ALL FILES\cn utility\main.py", line 493, in get_prefix
    return prefixes[str(message.guild.id)] #recieve the prefix for the guild id given
KeyError: '1036979664775815178'

I was making a custom prefix but this error is popping up.


Solution

  • A lot of times this can happen when you have created the custom prefix function and setup without removing and then adding back your bot. This is because you have the prefix and guild id added when your bot joins a new server. I'm assuming that you're using a json file which adds a default prefix as well as the guild id when the bot joins a new server. This works perfectly fine, however, if your bot is already in the server and you change how the on_guild_join event works, you will likely have to remove and then add back your bot. If you don't want to do that, you could always manually add the guild id and prefix to your json file like this:

    {
       "your guild id": "prefix"
    }
    

    Hope this answers your question