Search code examples
pythonnextcord

Bot does not check if user is in JSON file using Python Nextcord


@bot.slash_command(description="Adds user to fishing score list!", guild_ids=[TESTING_GUILD_ID])
async def adduser(interaction: nextcord.Interaction):
    if str(interaction.user) in score_file:
        await interaction.send("You are already added!")
    else:
        def write_score(data, filename=score_file):
            with open (filename, "w") as f:
                json.dump(data, f, indent=4)
        with open(score_file) as json_file:
            data = json.load(json_file)
            temp = data["usernames"]
            y = {"name": str(interaction.user), "score": 0}
            temp.append(y)
            write_score(data)
            json_file.close()
            await interaction.send("Added! You can now fish!")

My bot is just skipping checking to see if the user is added and instead adds them anyways, creating copies of the same user.

It's supposed to reply "you are already added!" to a user who is already on a JSON, and if they are not, then add them to the JSON.


Solution

  • From the code, it looks like score_file is a file name. The in operator in Python does string matching. It certainly does not open and read a file. So, unless the username is part of the file name, it will never match.

    I'm not sure why you want the username as a list of dicts, instead of just having it be a dict where the username is the key.

    You need to read the whole file in, then decide if it needs to change:

    @bot.slash_command(description="Adds user to fishing score list!", guild_ids=[TESTING_GUILD_ID])
    async def adduser(interaction: nextcord.Interaction):
        with open(score_file) as json_file:
            data = json.load(json_file)
        if interaction.user in (d['name'] for d in data["usernames"]):
            await interaction.send("You are already added!")
        else:
            data["usernames"].append( {"name": interaction.user, "score": 0} )
    
            with open (score_file, "w") as f:
                json.dump(data, f, indent=4)
            await interaction.send("Added! You can now fish!")