A
A
AdvoKappa2020-06-05 17:35:38
Python
AdvoKappa, 2020-06-05 17:35:38

Discord.ext.commands.errors.CommandInvokeError: Command raised an exception: KeyError: '293396418834464768', what should I do?

@bot.command(pass_context = True)
async def Test(ctx):
    if 'coins' > 'coinss':
        coins = users[str(user.id)]['coins']
        coinss = users[str(user.id)]['coinss']

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

    await add_coins(users, ctx.author, 50000)
    await coinss(users, ctx.author)

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

async def add_coins(users, user, coin):
    users[str(user.id)]['coins'] += coin

async def coinss(users, user):
    users[str(user.id)]['15000']

The error is this:
Ignoring exception in command Test:
Traceback (most recent call last):
  File "C:\Users\stas\AppData\Local\Programs\Python\Python38-32\lib\site-packages\discord\ext\commands\core.py", line 83, in wrapped
    ret = await coro(*args, **kwargs)
  File "save.py", line 26, in Test
    await add_coins(users, ctx.author, 50000)
  File "save.py", line 33, in add_coins
    users[str(user.id)]['coins'] += coin
KeyError: '293396418834464768'

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "C:\Users\stas\AppData\Local\Programs\Python\Python38-32\lib\site-packages\discord\ext\commands\bot.py", line 892, in invoke
    await ctx.command.invoke(ctx)
  File "C:\Users\stas\AppData\Local\Programs\Python\Python38-32\lib\site-packages\discord\ext\commands\core.py", line 797, in invoke
    await injected(*ctx.args, **ctx.kwargs)
  File "C:\Users\stas\AppData\Local\Programs\Python\Python38-32\lib\site-packages\discord\ext\commands\core.py", line 92, in wrapped
    raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: KeyError: '293396418834464768'

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Maxim Nevzorov, 2020-06-05
@AdvoKappa

The error KeyErrormeans that the specified key does not exist in the specified dictionary.

What to do?

Update the dictionary with the required key if it doesn't exist:
async def add_coins(users, user, coin):
    if str(user.id) not in users:
        users[str(user.id)]['coins'] = 0
    users[str(user.id)]['coins'] += coin

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question