繁体   English   中英

如何不断检查 JSON 文件是否在 Python 中更新? - 不和谐.py

[英]How can I constantly check if a JSON file is updated in Python? - discord.py

嗨,我正在尝试在我的 discord.py 机器人中实现一个货币系统,但是当机器人为用户创建一个帐户时,它不会不断更新,我需要重新启动机器人以检查是否有该用户的帐户。 我想知道如何在 python 中不断更新 json 文件。 我的代码:

f = open('MainBank.json')
banks = json.load(f)

client = discord.Client
client = commands.Bot(command_prefix = ">", case_insensitive=True)

@client.command()
async def bal(ctx):
    if f"{ctx.author.id}" in banks:
        print("-_-")
    else:
        user_detail = {f'{ctx.author.id}': [{'wallet':10, 'bank': 10}]}
        with open("MainBank.json", "r+") as file:
            data = json.load(file)
            data.update(user_detail)
            file.seek(0)
            json.dump(data, file)

    

    wallet_amt = banks[f'{ctx.author.id}'][0]["wallet"]
    bank_amt = banks[f'{ctx.author.id}'][0]["bank"]

    em = discord.Embed(title = f"{ctx.author.name}'s balance")
    em.add_field(name = "Wallet", value = wallet_amt)
    em.add_field(name = "Bank", value = bank_amt)
    await ctx.send(embed = em)

@client.command()
async def beg(ctx):
    earnings = random.randrange(150)
    banks[f'{ctx.author.id}'][0]["wallet"]+=earnings
    with open('MainBank.json', 'w') as file:
        json.dump(banks, file)
    await ctx.send(f"Someone gave you {earnings}")

当您检查用户帐户时,您使用了banks变量,您只在代码开始时设置一次,之后永远不会更新。 这意味着您对文件所做的任何更改都不会反映在banks

在检查用户帐户是否在其中之前,您需要执行与加载 json 文件的else语句类似的操作。

...
@client.command()
async def bal(ctx):
    with open("MainBank.json", "r+") as file:
        data = json.load(file) 
    if f"{ctx.author.id}" in data:
        print("-_-")
    else:
        user_detail = {f'{ctx.author.id}': [{'wallet':10, 'bank': 10}]}
        with open("MainBank.json", "r+") as file:
            data = json.load(file)
            data.update(user_detail)
            file.seek(0)
            json.dump(data, file)
...

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM