'Need to understand more about prefixes.json in discord.py
My Prefix String isn't working? Mainly line 13. Any fix/suggestions? I have a prefixes.json file. What should I try? Should I use a database? I might have written message.guild wrong. YT video
import discord
from discord.ext import commands
import json
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)
client.remove_command("help")
@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)
@client.event
async def on_ready():
print("Sir yes sir")
@client.command()
@commands.has_permissions(administrator = True)
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)
await ctx.send(f"The prefix was changed to {prefix}")
@client.event
async def on_message(msg):
try:
if msg.mentions[0] == client.user:
with open("prefixes.json", "r") as f:
prefixes = json.load(f)
pre = prefixes[str(msg.guild.id)] = prefix
await msg.channel.send(f"My prefix for this server is {pre}")
except:
pass
await client.process_commands(msg)
This error:
File "D:\Discord Bots\8's Server Bot\Bot.py", line 13, in get_prefix
return prefixes[str(message.guild.id)]
KeyError: '960030765704417351'
Solution 1:[1]
This happens when the key is not in the json file. Try removing and adding your bot to the server when it is running. If that does not work, Try adding the the line manually. If it still does not work, it means that the get_prefix is not able to access the file properly.
Also make another event function, on_guild_remove to remove the key from the json file in case the bot is removed from a guild. More information here.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Sandy |
