discord.py添加到服务器上的json文件中添加 [英] discord.py add to json file on server add

查看:87
本文介绍了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)

这篇关于discord.py添加到服务器上的json文件中添加的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆