Can not get client.command parameter to parse API response by key value in discord.py

Viewed 78

I'm building a command onto an existing bot that will search an API and take a baseball player's name as a parameter to query a json response with. I've gotten everything to work correctly in test, only for the life of me I can't figure out how to restrict the results to only those that include the query parameter that is passed when the command is invoked within discord.

For example: a user will type !card Adam Dunn and only the value "Adam Dunn" for the key "name" will return. Currently, the entire first page of results is being sent no matter what is typed for the parameter, and with my embed logic running, each result gets a separate embed, which isn't ideal.

I've only included the pertinent lines of code and not included the massive embed of the results for readability's sake.

It's got to be something glaringly simple, but I think I've just been staring at it for too long to see it. Any help would be greatly appreciated, thank you!

Below is a console output when the command is run:

Here is the code I'm currently working with:

async def card(ctx, *, player_name: str):
    async with ctx.channel.typing():
        async with aiohttp.ClientSession() as cs:
            async with cs.get("https://website.items.json") as r:
                data = await r.json()
                listings = data["items"]
                for k in listings:
                    if player_name == k["name"]
                        print()```
2 Answers

I hope I understood you right. If the user did not give a player_name Then you will just keep searching for nothing, and you want to end if there is no player_name given. if that is the case then.

Set the default value of player_name: str=None to be None then check at the beginning of your code if it is there.

async def card(ctx, *, player_name: str=None):
    if not player_name:
        return await ctx.send('You must enter a player name')

    # if there is a name do this
    async with ctx.channel.typing():
        async with aiohttp.ClientSession() as cs:
            async with cs.get("https://theshownation.com/mlb20/apis/items.json") as r:
                data = await r.json()
                listings = data["items"]
                for k in listings:
                    if player_name == k["name"]
                        print()```

Update:

I'm an idiot. Works as expected, but because the player_name I was searching for wasn't on the first page of results, it wasn't showing. When using a player_name that is on the first page of the API results, it works just fine.

This is a pagination issue, not a key value issue.

Related