Search code examples
pythondiscorddiscord.pynew-operator

discord.py creating and appending lists?


I am trying to make a script for a discord bot, where i can use a command and enter the result into a json file.

e.g !add_ally BriansCrew

With BriansCrew being added to the following JSON file

{
  "allies_and_enemies": {
    "allies": [],
    "enemies": []

    }

}

My code is....

allies_and_enemies = {'allies': [], 'enemies': []}


def add_ally(ally_name):
    allies_and_enemies['allies'].append( ally_name )


def add_enemy(enemy_name):
    allies_and_enemies['enemy'].append( enemy_name )


@bot.command()
async def add_ally(ctx, *, args):
    ctx.message.content = "".join(*args)
    allies_and_enemies = ctx.message.content

    with open("ally.json") as f:
        ally = json.load(f)

    ally = allies_and_enemies["allies"].append(ally_name)

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

I am a begginer, i'd really appreciate some explantion if possible

REgards, Ben


Solution

  • Here is a basic python script that will do this. You can create a json file and ready from it and overwrite the new data every time.

    @bot.command()
    async def add_ally(ctx, *args):
        with open('ally.json', 'r') as f:
            lines = json.loads(f.read())
    
        for ally in args:
            lines['allies_and_enemies']['allies'].append(ally)
    
        with open('ally.json', 'w') as f:
            f.write(json.dumps(lines))