Search code examples
pythondiscorddiscord.pyprefix

Why I've this error with my prefix in discord.py


I recently started to develop a discord bot in python and there is an error that I do not understand

What I want: I want to be able to have as a prefix the mention of the bot and a prefix which is drawn from a JSON file

My problem: I've this error:

Traceback (most recent call last):
  File "C:\Users\baron_btjit4i\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\client.py", line 343, in _run_event
    await coro(*args, **kwargs)
  File "C:\Users\baron_btjit4i\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\bot.py", line 942, in on_message
    await self.process_commands(message)
  File "C:\Users\baron_btjit4i\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\bot.py", line 938, in process_commands
    ctx = await self.get_context(message)
  File "C:\Users\baron_btjit4i\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\bot.py", line 875, in get_context
    raise TypeError("Iterable command_prefix or list returned from get_prefix must "
TypeError: Iterable command_prefix or list returned from get_prefix must contain only strings, not function

Here's my code:

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

client = commands.Bot(command_prefix = when_mentioned_or(get_prefix), description = "Bot by Cucus#0001",intents=intents)

I don't understand because my function get_prefix() return a string 😕

Can you please help me ?


Solution

  • You use the when_mentioned_or function incorrectly.

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

    And then use can use it:

    client = commands.Bot(command_prefix=get_prefix, description="Bot by Cucus#0001",intents=intents)