OpenWeather API 获取当前温度。 Discord.py

OpenWeather API Get Current Temp. with Discord.py

我正在尝试使用 OpenWeather API 和 Discord.py.

获取我所在城市的当前温度

这是来自 API 的负载响应:

{
    "lat": ***,
    "lon": ***,
    "timezone": "America/New_York",
    "timezone_offset": -18000,
    "current": {
        "dt": 1639881036,
        "sunrise": 1639831807,
        "sunset": 1639866054,
        "temp": 39.4, # This is the value I want! #
        "feels_like": 31.44,
        "pressure": 1020,
        "humidity": 88,
        "dew_point": 36.14,
        "uvi": 0,
        "clouds": 90,
        "visibility": 10000,
        "wind_speed": 13.8,
        "wind_deg": 350,
        "wind_gust": 21.85,
        "weather": [
            {
                "id": 804,
                "main": "Clouds",
                "description": "overcast clouds",
                "icon": "04n"
            }
        ]
    }
}

我正在尝试发出一个命令,returns 来自 API 的当前温度。由于 API returns 采用 JSON 格式,我使用字符串索引来 return 当前温度,但我无法确定我必须使用哪些索引来 return 正确。

我的代码:

@commands.command()
@commands.check(is_owner)
    async def weather(self, ctx):
        try:
            req = requests.get('https://api.openweathermap.org/data/2.5/onecall?lat=****&lon=****&exclude=minutely,hourly,daily&units=imperial&appid=****')
            weather = req.text
            for element in weather[5]:
                if element[3] == True:
                    await ctx.send('there')
                    break
                else:
                    await ctx.send('not there')
        except Exception as e:
            await ctx.send(e)

我想找到 current 和 return temp,现在我只能输出 'there''not there' .

当在 JSON 中收到来自 API 响应的有效负载时,您需要将其转换为 Python 可读数据格式,在本例中为字典。

为此,您可以在回复中使用 json.loads()

import json # Don't forget to import the json module!

req = requests.get('https://api.openweathermap.org/data/2.5/onecall?lat=****&lon=****&exclude=minutely,hourly,daily&units=imperial&appid=****')
weather = req.text
weather = json.loads(weather) # Converts to Python Dict.

从那里,您可以简单地访问键 'current''temp' 下的温度:

currentTemp = weather["current"]["temp"]

完整代码: (记得要import json!)

@commands.command()
@commands.check(is_owner)
    async def weather(self, ctx):
        try:
            req = requests.get('https://api.openweathermap.org/data/2.5/onecall?lat=****&lon=****&exclude=minutely,hourly,daily&units=imperial&appid=****')
            weather = json.loads(req.text)
            currentTemp = weather["current"]["temp"] # Gets the current temperature.
        except Exception as e:
            await ctx.send(e)

一如既往,请记住验证 API 的 JSON 响应,以确保 current 索引中有 temp,如果纬度-提供的经度无效,或者没有可用的温度报告可能会抛出错误,因为索引不存在。