Discord.py Variables Not Constant Throughout The Code
I am currently developing a bot using discord.py and in this case using a JSON file to store the bots prefixes for each server that it is in. ( + is the bots default prefix ) With
Solution 1:
Your code makes no sense to me in many places, because you use ctx
in a message
event, which is not possible at first. Also, when copying the code, I get an error with prefixes = prefix
, so it is questionable why this supposedly works for you.
Your on_guild_join
also makes no sense to me, because everyone has the default prefix. The event may be relevant for your changeprefix
command, but that can be done better.
I rewrote your changeprefix
command a bit and adjusted your on_message
event.
Take a look at the following code:
@bot.eventasyncdefon_message(message):
if message.content.startswith("What is the prefix for this guild?"):
withopen('prefix.json', 'r', encoding='utf-8') as fp:
custom_prefixes = json.load(fp)
try:
prefix = custom_prefixes[f"{message.guild.id}"]
await message.channel.send(f'Hi my prefix for this server is **{prefix}**')
except KeyError:
returnawait message.channel.send("You have not set a new prefix.") # No JSON entryawait bot.process_commands(message)
@bot.command()asyncdefsetprefix(ctx, prefixes: str):
withopen('prefix.json', 'r', encoding='utf-8') as fp:
custom_prefixes = json.load(fp)
try:
custom_prefixes[f"{ctx.guild.id}"] = prefixes # If the guild.id already existsexcept KeyError: # If there is no JSON entry
new = {ctx.guild.id: prefixes} # New prefix with command input
custom_prefixes.update(new) # Add guild.id and prefixawait ctx.send(f"Prefix set to: `{prefixes}`")
withopen('prefix.json', 'w', encoding='utf-8') as fpp:
json.dump(custom_prefixes, fpp, indent=2)
As your on_guild_join
event also contains errors we have to determine the prefix in a different way. We can achieve that if we append the set prefix
to the default one.
Have a look at the following code:
defdetermine_prefix(bot, msg):
guild = msg.guild
base = [DEFAULT_PREFIX]
withopen('prefix.json', 'r', encoding='utf-8') as fp: # Open the JSON
custom_prefixes = json.load(fp) # Load the custom prefixesif guild: # If the guild existstry:
prefix = custom_prefixes[f"{guild.id}"] # Get the prefix
base.append(prefix) # Append the new prefixexcept KeyError:
passreturn base
[...](command.prefix = determine_prefix) # Where you defined your bot
Post a Comment for "Discord.py Variables Not Constant Throughout The Code"