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.
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!
CodePudding user response:
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.