discord.py add to json file on server add

2019-08-20 19:03发布

I am wanting my bot to add the server ID and prefix of choice when they do $prefix (desired prefix) to the JSON file called settings.json. I have an example of this JSON file below.

{
  "496019377515266060": "$"
}

I need it so when users type $prefix (desired prefix) it will add their server ID and the prefix of choice if not there or if it is there it will just update the prefix. I have got as far as making custom prefixes but I cannot make it so users can change them.

NOTE I am not using the rewrite branch.

1条回答
霸刀☆藐视天下
2楼-- · 2019-08-20 19:56

I'm operating under the assumption that your code looks more or less like this answer. We can use the standard library json module to edit the file whenever we change it:

from discord import commands
import json

with open("prefixes.json") as f:
    prefixes = json.load(f)
default_prefix = "!"

def prefix(bot, message):
    id = message.server.id
    return prefixes.get(id, default_prefix)

bot = commands.Bot(command_prefix=prefix)

@bot.command(name="prefix", pass_context=True)
async def _prefix(ctx, new_prefix):
    # Do any validations you want to do
    prefixes[ctx.message.server.id] = new_prefix
    with open("prefixes.json", "w") as f:
        json.dump(prefixes, f)
查看更多
登录 后发表回答