我不想为我的不和谐机器人制作一个关卡系统。当用户加入服务器时。机器人在 json 文件中正确创建新的 json 项,但是当涉及到增加用户的 exp 时,机器人不会正确添加数量,有时它会使用不同的用户 ID 创建新的 json 输入。
json 文件 :users_level.json
{
}
法典:
@client.event
async 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.event
async 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"] = 1
async def add_experience(users, user, exp):
users[user.id]["experience"] += exp
async 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}}
侃侃无极
相关分类