Search code examples
pythondiscord.pypython-asyncio

Eliminate duplicate responses in a nested for loop


I am working on finding a solution for my discord bot, it is written in Py, it's coded to search in game database apis for a specific player name, if found, it sends a message on discord with the server ID, this part works however now I want to add a message if the player is not found after searching all the databases, here is the code:

@client.command()
async def whereis(ctx, player):  # General stats
    for element in gameIDs["IDs"]:
        url0 = apiLink1 + "/players/?gameId=" + element
        r = requests.get(url0)
        rs = r.json()
        a = rs['teams'][0]['players']
        b = rs['teams'][1]['players']
        c = a + b
        d = rs['serverinfo']['name']
        for element1 in c:
            if element1["name"] == str(player):
                embed = discord.Embed(title=player + " HAS BEEN FOUND",description=d)
                await ctx.send(embed=embed)
                break
            else:
                print("not found")

The first for loop is to have every database id checked, the second for loop is to verify every database with the given player, my current solution returns a "not found" for every gameID instance, which I understand why, but I would only like for it to send the message once the gameIDs list has been exhausted. How would I proceed with this?

Thank you all so much in advance.


Solution

  • What about just adding a player_found bool and print if it is not found?

    async def whereis(ctx, player):  # General stats
        player_found = False
        for element in gameIDs["IDs"]:
            url0 = apiLink1 + "/players/?gameId=" + element
            r = requests.get(url0)
            rs = r.json()
            a = rs['teams'][0]['players']
            b = rs['teams'][1]['players']
            c = a + b
            d = rs['serverinfo']['name']
            for element1 in c:
                if element1["name"] == str(player):
                    player_found = True
                    embed = discord.Embed(title=player + " HAS BEEN FOUND",description=d)
                    await ctx.send(embed=embed)
                    break
        if not player_found:
            print("not found")