【问题标题】:discord.py How to add a new json key to all users one timediscord.py 如何一次性为所有用户添加一个新的 json 密钥
【发布时间】:2022-01-09 11:16:33
【问题描述】:

我有一个不和谐的机器人将用户信息保存在一个 json 文件中,如下所示: https://imgur.com/hM399Pw

所以我需要为所有用户添加一个新的 json 密钥 (name="House", value=False)。 我之前试过json.dump(house, json_file) bot 不工作。

重要信息:我有这些功能:

要开一个新的 json 账户:

async def open_account(user):
    users = await get_bank_data()
    if str(user.id) in users:
        house = users[str(user.id)]['House'] = False
        with open("main.json", 'w') as f:
            f.write(json.dumps(house))
        return False
    else:
        users[str(user.id)] = {}
        users[str(user.id)]["wallet"] = 0
        users[str(user.id)]["bank"] = 0
        users[str(user.id)]["House"] = False

读取json文件:

async def get_bank_data():
    with open("main.json", "r") as f:
        users = json.load(f)
    return users

另一个信息: user 的值是 ctx.author

【问题讨论】:

    标签: python json discord discord.py


    【解决方案1】:

    您可以编写一个 1 次方法,循环遍历 json 中的所有用户以添加新字段,如下所示:

    async def open_account(user):
        users = await get_bank_data()
    
        for user in users:
            house = user['House'] = False
            
        with open("main.json", 'w') as f:
            f.write(json.dumps(house))
    

    如果您想为服务器中的每个用户添加该字段,您可以像这样遍历所有成员以添加到您的 json 中:

    users = await get_bank_data()
    
    async for member in guild.fetch_members():
        house = users[str(member.id)]['House'] = False
    
            
    with open("main.json", 'w') as f:
        f.write(json.dumps(house))
    

    【讨论】:

      【解决方案2】:

      只需在本地运行此脚本即可将“House”键添加到main.json 文件中的每个用户

      with open("main.json", "r") as f:
          bank_data = json.load(f)
      
      # scroll through every user
      for key in bank_data.keys():
         # If there is no "House" key for a user
         if bank_data[key].get("House") is None:
             # Add the key
             bank_data[key]["House"] = False
      
      # Save the json
      with open("main.json", 'w') as f:
         f.write(json.dumps(bank_data))
      

      顺便说一句,get_bank_data 不需要是 async 函数,因为它不使用任何异步函数

      【讨论】:

      • get_bank_dataasync 因为我在每个命令中都使用它
      • @AliFGT 并没有真正解释什么
      猜你喜欢
      • 1970-01-01
      • 2021-03-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-08-15
      • 1970-01-01
      • 2019-04-13
      相关资源
      最近更新 更多