简体   繁体   中英

Discord.py json files keep resetting after restarting bot

So basically I made a bot that can change its prefix through a command, and it will only set that custom prefix to the server you are in. But when I rerun the program, it resets the prefixes back to default. For example if I set the prefix to ! from -, if I rerun the bot, it will set it back to !. Here's my code:

custom_prefixes = {}
with open('prefixes.json', 'r') as f:
  json.load(f)
default_prefixes = ['-']

async def determine_prefix(bot, message):
guild = message.guild
#Only allow custom prefixs in guild
if guild:
    return custom_prefixes.get(guild.id, default_prefixes)
else:
    return default_prefixes

client = commands.Bot(command_prefix = determine_prefix)

@client.event
async def on_ready():
  print("Bot loaded successfully")

@client.command()
@commands.guild_only()
async def setprefix(ctx, *, prefixes=""):
custom_prefixes[ctx.guild.id] = prefixes.split() or default_prefixes
with open('prefixes.json', 'w') as f:
  json.dump(custom_prefixes, f)
await ctx.send("Prefixes set!")

As you coded it, custom_prefixes will always be an empty dictionary.
You wrote json.load(f) to read your json file but you're not assigning any variable to this file content:

with open('prefixes.json') as f:
    custom_prefixes = json.load(f)

In json files, keys must be strings and can't be integers. In your code, you're getting guild.id which is an integer, so custom_prefixes.get(guild.id, default_prefixes) will always return default_prefixes :

def determine_prefix(bot, message):
    guild = message.guild
    if guild:
        return custom_prefixes.get(str(guild.id), default_prefixes)

    # The else statement is unnecessary
    return default_prefixes

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM