如何检查ID是否存在于json中

时间:2019-08-20 21:20:59

标签: python discord discord.py

每次我使用.register时,它只会继续建立帐户,而不检查ID是否存在,如果存在,它将表明帐户已经建立。

我尝试过ctx.author.id是否不在jsonfile中 并从文件中获取其他代码 太多太多添加

@bot.command()
@commands.has_permissions(manage_guild=True)
async def register(ctx):
    with open('Configs/amounts.json') as f:
        usersidlel = json.loads(f.read())
    if ctx.message.author.id not in usersidlel:
        with open('Configs/amounts.json') as f:
            data = json.loads(f.read())
            data[str(ctx.author.id)] = {}
            data[str(ctx.author.id)]['cash'] = 100
            data[str(ctx.author.id)]['bank'] = 100
            data = json.dumps(data, indent=4, sort_keys=True)
        with open('Configs/amounts.json', 'w') as f:
            f.write(data)
            await ctx.send(f"```Account Registered!```")
    else:
        await ctx.send(f"Hey {ctx.author.name} you already got an account you silly person!")

没有错误消息,只是不确定如何检查ID是否存在。

1 个答案:

答案 0 :(得分:0)

您要测试的变量与要添加的变量不同。另外,如果ctx.author.id是整数,则需要在测试之前将其转换为字符串。

也不需要两次加载JSON,只需使用第一次加载返回的数据即可。

async def register(ctx):
    with open('Configs/amounts.json') as f:
        usersidlel = json.load(f)
    if str(ctx.author.id) not in usersidlel:
        usersidlel[str(ctx.author.id)] = {'cash': 100, 'bank': 100}
        with open('Configs/amounts.json', 'w') as f:
            json.dump(usersidlel, f, indent=4, sort_keys=True)
            await ctx.send(f"```Account Registered!```")
    else:
        await ctx.send(f"Hey {ctx.author.name} you already got an account you silly person!")