检查字符串是否在 json 文件中
Checking if a string is in a json file
我目前正在为市场服务器开发信誉命令,但每当我 运行 命令时,它都找不到作者 ID,我不确定为什么。
@bot.command()
async def rep(ctx):
with open('rep.json') as data_file:
data = json.load(data_file)
print(data)
if ctx.author.id not in data:
new = {
f"{ctx.author.id}": {
"rep": 0
}
}
with open('rep.json', 'w') as outfile:
json.dump(new, outfile, sort_keys=True, indent=4)
added = discord.Embed(title="Added to database", color=0x38dd22, description="You have been successfully added to our database, you may run this command again.")
added.set_footer(text=f"Requested by {ctx.author} • {datetime.now().strftime('%H:%M%p')}", icon_url=ctx.author.avatar_url)
await ctx.send(embed=added)
else:
repu = json.loads(open("rep.json").read())[f"{ctx.author.id}"]["rep"]
rep = discord.Embed(title="Reputation", color=0x38dd22, description=f"You currently have {repu} reputation.")
rep.set_footer(text=f"Requested by {ctx.author} • {datetime.now().strftime('%H:%M%p')}", icon_url=ctx.author.avatar_url)
await ctx.send(embed=rep)
rep.json:
{
"702221444796383454": {
"rep": 0
}
}
这就是命令returns:
{'702221444796383454': {'rep': 0}}
感谢您的贡献。
由于 id
是 int
类型,您不能将它与 str
对象(即 json 文件中的 ID)进行比较。
尝试将您的 ctx.author.id
转换为 str
对象,然后您应该能够检查它是否在 json 文件中。
我目前正在为市场服务器开发信誉命令,但每当我 运行 命令时,它都找不到作者 ID,我不确定为什么。
@bot.command()
async def rep(ctx):
with open('rep.json') as data_file:
data = json.load(data_file)
print(data)
if ctx.author.id not in data:
new = {
f"{ctx.author.id}": {
"rep": 0
}
}
with open('rep.json', 'w') as outfile:
json.dump(new, outfile, sort_keys=True, indent=4)
added = discord.Embed(title="Added to database", color=0x38dd22, description="You have been successfully added to our database, you may run this command again.")
added.set_footer(text=f"Requested by {ctx.author} • {datetime.now().strftime('%H:%M%p')}", icon_url=ctx.author.avatar_url)
await ctx.send(embed=added)
else:
repu = json.loads(open("rep.json").read())[f"{ctx.author.id}"]["rep"]
rep = discord.Embed(title="Reputation", color=0x38dd22, description=f"You currently have {repu} reputation.")
rep.set_footer(text=f"Requested by {ctx.author} • {datetime.now().strftime('%H:%M%p')}", icon_url=ctx.author.avatar_url)
await ctx.send(embed=rep)
rep.json:
{
"702221444796383454": {
"rep": 0
}
}
这就是命令returns:
{'702221444796383454': {'rep': 0}}
感谢您的贡献。
由于 id
是 int
类型,您不能将它与 str
对象(即 json 文件中的 ID)进行比较。
尝试将您的 ctx.author.id
转换为 str
对象,然后您应该能够检查它是否在 json 文件中。