#๐Ÿ”’ Help with command

226 messages ยท Page 1 of 1 (latest)

tall belfry
#

..

bold shardBOT
#

@tall belfry

Python help channel opened

Remember to:

  • Ask your Python question, not if you can ask or if there's an expert who can help.
  • Show a code sample as text (rather than a screenshot) and the error message, if you've got one.
  • Explain what you expect to happen and what actually happens.

:warning: Do not pip install anything that isn't related to your question, especially if asked to over DMs.

tall belfry
#

The Error:

#

The code:

def save_warn(ctx, member: discord.Member):
    with open('warns.json', 'r') as f:
         warns = json.load(f)

         warns[str(member.id)] += 1

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

def remove_warn(ctx, member: discord.Member, amount: int):
    with open('warns.json', 'r') as f:
         warns = json.load(f)

         warns[str(member.id)] -= amount

    with open('warns.json', 'w') as f:
         json.dump(warns, f)
    
def warns_check(member: discord.Member):
    with open('warns.json', 'r') as f:
         warns = json.load(f)

         warns[str(member.id)]
    return warns

@bot.command()
@commands.has_permissions(kick_members=True)
async def warn(ctx, member: discord.Member, *, reason):
      save_warn(ctx, member)
      dm = await bot.fetch_user(member.id)
      em=discord.Embed(title="Warning", description=f"Server: {ctx.guild.id}\nReason: {reason}"
      await dm.send(embed=em)

@bot.command()
@commands.has_permissions(kick_members=True)
async def warnings(ctx, member: discord.Member):
      warns = warns_check(member)
      await ctx.send(f"{member.name} has {warns} warnings.")

@bot.command()
@commands.has_permissions(kick_members=True)
async def rmwarn(ctx, member: discord.Member, amount: int):
      remove_warn(ctx, member, amount)
      await ctx.send(f"Removed {amount} warnings from {member.name}!")```
edgy fossil
#

I believe it is the formatting of the json please have a look at the structure of the json files

tall belfry
#

Alright, thanks!

#

Tbh i dont know what is the error or how to fix it

edgy fossil
#

look at your json file it is not in json file formatting missing comma or bracket or something likle that

#

json files

tall belfry
#

ohhh i understand i guess

edgy fossil
tall belfry
#

Im getting a mental breakdown๐Ÿฅฒ

#

Tbh i dont know what i've done but idk what to fix or to look for i fixed the json file

plush nest
tall belfry
#

I am on a call with my gf

plush nest
#

ok

plush nest
tall belfry
#

There u go

plush nest
#
def warns_check(member: discord.Member):
    with open('warns.json', 'r') as f:
         warns = json.load(f)

         # Added a default value (an empty list) which is
         # returned when the user has no warnings
         warns.get(str(member.id), [])
    return warns
tall belfry
#

Ima try that 1 sec

tall belfry
#

Why does it only return the {} ?

plush nest
#

How do you store your warnings? As a list as I assumed, or do you use a dictionary?

tall belfry
#

i use the file to store it

#

the warns.json

plush nest
#

In other words, what is the return type of the function I edited?

tall belfry
#

Uhh

#

Idk tbh im kinda confused rn

#

Like im pretty new to python but i got the basic knowlegde and my friend bascially teaches me if i need help and he told me to do it in this way and it will work fine

plush nest
#

does dm feature work?

tall belfry
#

I'll change it once i got the code working, but it does not work as of right now.

plush nest
#

I just found out you store warnings as a number not a list

#
warns.get(str(member.id), 0)
#

This should work

tall belfry
#

lemme try

plush nest
# tall belfry

Share this error as text instead of screenshot. I want to tell you something.

tall belfry
#

i cant due to me being on mobile

plush nest
#

What app are u using to code?

tall belfry
#

spck editor

#

Its for mobile

#

But back to the code it still returns the {}

plush nest
tall belfry
#

just basically an empty file or what should i put in it?

plush nest
#

remove the file

tall belfry
#

yes

plush nest
#

but then you will get an error

#

FileNotFoundError

#

Just try one last time to copy the error text

tall belfry
#

File "/home/container/.local/lib/python3.13/site -packages/discord/ext/commands/core.py", line 235, in wrapped

ret = await coro(*args, **kwargs)

File "/home/container/main.py", line 652, in war nings

warns warns_check(member)

File "/home/container/main.py", line 55, in warn s_check

warns [str(member.id)]

KeyError: '1244794665769766967'

The above exception was the direct cause of the fo llowing exception:

Traceback (most recent call last):

File "/home/container/.local/lib/python3.13/site -packages/discord/ext/commands/bot.py", line 1366, in invoke

await ctx.command.invoke(ctx)

File "/home/container/.local/lib/python3.13/site

-packages/discord/ext/commands/core.py", line 1029 , in invoke

await injected(*ctx.args, **ctx.kwargs) # typ e: ignore

File "/home/container/.local/lib/python3.13/site -packages/discord/ext/commands/core.py", line 244, in wrapped

raise Command Invoke Error (exc) from exc discord.ext.commands.errors.Command InvokeError: Co mmand raised an exception: KeyError: '124479466576 9766967'

#

Like this?

plush nest
#

very close to what I want

#

!code

tall belfry
#
File "/home/container/.local/lib/python3.13/site -packages/discord/ext/commands/core.py", line 235, in wrapped

ret = await coro(*args, **kwargs)

File "/home/container/main.py", line 652, in war nings

warns warns_check(member)

File "/home/container/main.py", line 55, in warn s_check

warns [str(member.id)]

KeyError: '1244794665769766967'

The above exception was the direct cause of the fo llowing exception:

Traceback (most recent call last):

File "/home/container/.local/lib/python3.13/site -packages/discord/ext/commands/bot.py", line 1366, in invoke

await ctx.command.invoke(ctx)

File "/home/container/.local/lib/python3.13/site

-packages/discord/ext/commands/core.py", line 1029 , in invoke

await injected(*ctx.args, **ctx.kwargs) # typ e: ignore

File "/home/container/.local/lib/python3.13/site -packages/discord/ext/commands/core.py", line 244, in wrapped

raise Command Invoke Error (exc) from exc discord.ext.commands.errors.Command InvokeError: Co mmand raised an exception: KeyError: '124479466576 9766967'```
#

There we gi

#

Go

plush nest
#

without the py since this is not entirely python code

tall belfry
#
File "/home/container/.local/lib/python3.13/site -packages/discord/ext/commands/core.py", line 235, in wrapped

ret = await coro(*args, **kwargs)

File "/home/container/main.py", line 652, in war nings

warns warns_check(member)

File "/home/container/main.py", line 55, in warn s_check

warns [str(member.id)]

KeyError: '1244794665769766967'

The above exception was the direct cause of the fo llowing exception:

Traceback (most recent call last):

File "/home/container/.local/lib/python3.13/site -packages/discord/ext/commands/bot.py", line 1366, in invoke

await ctx.command.invoke(ctx)

File "/home/container/.local/lib/python3.13/site

-packages/discord/ext/commands/core.py", line 1029 , in invoke

await injected(*ctx.args, **ctx.kwargs) # typ e: ignore

File "/home/container/.local/lib/python3.13/site -packages/discord/ext/commands/core.py", line 244, in wrapped

raise Command Invoke Error (exc) from exc discord.ext.commands.errors.Command InvokeError: Co mmand raised an exception: KeyError: '124479466576 9766967'```
#

Like this?

plush nest
#

yes

#

I see this is the error from earlier

tall belfry
#

Its the one from the picture you replied on

plush nest
#

I am interested in this portion ```
File "/home/container/.local/lib/python3.13/site -packages/discord/ext/commands/core.py", line 235, in wrapped
ret = await coro(*args, **kwargs)
File "/home/container/main.py", line 652, in war nings
warns warns_check(member)
File "/home/container/main.py", line 55, in warn s_check
warns [str(member.id)]
KeyError: '1244794665769766967'

#

This part specifically ```
File "/home/container/main.py", line 55, in warn s_check
warns [str(member.id)]
KeyError: '1244794665769766967'

tall belfry
#

yes

plush nest
#

It says there was a KeyError in line number 55 in warns_check function

#

Do you see how errors can be helpful?

#

The part above tells you what happened before that. The part below tells you what other error occured as a result of this error.

#

It also tells you which file the function is located in

tall belfry
#

yes, but what is a KeyError ?

plush nest
#

A KeyError is an error that occurs when you access a missing data. Here is an example

#

!e ```py
warns = {"user1": 5}
print(warns["user1"])
print(warns["user2"])

bold shardBOT
tall belfry
#

I understand so the KeyError in my code is that its looking for the data (my user id) in warns.json but it cant find it so it returns the error right?

plush nest
#

The first print ran correctly because the key "user1" is present in the dictionary. The second one failed and gave a key error

#

You can always check if a key is present in the dictionary before using it.

if "user2" in warns:
  warns["user2"] += 1
#

Or you can use .get method (as I did) to get a default value when the key is missing. ```py
warns = {"user1": 5}
print(warns.get("user2", 0)) # prints 0

#

These are 2 possible fixes you can apply when facing such a problem.

#

Is that good so far?

tall belfry
#

Uh i tried the one with the 0 at the end but it still returned the {}

plush nest
#

Because this is a different error

#

Yes it returns 0 when the key is missing, but it will return the stored value if it is there

#

In this case the stored value was, for some reason, an empty dict {}

tall belfry
#

So it returned the {} ?

plush nest
#

That's why I told you to clear the json file.

tall belfry
#

I did its completely empty and the bot is not responding and its giving me an new error

plush nest
#

Deleting the file will result in FileNotFoundError when you run the code.

#

This error is somewhat similar to the one we explored, except it is for when trying to read from a file that doesn't exist.

tall belfry
#

i recreated the warns.json and its now just empty

plush nest
plush nest
#

it is coming fom json.load

tall belfry
#

Hmm but what's the error than i mean json.load is the right thing to use right?

plush nest
#

It expects to find something in there

tall belfry
#

But like i have one thing if i can ask you that?

#

It'll resolve it ig tho

plush nest
#

write this in your json file {}

tall belfry
#

I did

plush nest
tall belfry
plush nest
#

Is your bot working now?

tall belfry
#

Nope

#

But like can you help me with something else it might fix the error tho

plush nest
#

I think I can fix this for you

tall belfry
#

you can?

plush nest
#

just give me your current code

#

after the edits

plush nest
tall belfry
#

Including the warns.json ?

plush nest
#

just the functions

tall belfry
#
def save_warn(ctx, member: discord.Member):
    with open ('warns.json', 'r') as f:
        warns = json.load(f)
        
        warns[str(member.id)] += 1
    
    with open ('warns.json', 'w') as f:
        json.dump(warns, f)
        
def remove_warn(ctx, member: discord.Member, amount: int):
    with open('warns.json', 'r') as f:
         warns = json.load(f)

         warns[str(member.id)] -= amount

    with open('warns.json', 'w') as f:
         json.dump(warns, f)
    
def warns_check(member: discord.Member):
    with open('warns.json', 'r') as f:
         warns = json.load(f)

         warns.get(str(member.id), 0)
    return warns

@bot.command()
@commands.has_permissions(kick_members=True)
async def warn(ctx, member: discord.Member, *, reason):
      save_warn(ctx, member)
      dm = await bot.fetch_user(member.id)
      em=discord.Embed(title="Warning", description=f"Server: {ctx.guild.id}\nReason: {reason}")
      await dm.send(embed=em)

@bot.command()
@commands.has_permissions(kick_members=True)
async def warnings(ctx, member: discord.Member):
      warns = warns_check(member)
      await ctx.send(f"{member.name} has {warns} warnings.")

@bot.command()
@commands.has_permissions(kick_members=True)
async def rmwarn(ctx, member: discord.Member, amount: int):
      remove_warn(ctx, member, amount)
      await ctx.send(f"Removed {amount} warnings from {member.name}!")```
#

This is the current code

plush nest
#

You have to ask yourself, what happens when the json is empty and you add a warning to it?

tall belfry
plush nest
#
warns[str(member.id)] += 1
#

now look at this

plush nest
tall belfry
plush nest
#

If not, this should be an error

#

Instead

plush nest
#

Basically,

  1. get the value
  2. add one
  3. store the value
#

I will change that to

key = str(member.id)
warns[key] = warns.get(key, 0) + 1
tall belfry
#

But like the code will add 1 warn to the user id if its in the warns.json but what if its not in there like how will i add the value in the file

plush nest
#

Just add this in place. You already have the code that stores the value back in the file.

#

But don't test your bot yet

#

There is another change

#

Or maybe, yes go ahead and see the result.

tall belfry
#

So what should i change before i test?

plush nest
tall belfry
#

Alr 1 sec

plush nest
#

You will see something like {'2563267543': 1}

#

We will fix that next

tall belfry
#

Notthing happends

#

Still more errors

plush nest
#

really?

tall belfry
#

This is so hard to learn๐Ÿฅฒ

plush nest
#

oh sorry

#

I referred to the wrong message

tall belfry
#

Alr

plush nest
#

Still one change after this to get it working

#

I am using my phone right now just like you do

tall belfry
#

Alright whats the next change?

plush nest
#

What did you get?

tall belfry
#

Next error

plush nest
#
def warns_check(member: discord.Member):
    with open('warns.json', 'r') as f:
         warns = json.load(f)

         warns.get(str(member.id), 0)  # gets the right value
    return warns  # returns the whole dictionary
plush nest
tall belfry
#

Can you edit my code bc i dont know where to replace it i think i messed it up

plush nest
#

this is the same as the previous error

tall belfry
#

yh ik i think i messed it up badly๐Ÿฅฒ

plush nest
#

Share your code

#

not all of it, just the part that was changed

tall belfry
#
def save_warn(ctx, member: discord.Member):
    with open ('warns.json', 'r') as f:
        warns = json.load(f)
        
        warns[str(member.id)] += 1
    
    with open ('warns.json', 'w') as f:
        json.dump(warns, f)
        
def remove_warn(ctx, member: discord.Member, amount: int):
    with open('warns.json', 'r') as f:
         warns = json.load(f)

         warns[str(member.id)] -= amount

    with open('warns.json', 'w') as f:
         json.dump(warns, f)
    
def warns_check(member: discord.Member):
    with open('warns.json', 'r') as f:
         warns = json.load(f)

         key = str(member.id)
         warns[key] = warns[key] + 1
    return warns```
#

I changed some stuff in here

plush nest
#

Ok I see

#

you replaced the wrong line ๐Ÿ˜ญ

#

just hit undo

#

now let's get back

tall belfry
plush nest
#

This function ...

def save_warn(ctx, member: discord.Member):
    with open ('warns.json', 'r') as f:
        warns = json.load(f)
        
        warns[str(member.id)] += 1
    
    with open ('warns.json', 'w') as f:
        json.dump(warns, f)
tall belfry
#

yes?

plush nest
plush nest
tall belfry
plush nest
#

talk in steps

#

like it opens the file, then ...?

#

load it's content?

tall belfry
#

It opens it

plush nest
#

Don't be afraid, I am only checking your understanding

#
def save_warn(ctx, member: discord.Member):
    # open file in reading mode
    with open ('warns.json', 'r') as f:
        # loads content of the file, warns is a dictionary now
        warns = json.load(f)
        
        # updates the value
        warns[str(member.id)] += 1
    
    # open the same file again in writing mode
    with open ('warns.json', 'w') as f:
        # store the data into the file
        json.dump(warns, f)
#
# updates the value
warns[str(member.id)] += 1

# issue: it only updates the value if it is there
# solution: replace this line

key = str(member.id)
if key in warns:
    # increase by one
    warns[key] += 1
else:
    # set to one
    warns[key] = 1
#
def save_warn(ctx, member: discord.Member):
    # open file in reading mode
    with open ('warns.json', 'r') as f:
        # loads content of the file, warns is a dictionary now
        warns = json.load(f)
        
        # update the value
        key = str(member.id)
        if key in warns:
            # increase by one
            warns[key] += 1
        else:
            # set to one
            warns[key] = 1
    
    # open the same file again in writing mode
    with open ('warns.json', 'w') as f:
        # store the data into the file
        json.dump(warns, f)
#

@tall belfry Is that clear?

tall belfry
#

yes

plush nest
#

Do you see how we, programmers, replace code?

#

This is what I wanted you to do

#

This is how your check function looked like before it was messed up

def warns_check(member: discord.Member):
    with open('warns.json', 'r') as f:
        warns = json.load(f)
        
        key = str(member.id)
        warns.get(key, 0)  # gets the amount
    return warns  # return the dictionary
#

Coding on phone is hard, ik

#

I was there there too,

#

@tall belfry can you, ahh.. , edit your code again?

tall belfry
#

Like replace it with yours?

plush nest
#

just be aware of what you are replacing

tall belfry
#

Alright i will

#

It worked! But its saying my user id and the warning amount

plush nest
#

Exactly

#

That means you did it right this time

#

only one fix to do

plush nest
#

I want you to take a look at this function and tell me what is wrong with it

tall belfry
#

Uhh

#

I dont get it

plush nest
#

-# hint: what does the function return?

tall belfry
#

the warns

plush nest
#

And what is warns? What value is stored in there?

tall belfry
#

The user id and the amount ?

plush nest
#

exactly

#

but if you only want to return the amount, how would you do it.

tall belfry
#

Hmm

#

Tbh i dont know

plush nest
#

-# just return the amount instead of returning the entire dictionary

tall belfry
#

yh but how can i only return the amount like over a variable ?

plush nest
#
def warns_check(member: discord.Member):
    with open('warns.json', 'r') as f:
        warns = json.load(f)
        
        key = str(member.id)
        warns.get(key, 0)  # gets the amount
    return warns  # return the dictionary
def warns_check(member: discord.Member):
    with open('warns.json', 'r') as f:
        warns = json.load(f)
        
        key = str(member.id)
        return warns.get(key, 0)  # get the amount and return the amount
#

Did you get it?

tall belfry
#

ye

#

Okay i got it working but how can i fix the remove warns now over command?

plush nest
#

look at the function that saves warning, it will be similar to that

#

like if the key is present reduce by the given amount, and if it is not there set it to zero

tall belfry
#
def remove_warn(ctx, member: discord.Member, amount: int):
    with open('warns.json', 'r') as f:
        warns = json.load(f):
            key = str(member.id)
            if key in warns:
                 warns[key] -= amount 
            else:
                warns[key] = 0

    with open('warns.json', 'w') as f:
         json.dump(warns, f)```
#

Is this right?

plush nest
#

fix the indent

#
def remove_warn(ctx, member: discord.Member, amount: int):
    with open('warns.json', 'r') as f:
        warns = json.load(f):
        key = str(member.id)
        if key in warns:
             warns[key] -= amount 
        else:
            warns[key] = 0

    with open('warns.json', 'w') as f:
         json.dump(warns, f)
bold shardBOT
#
Python help channel closed for inactivity

This help channel has been closed. Feel free to create a new post in #1035199133436354600. To maximize your chances of getting a response, check out this guide on asking good questions.