A
A
AdvoKappa2020-06-08 21:48:34
Python
AdvoKappa, 2020-06-08 21:48:34

KeyError: 293396418834464768 why is this happening?

@bot.event
async def on_message(message):
    await bot.process_commands(message)
    if message.author == bot.user:
        return

    with open('users.json', 'r') as f:
        users = json.load(f)

        async def update_data(users, user):
            if not str(user.id) in users:
                users[str(user.id)] = {}
                users[str(user.id)]['experience'] = 0
                users[str(user.id)]['level'] = 1

        await update_data(users, message.author)
        await add_experience(users, message.author, 5)
        await level_up(users, message.author, message.channel)

    with open('users.json','w') as f:
        json.dump(users, f)

async def add_experience(users, user, exp):
    users[str(user.id)]['experience'] += exp

async def level_up(users, user, channel):
    experience = users[str(user.id)]['experience']
    lvl_start = users[str(user.id)]['level']
    lvl_end = int(experience * (1/10))

    if lvl_start < lvl_end:
        await channel.send(":thumbsup: {}, вы повысились до {} уровня! :thumbsup: ".format(user.mention, lvl_end))
        users[user.id]["level"] = lvl_end


The error is this:
Ignoring exception in on_message
Traceback (most recent call last):
  File "C:\Users\stas\AppData\Local\Programs\Python\Python38-32\lib\site-packages\discord\client.py", line 312, in _run_event
    await coro(*args, **kwargs)
  File "level_system.py", line 44, in on_message
    await level_up(users, message.author, message.channel)
  File "level_system.py", line 59, in level_up
    users[user.id]["level"] = lvl_end
KeyError: 347340011580162058

Answer the question

In order to leave comments, you need to log in

3 answer(s)
G
galaxy, 2020-06-08
@AdvoKappa

users[str(user.id)]["level"] = lvl_end

S
soremix, 2020-06-08
@SoreMix

There is no such key.

D
Dr. Bacon, 2020-06-08
@bacon

You have already been explained how many times, but you have it again users[user.id], then users[str(user.id)]Go and learn the basics first, then write bots, also on asyncio
Threat as soon as more than one body starts using your code (if it comes to that at all), you have a file 'users.json' will turn into unreadable mess

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question