-3

so I have this code(discord.py):

@client.command()
async def buyrole(ctx, role: int):
    print(serverdata[f'{ctx.guild}'][role].split(' '))
    print(int(serverdata[f'{ctx.guild}'][role].split(' ')[1]))
    for i in range(baldata[f'{ctx.guild}'].__len__()):
        if(i):
            if(f'{str(ctx.message.author).split("#")[0]}' in baldata[f'{ctx.guild}'][i]):
                userbal = int(baldata[int(baldata[f'{ctx.guild}'][i].split('#')[1].split(' ')[1])])
                if(userbal > int(serverdata[f'{ctx.guild}'][role].split(' ')[1])):
                    buy = discord.utils.get(ctx.guild.roles, name=serverdata[f'{ctx.guild}'][role].split(' ')[0])
                    if(not buy in ctx.message.author.roles):
                            add = int(baldata[f'{ctx.guild}'][i].split('#')[1].split(' ')[1]) - int(serverdata[f'{ctx.guild}'][role].split(' ')[1])
                            baldata[f'{ctx.guild}'][i] = f'{ctx.message.author} {add}'
                            await ctx.message.author.add_roles(buy)
                            await ctx.send(f'role {buy} purchased')
                    else:
                        await ctx.send('you already have that role')
                else:
                    await ctx.send('you do not have enough money to buy that role, keep being active!')

and I get this error and I don't know what it means and how to fix it:

Ignoring exception in command buyrole:
Traceback (most recent call last):
  File "C:\Users\roeyd\PycharmProjects\roleShop\venv\lib\site-packages\discord\ext\commands\core.py", line 85, in wrapped
    ret = await coro(*args, **kwargs)
  File "C:/Users/roeyd/PycharmProjects/roleShop/main.py", line 97, in buyrole
    userbal = int(baldata[int(baldata[f'{ctx.guild}'][i].split('#')[1].split(' ')[1])])
KeyError: 20

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

Traceback (most recent call last):
  File "C:\Users\roeyd\PycharmProjects\roleShop\venv\lib\site-packages\discord\ext\commands\bot.py", line 902, in invoke
    await ctx.command.invoke(ctx)
  File "C:\Users\roeyd\PycharmProjects\roleShop\venv\lib\site-packages\discord\ext\commands\core.py", line 864, in invoke
    await injected(*ctx.args, **ctx.kwargs)
  File "C:\Users\roeyd\PycharmProjects\roleShop\venv\lib\site-packages\discord\ext\commands\core.py", line 94, in wrapped
    raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: KeyError: 20

thank you so so much for helping I really appreciate it I am new and having some trouble so helping is incredible

Roey Doron
  • 31
  • 2
  • Does this answer your question? [I'm getting Key error in python](https://stackoverflow.com/questions/10116518/im-getting-key-error-in-python) – mkrieger1 Jan 27 '21 at 17:03
  • Solution: either ensure that the key you want to look up exists, or do not look up keys that do not exist, or handle the exception that is raised when looking up a key that does not exist. – mkrieger1 Jan 27 '21 at 17:04

2 Answers2

0

A key error occurs whenever you query a dictionary for a key and the entry does not exist so whats happening is in line 97 whenever you query the users balance

userbal = int(baldata[int(baldata[f'{ctx.guild}'][i].split('#')[1].split(' ')[1])])

(I can't be more specific cus that code is a pain to read.) you query a dictionary with the key 20 and the key does not exist so it raises an exception

0

In order to determine which exact part of that code is causing the error, break it up into separate lines, like so (except use actual descriptive variable names rather than a, b, etc):

a = baldata[f'{ctx.guild}']
b = a[i]
c = b.split('#')
d = c[1]
e = d.split(' ')
f = e[1]
g = int(f)
h = baldata[g]
userbal = int(h)

Having a whole bunch of code chained together like you did makes it really hard to read and debug. All of your code is filled with chained, dense statements like the erroring one, and thus it's going to be really difficult to understand exactly what's causing the error. If you replace that line with the above code, it'll be obvious where the actual error is happening.

However I recommend going through all your code and replacing those long chains with more broken-up statements, so that your code is readable. Currently it's next to impossible to understand. If you come back to it later it's going to take you a long time to figure out what it does. Code is meant to be executed by a computer, sure, but your main focus should be readability rather than density.

After looking at your broken-up code, the two parts that seem like the culprits are the following lines:

a = baldata[f'{ctx.guild}']
...
h = baldata[g]
...

So, if that's the case, I'd focus on why the value is being set to 20, and/or why it's not in baldata.

Random Davis
  • 6,662
  • 4
  • 14
  • 24