discord.py add to json file on server add

泄露秘密 提交于 2020-01-06 05:18:06

问题


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:


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)


来源:https://stackoverflow.com/questions/52612358/discord-py-add-to-json-file-on-server-add

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!