I wanted to make my Discord Bot have changing prefixes. By this is I mean the user (has to have administrator permissions) sets the prefix as they want it to be. The default prefix is &
but say if they want it to be !
they would use the &spr
command, like this &spr !
and the prefix would be changed to !
. That in itself works fine. However, for that to work, it needs a starting prefix so I set it up like this:
@client.event
async def on_guild_join(guild):
with open('prefixes.json', 'r') as pr:
prefixes = json.load(pr)
prefixes[str(guild.id)] = '&'
with open('prefixes.json', 'w') as pr:
json.dump(prefixes, pr, indent = 4)
It writes to a json file when the bot joins the server like this:
{
"SERVER1 ID": "&",
"SERVER2 ID": "&",
"SERVER3 ID": "&",
"SERVER4 ID": "&",
"SERVER5 ID": "&"
}
I also have a function, at the start of the code, that retrieves the prefix :
def getPrefix(client, message):
with open('prefixes.json', 'r') as pr:
prefixes = json.load(pr)
return prefixes[str(message.guild.id)]
and gives it to the client:
client = commands.Bot(command_prefix = getPrefix, help_command = None)
Everything works fine. However, I realised that because it adds the prefix to the json file when it joins the server, it doesn't add it if the bot joins the server while it's offline. This means that the bot can't respond to any commands since it doesn't have a prefix. To combat this, I created a setup event:
@client.event
async def on_message(message):
if message.author == client.user:
return
if message.content.startswith('&setup'):
with open('prefixes.json', 'r') as pr:
prefixes = json.load(pr)
prefixes[str(message.guild.id)] = '&'
with open('prefixes.json', 'w') as pr:
json.dump(prefixes, pr, indent = 4)
It adds the prefix &
to the json file as planned. However, the bot still doesn't respond to commands even though it has its prefix set in the json file. How can I make it work?