我不想为我的不和谐机器人制作一个关卡系统。当用户加入服务器时。机器人在 json 文件中正确创建新的 json 项,但是当涉及到增加用户的 exp 时,机器人不会正确添加数量,有时它会使用不同的用户 ID 创建新的 json 输入。json 文件 :users_level.json{}法典:@client.eventasync def on_member_join(member): with open("./data/users_level.json", "r") as f: users = json.load(f) await update_data(users, member) with open("./data/users_level.json", "w") as f: json.dump(users, f)@client.eventasync def on_message(message): with open("./data/users_level.json", "r") as f: users = json.load(f) if message.author.bot: return else: await update_data(users, message.author) number = random.randint(5, 10) await add_experience(users, message.author, number) await level_up(users, message.author, message.channel) with open("./data/users_level.json", "w") as f: json.dump(users, f)async def update_data(users, user): if not user.id in users: users[user.id] = {} users[user.id]["experience"] = 0 users[user.id]["level"] = 1async def add_experience(users, user, exp): users[user.id]["experience"] += expasync def level_up(users, user, channel): experience = users[user.id]["experience"] lvl_start = users[user.id]["level"] lvl_end = int(experience ** (1/4)) if lvl_start < lvl_end: await channel.send(f":tada: Congrats {user.mention}, you levelled up to level {lvl_end}!") users[user.id]["level"] = lvl_end这是 json 文件在使用同一帐户发送一些消息后的外观:{"676573403230240813": {"experience": 9, "level": 1}, "676573403230240813": {"experience": 10, "level": 1}}
1 回答
侃侃无极
TA贡献2051条经验 获得超10个赞
问题在于 。JSON密钥总是以字符串结束;因此,当作为Python字典加载时,键的类型为 。与此相反,是一个 .user.id
str
user.id
int
要解决此问题,只需在访问字典之前将所有转换为。user.id
str
users
例:
async def update_data(users, user): uid = str(user.id) if not uid in users: users[uid] = {} users[uid]["experience"] = 0 users[uid]["level"] = 1
添加回答
举报
0/150
提交
取消