Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to use json files to black list others discord py

I am trying to make a blacklist command so that if others abuse my bot I can add their user id and then they get blacklisted. I found code off of this question and I tried to use the code, but the code they use, you have to actually mention the member in order to blacklist them, so now I am stuck.

Here is the code I tried:

# black list command attempt one
@bot.command()
@commands.is_owner
async def blacklist(ctx, user_id):
    user_id_int = int(user_id)
    guild = ctx.guild
    if user_id_int == None:
        await ctx.send(f"You did not provide an id!")
        print(f"You did not run the blacklist command properly due to providing no id.")
    else:
        with open('blacklist.json', 'r') as blacklist_file:
            users = json.load(blacklist_file)

(Yes ik this is a little skidded from the other question but I am stuck and I tried to make my own code off of the code from the other question)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

What you’re doing is:

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

Reading the file, load it into users and nothing else.

Here’s how you read a json and update it to add a user id to it.

with open('blacklist.json', 'r+') as blacklist_file:
    users = json.load(blacklist_file)

    users.append(user_id_int)

    blacklist_file.seek(0)
    json.dump(users, blacklist_file, indent=4)
    blacklist_file.truncate()

You open the file in read+write mode, load the json, append the user_id you mentioned and then overwrite the file with the updated json.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading