【问题标题】:OpenWeather API discord.pyOpenWeather API discord.py
【发布时间】:2020-12-04 09:00:17
【问题描述】:

我最近接触了 OpeNweather API,并在这篇文章的帮助下创建了一个简单的当前天气命令:How to make a weather command using discord.py v1.4.1

我对 API 很陌生,所以我需要使用 Forecast API 的帮助(文档可以在这里找到 https://openweathermap.org/api/hourly-forecast

我正在为我的机器人使用 discord.py Rewrite

【问题讨论】:

  • 没有人会给你写一堆代码,让自己走上正轨,写一些代码。如果您卡在任何地方,请随时到达这里。可以在此处找到有关如何提出好问题的更多信息。 stackoverflow.com/help/how-to-ask
  • 您可以使用 1. 请求模块和 2. JSON 模块手动对其进行编码。

标签: discord bots discord.py-rewrite openweathermap


【解决方案1】:

感谢您提供制作此命令的灵​​感。但是通过一些研究和更多细节/学习如何从 API 中检索数据,我来到了这里。我想帮助并与您分享我的想法。

基本上,我使用了 API 提供的所有功能。在我下面的代码中,它将寻找空气中的温度、湿度和压力。它使用“get”方法来检索这些数据,条件是在命令中提供了一个有效的城市。

只需从站点获取密钥,然后复制并粘贴到“api_key”字符串中。希望这对您的进步有所帮助,尽管我也可以在命令运行良好时提供帮助。

api_key = "123abcmyweathercodeapitoken"
base_url = "http://api.openweathermap.org/data/2.5/weather?"


@client.command()
async def weather(ctx, *, city: str):

        city_name = city
        complete_url = base_url + "appid=" + api_key + "&q=" + city_name
        response = requests.get(complete_url)
        x = response.json()
        channel = ctx.message.channel

        if x["cod"] != "404":

                y = x["main"]
                current_temperature = y["temp"]
                current_temperature_celsiuis = str(round(current_temperature - 273.15))
                current_pressure = y["pressure"]
                current_humidity = y["humidity"]
                z = x["weather"]
                weather_description = z[0]["description"]

                embed = discord.Embed(
                    title=f"Weather forecast - {city_name}",
                    color=0x7289DA,
                    timestamp=ctx.message.created_at,
                )
                embed.add_field(
                    name="Description",
                    value=f"**{weather_description}**",
                    inline=False)
                embed.add_field(
                    name="Temperature(C)",
                    value=f"**{current_temperature_celsiuis}°C**",
                    inline=False)
                embed.add_field(
                    name="Humidity(%)", value=f"**{current_humidity}%**", inline=False)
                embed.add_field(
                    name="Atmospheric Pressure(hPa)",
                    value=f"**{current_pressure}hPa**",
                    inline=False)
                embed.set_footer(text=f"Requested by {ctx.author.name}")

                await channel.send(embed=embed)

        else:
                await channel.send(
                    f"There was no results about this place!")

【讨论】:

    猜你喜欢
    • 2022-01-21
    • 2021-11-28
    • 1970-01-01
    • 1970-01-01
    • 2018-10-18
    • 2018-10-30
    • 1970-01-01
    • 2013-09-25
    • 1970-01-01
    相关资源
    最近更新 更多