Search code examples
pythonpython-3.xdiscorddiscord.py

How to use JSON files to black list others using 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)

Solution

  • You're doing:

    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 file 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 content, append the user_id you mentioned and then overwrite the file with the updated JSON content.