带有JSON数据库的Python Discord bot命令

时间:2020-06-07 14:54:36

标签: json python-3.x discord.py discord.py-rewrite

所以我正在创建一个命令! 当您在聊天中输入该分数时,它将更新数据库中的成员分数。 数据库看起来像这样

{
  "person": "epikUbuntu"
  "score": "22"
}

我该怎么做呢?

编辑: 如果我不清楚,我是说我会继续做它的python部分吗?

1 个答案:

答案 0 :(得分:0)

Python中的JSON对象像字典一样工作。

您可以编写新词典并将其保存:

data = {"foo": "bar"}

with open("file.json", "w+") as fp:
    json.dump(data, fp, sort_keys=True, indent=4) # kwargs for beautification

您可以从文件加载数据(这将用于更新文件):

with open("file.json", "r") as fp:
    data = json.load(fp) # loading json contents into data variable - this will be a dict

data["foo"] = "baz" # updating values
data["bar"] = "foo" # writing new values

with open("file.json", "w+") as fp:
    json.dump(data, fp, sort_keys=True, indent=4)

Discord.py示例:

import os # for checking the file exists

def add_score(member: discord.Member, amount: int):
    if os.path.isfile("file.json"):
        with open("file.json", "r") as fp:
            data = json.load(fp)
        try:
            data[f"{member.id}"]["score"] += amount
        except KeyError: # if the user isn't in the file, do the following
            data[f"{member.id}"] = {"score": amount} # add other things you want to store
    else:
        data = {f"{member.id}": {"score": amount}}
    # saving the file outside of the if statements saves us having to write it twice
    with open("file.json", "w+") as fp:
        json.dump(data, fp, sort_keys=True, indent=4) # kwargs for beautification
   # you can also return the new/updated score here if you want

def get_score(member: discord.Member):
    with open("file.json", "r") as fp:
        data = json.load(fp)
    return data[f"{member.id}"]["score"]

@bot.command()
async def cmd(ctx):
    # some code here
    add_score(ctx.author, 10)
    # 10 is just an example
    # you can use the random module if you want - random.randint(x, y)
    await ctx.send(f"You now have {get_score(ctx.author)} score!")

参考: