Jango DarkWind
Jango DarkWind

Reputation: 47

Discord.py adding params to a api command

I am needing help in adding parameters in API command for api's such Urban Dictionary (for searching definitions) and open weather map (to get weather of certain location) I understand the fact that a lot of these are provided with code for querystring then ("GET", url, headers=headers, params=querystring) but I don't understand how to allow something such as $urban yo-yo.

@commands.command(
        name="urban",
        description="Allows the user to get a definition from Urban Dictionary",
        aliases=['urbandict']
    )
    async def urban(self, ctx):
        url = "https://mashape-community-urban-dictionary.p.rapidapi.com/define"

        headers = {
            'x-rapidapi-key': self.bot.quote_api_key,
            'x-rapidapi-host': "mashape-community-urban-dictionary.p.rapidapi.com"
        }

        async with ClientSession() as session:
            async with session.get(url, headers=headers) as response:
                r = await response.json()
                # print(r)
                embed = discord.Embed(title="Term:", description=f"{r['']}")

                embed.add_field(name="Definition:", value=f"||{r['']}||")

                embed.set_author(name=ctx.author.display_name, icon_url=ctx.message.author.avatar_url)

                await ctx.send(embed=embed)
    

Upvotes: 0

Views: 509

Answers (1)

MrSpaar
MrSpaar

Reputation: 3994

Looking at the Urban Dictionnary API, querystring must a dictionnary that has a term key.
Then, to add parameters to commands, you simply have to add a parameter to your function and discord.py will parse the command automatically. If you want everything after $urban in a single parameter, you have to add a * before the term parameter.

It would look like this :

@commands.command()
async def urban(self, ctx, *, term):
    url = "https://mashape-community-urban-dictionary.p.rapidapi.com/define"

    querystring = {"term": term}
    headers = {
        'x-rapidapi-key': self.bot.quote_api_key,
        'x-rapidapi-host': "mashape-community-urban-dictionary.p.rapidapi.com"
    }

    async with ClientSession() as session:
        async with session.get(url, headers=headers, params=querystring) as response:
            r = await response.json()

    embed = discord.Embed(title="Term:", description=f"{r['']}")
    embed.add_field(name="Definition:", value=f"||{r['']}||")
    embed.set_author(name=ctx.author.display_name, icon_url=ctx.message.author.avatar_url)

    await ctx.send(embed=embed)

For the Open Weather Map API, you need to pass the argument in the url. For instance, if you want Paris' 5 days forecast, you'd have to use this url :

http://api.openweathermap.org/data/2.5/forecast?q=Paris&units=metric&APPID=your_token

For more informations, you can look at the documentations :

Upvotes: 1

Related Questions