通过bot命令更新json



我试图创建一个命令(<MF_add),添加一个点到成员的json值,只有管理员可以使用。这是我现在的代码:>

@client.command()
@commands.has_permissions(administrator = True)
async def MF_add(ctx, user: discord.Member):
with open ("MF Points.json", "r") as f:
users = json.load(f)   

await client.get_user(user_id)
user = client.get_user(user_id)
if user in users:
users["{user.mention}"]["points"] += 1
await ctx.message.channel.send(f"You have given {member.mention} 1 MF point.")

with open("MF Points.json", "w") as f:
json.dump(users, f, indent = 4)   

它没有给出任何错误,但也完全没有响应。

谢谢你的帮助!

首先我想建议您使用SQLLite而不是JSON。JSON不是数据库。您应该避免使用它来存储经常更改的用户数据。

关于你目前得到的,JSON的使用类似于字典。它使用键和值。我非常怀疑if语句if user in users:返回true。您应该检查(使用print语句)if语句是否正常工作。

您实际上并没有在这里创建命令,@commands.has_permissions(administrator = True)不是您用来创建新命令的。你需要在它前面加一个@bot.command():

@bot.command()
@commands.has_guild_permissions(administrator=True)
async def MF_add(ctx, user: discord.Member):
with open ("MF Points.json", "r") as f:
users = json.load(f)   

await client.get_user(user_id)
user = client.get_user(user_id)
if user in users:
users["{user.mention}"]["points"] += 1
await ctx.message.channel.send(f"You have given {member.mention} 1 MF point.")

with open("MF Points.json", "w") as f:
json.dump(users, f, indent = 4)

这将解决你的问题,我相信,现在谈谈你的程序,因为它不会像你期望的那样工作,根本(或者它只是错误):

  • client.get_user(userid)不是异步的,不需要等待
  • 你似乎从来没有在任何地方定义user_id(因为它是一个变量)
  • 你为什么想要再次获得用户?你从你的参数中获得用户,对吗?
  • ["{user.mention}"]当您查看用户的键时,它只是一个字符串,您需要在它前面添加一个f,以便它实际查找user
  • 中的提及值。
  • ctx.message.channel。send可以缩短为ctx.send
  • f"你已经给了{成员。提及1 MF点。没有定义成员值

我已经把你的大部分代码重写成我认为应该可以工作的东西:

@bot.command()
@commands.has_guild_permissions(administrator=True)
async def MF_add(ctx, user: discord.Member):
with open ("MF Points.json", "r") as f:
users = json.load(f)   

if str(user.id) in users:
users[str(user.id)] += 1
else:
users[str(user.id)] = 1

await ctx.send(f"You have given {user.mention} 1 MF point.")

with open("MF Points.json", "w") as f:
json.dump(users, f, indent = 4)

注意,不知道你想用这段代码实现什么/你想引入什么其他函数,我不太确定这是最好的方法。但是你应该能够用这个作为基础来解决问题

注意:我将键转换为字符串,因为json不喜欢int键,你可以使用int键,如果你使用自定义object_hook虽然(我会让你看看,它可能不工作寻找你的用例无论如何)

最新更新