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)

>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.

Leave a Reply