首页 > 解决方案 > discord.py 添加到服务器上的 json 文件添加

问题描述

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

{
  "496019377515266060": "$"
}

我需要它,因此当用户键入 $prefix (所需前缀)时,它将添加他们的服务器 ID 和选择的前缀(如果不存在或存在则只会更新前缀)。我已经制作了自定义前缀,但我无法做到,因此用户可以更改它们。

注意 我没有使用重写分支。

标签: pythonpython-3.xdiscorddiscord.py

解决方案


我在假设您的代码看起来或多或少像这个答案的情况下进行操作。json每当我们更改文件时,我们都可以使用标准库模块来编辑它:

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)

推荐阅读