Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

OpenWeather API Get Current Temp. with Discord.py

I am trying to get the current temperature for my city using the OpenWeather API and D.PY.

Currently my API request returns:

{
    "lat": ***,
    "lon": ***,
    "timezone": "America/New_York",
    "timezone_offset": -18000,
    "current": {
        "dt": 1639881036,
        "sunrise": 1639831807,
        "sunset": 1639866054,
        "temp": 39.4, ####WANT THIS####
        "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"
            }
        ]
    }
}

I am trying to make a command that returns the temperature that the API returns. Since the API returns in JSON format, I am using string indices to return the current temp. But, I am having trouble of what numbers I have to use to return it correctly.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

My current code:

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

So basically I want to find the current and return the temp if that makes sense. Right now I only get it to send there or no there. What string indices do I need to use in order to return what I want? Thanks in advanced!

>Solution :

When the payload from the API response is received in JSON, you need to convert it into a Python readable data format, in this case it would be a Dictionary.

To do so, you can use json.loads() on your response.

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.

From there, you can simply access the temperature under the key 'current' and 'temp' as such:

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

Full Code: (Remember to 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)

As always, remember to validate the JSON response from the API to make sure there is a temp in the current index, in cases where the lattitude-longitude provided are invalid, or there is no available temperature to report may throw an error because the index won’t exist.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading