Rensjuh
Rensjuh

Reputation: 71

How to get the prefix of a server when the bot is mentioned? discord.py

What im trying to do: I have a custom prefix system similar to this one: discord.py prefix command And this is my event for when my bot is mentioned:

@client.event
async def on_message(message):
  if client.user.mentioned_in(message):

    embed=discord.Embed(title=f"Hello! my prefix is `{prefix}`")
   
    await message.channel.send(embed=embed)

  await client.process_commands(message)

So i want my bot to respond with the prefix for that server.

My problem: I don't know how i can read the json file and get the prefix.

Upvotes: 1

Views: 2716

Answers (1)

GGberry
GGberry

Reputation: 945

To add custom prefixes to your bot, you can store the prefix data in a JSON file. You should create a file named prefixes.json and 3 commands/events: An event to set a default prefix when the bot joins a server, an event to remove the prefix information from the prefixes.json file, and also a command to change the bot's prefix.

Here is how you can write the first event: the event that defines a default prefix when the bot joins a guild:

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

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

And this is a way you can write the event to remove the prefix data from the JSON file when the bot is removed from a server:

@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 finally, here is how you can define the function to change the prefix of the bot. The command will be named changeprefix, and you can use it by typing [prefix]changeprefix ( replace [prefix] to your bot's prefix ). :

async def changeprefix(ctx, prefix):
    with open('prefixes.json', 'r') as f:
        prefixes = json.load(f)
    prefixes[str(ctx.guild.id)] = prefix

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

You'll also need a command to find the prefix corresponding to the guild your bot is in. It's a simple function you can define just like this:

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

Now, the last step to this is to integrate those four commands into your bot variable you defined to run other commands. Here is how you should change the prefix statement:

client = commands.Bot(command_prefix=get_prefix)

Upvotes: 1

Related Questions