padel/padel/weather.py

41 lines
1.0 KiB
Python

import requests
from datetime import datetime
class WeatherAPI:
BASE_URL = "https://api.weatherapi.com/v1"
def __init__(self, api_key):
self._api_key = api_key
def _get(self, endpoint, params):
params["key"] = self._api_key
return requests.get(f"{self.BASE_URL}{endpoint}", params=params)
async def get_hourly_conditions(self, query, days=1):
r = self._get(
"/forecast.json",
{
"q": query,
"days": days,
"aqi": "no",
"alert": "no",
},
)
if r.status_code != 200:
return None
data = r.json()
hour_forecasts = sum(
[obj["hour"] for obj in data["forecast"]["forecastday"]], []
)
return [
(
datetime.fromtimestamp(forecast["time_epoch"]),
forecast["condition"]["text"],
forecast["condition"]["code"],
)
for forecast in hour_forecasts
]