Discord.py 将参数添加到 api 命令

Discord.py adding params to a api command

我需要帮助在 API 命令中为 api 这样的城市词典(用于搜索定义)和打开天气图(用于获取特定位置的天气)添加参数,我了解事实上,其中很多都提供了查询字符串代码 ("GET", url, headers=headers, params=querystring) 但我不明白如何允许诸如 $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)
    

查看 Urban Dictionnary APIquerystring 必须是具有 term 键的字典。
然后,要向命令添加参数,您只需向函数添加一个参数,discord.py 将自动解析命令。如果你想在单个参数中 $urban 之后的所有内容,你必须在 term 参数之前添加一个 *

看起来像这样:

@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)

对于开放天气图API,您需要在url中传递参数。例如,如果你想要巴黎的 5 天预报,你必须使用这个 url :

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

有关更多信息,您可以查看文档: