Python 为什么它不能正确地从json增加整数?
我不想为我的discord机器人制作一个levelsystem。当用户加入服务器时。bot在json文件中正确地创建了一个新的json项,但是当需要增加用户的exp时,bot不会正确地添加该量,有时它会使用不同的userid创建一个新的json输入 json文件Python 为什么它不能正确地从json增加整数?,python,json,discord,Python,Json,Discord,我不想为我的discord机器人制作一个levelsystem。当用户加入服务器时。bot在json文件中正确地创建了一个新的json项,但是当需要增加用户的exp时,bot不会正确地添加该量,有时它会使用不同的userid创建一个新的json输入 json文件users\u level.json: { } 代码: 问题在于user.id。JSON键总是以字符串结束;因此,当作为Python字典加载时,键的类型将为str。与此相反,user.id是一个int 要解决这个问题,只需在访问user
users\u level.json
:
{
}
代码:
问题在于
user.id
。JSON键总是以字符串结束;因此,当作为Python字典加载时,键的类型将为str
。与此相反,user.id
是一个int
要解决这个问题,只需在访问users
字典之前将所有user.id
强制转换为str
例如:
async def update_数据(用户,用户):
uid=str(user.id)
如果用户中没有uid:
用户[uid]={}
用户[uid][“体验”]=0
用户[uid][“级别”]=1
“有时”?你有没有试着弄清楚是什么条件触发了这种行为?我不知道,但是当你发送第一条消息时,它会给你json列表中用户id的exp。在第二条消息中,它在json列表中创建了一个具有相同userid和0 exp的新项。在第三条消息中,两个相同的userid都有5 exp,然后下一条消息不会更改任何内容
@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
{"676573403230240813": {"experience": 9, "level": 1}, "676573403230240813": {"experience": 10, "level": 1}}