【问题标题】:Why is it not correctly increasing a integer from json?为什么它不能正确地从 json 中增加一个整数?
【发布时间】:2020-06-10 23:51:00
【问题描述】:

我不想为我的不和谐机器人制作关卡系统。当用户加入服务器时。 bot 在 json 文件中正确地创建了一个新的 json 项,但是当涉及到增加用户的 exp 时,bot 不会正确添加数量,有时它会创建一个具有不同用户 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}}

【问题讨论】:

  • “有时”?您是否尝试过找出触发该行为的条件?
  • 我不知道,但是当您发送第一条消息时,它会给您 exp 到您在 json 列表中的用户 ID。在第二条消息中,它在 json 列表中创建一个具有相同用户 ID 和 0 exp 的新项目。在第三条消息中,两个相同的用户 ID 都有 5 个 exp 及以上,然后下一条消息不会改变任何内容

标签: python json discord


【解决方案1】:

问题在于user.id。 JSON 键总是以字符串结尾;因此,当作为 Python 字典加载时,键的类型为 str。与此相反,user.idint

要解决此问题,只需在访问 users 字典之前将所有 user.id 转换为 str

例子:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-12-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多