discord.py添加到服务器上的json文件中添加

问题描述:

我希望我的机器人在对名为settings.json的JSON文件执行$ prefix(所需的前缀)时添加服务器ID和选择的前缀。我在下面有这个JSON文件的示例。

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": "$"
}

我需要它,因此当用户键入$ prefix(所需前缀)时,它将添加其服务器ID和选择的前缀(如果不存在或不存在)将仅更新前缀。我可以做自定义前缀,但是我做不到,因此用户可以更改它们。

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.

我正在假设您的代码或多或少像此答案。每当我们更改文件时,我们都可以使用标准库 json 模块编辑文件:

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)