Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I'm not sure how to delete something from a .json file

I've tryed looking it up and it still nothing :(

@bot.command()
async def afkremoveme(ctx):
#pls help me I'm lost!

no errors

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
279 views
Welcome To Ask or Share your Answers For Others

1 Answer

I'm not sure what you want your command to do, but here's an example of how you would implement json into discord.py.

Here, whenever the command is executed, the bot opens a json file, reads the data, and sees if the message author is in the data. If the author is in the data, the key/value pair is deleted, and the data is rewritten into the json file:

import json

@bot.command()
async def afkremoveme(ctx):

    f = "yourFile.json"
    author = str(ctx.author.id)

    with open(f, "r") as read_file:
        data = json.load(read_file)

    if author in data: # if any key in the dictionary is an integer, it is converted to a string when a json file is written

        del data[author]
        newData = json.dumps(data, indent=4)

        with open(f, "w") as write_file:
            write_file.write(newData)

        await ctx.send(f"{ctx.author.display_name} is no longer afk...")

This is reading a json file that looks like this (replace 000000 with your id):

{
    "000000" : "afk",
    "someOtherGuy" : "afk"
}

All of this uses dictionaries and the json module. If you're unfamiliar with either of the concepts, here are a few links to help you out :-)

Python Dictionaries, Python-Json


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...