Search code examples
pythonjsondiscord.pyprefix

custom prefix discord.py, json file


I have looked at all the turorials, all the forums, and they all say the same thing about a custom prefix for a discord bot. I've tried it and it doesnt work. I've EVEN tried to copy-paste the code and changing the names. idk what to do now, here's my code:

def get_prefix(client, message):
    with open('prefixes.json', 'r') as f:
        prefixes = json.load(f)
    return prefixes[str(message.guild.id)]

client = commands.Bot(command_prefix = get_prefix, help_command = None)
slash = SlashCommand(client, sync_commands = True)

@client.event
async def on_ready():
    activity = discord.Game(name="!help", type=3)
    await client.change_presence(activity=activity)
    print('online !')

@client.event
async def on_guild_join(guild):
    with open('prefixes.json', 'r') as f:
        prefixes = json.load(f)

    prefixes[str(guild.id)] = '!'

    with open('prefixes.json', 'w') as f:
        json.dump(prefixes, f, indent=4)

@client.event
async def on_guild_remove(guild):
    with open('prefixes.json', 'r') as f:
        prefixes = json.load(f)

    prefixes.pop(str(guild.id))

    with open('prefixes.json', 'w') as f:
        json.dump(prefixes, f, indent=4)

and here's my error message:

Ignoring exception in on_guild_join
Traceback (most recent call last):
  File "C:\Users\ethom\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\client.py", line 343, in _run_event
    await coro(*args, **kwargs)
  File "C:\Users\ethom\PycharmProjects\discord\rocket_bot\rocket.py", line 32, in on_guild_join
    prefixes = json.load(f)
  File "C:\Users\ethom\AppData\Local\Programs\Python\Python38\lib\json\__init__.py", line 293, in load
    return loads(fp.read(),
  File "C:\Users\ethom\AppData\Local\Programs\Python\Python38\lib\json\__init__.py", line 357, in loads
    return _default_decoder.decode(s)
  File "C:\Users\ethom\AppData\Local\Programs\Python\Python38\lib\json\decoder.py", line 337, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "C:\Users\ethom\AppData\Local\Programs\Python\Python38\lib\json\decoder.py", line 355, in raw_decode
    raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

Solution

  • I have answered my own question. It says that the json file isn't found but in fact, it's not a code problem. It's a file problem, I have deleted the __pycache__ file and it suddenly worked correctly. So, my conclusion is that you have to have no directories in your bot folder.

    so, have a nice day ! I hope my response worked for you.