|
| 1 | +import requests |
| 2 | + |
| 3 | +city_api_url = "https://geocoding-api.open-meteo.com/v1/search" |
| 4 | +forecast_api_url = "https://api.open-meteo.com/v1/forecast" |
| 5 | + |
| 6 | +class WeatherForecast: |
| 7 | + def __init__(self): |
| 8 | + pass |
| 9 | + |
| 10 | + def get_forecast_by_city(self, city: str) -> any: |
| 11 | + try: |
| 12 | + response = requests.get(city_api_url, params={"name": city}) |
| 13 | + except: |
| 14 | + raise RuntimeError("Failed to look city up") |
| 15 | + |
| 16 | + data = response.json() |
| 17 | + results = data.get("results", []) |
| 18 | + if results: |
| 19 | + result = results[0] |
| 20 | + else: |
| 21 | + raise RuntimeError("City not found") |
| 22 | + |
| 23 | + return self.get_forecast_by_coords(result['latitude'], result['longitude']) |
| 24 | + |
| 25 | + def get_forecast_by_coords(self, latitude: str, longitude: str, timezone = "GMT") -> any: |
| 26 | + params = { |
| 27 | + "latitude": latitude, |
| 28 | + "longitude": longitude, |
| 29 | + "timezone": timezone, |
| 30 | + "current": "temperature_2m,weather_code,precipitation", |
| 31 | + "hourly": "temperature_2m,weather_code,precipitation_probability", |
| 32 | + "forecast_days": "1", |
| 33 | + "format": "json" |
| 34 | + } |
| 35 | + try: |
| 36 | + response = requests.get(forecast_api_url, params=params) |
| 37 | + except: |
| 38 | + raise RuntimeError("Failed to get weather data") |
| 39 | + |
| 40 | + data = response.json() |
| 41 | + if response.status_code == 200: |
| 42 | + return data |
| 43 | + else: |
| 44 | + raise RuntimeError(f"Failed to get weather data: {data.get('reason', 'Unknown error')}") |
| 45 | + |
| 46 | + def execute(self, city, something_else=None): |
| 47 | + return self.get_forecast_by_city(city) |
| 48 | + |
| 49 | + # def execute(self, msg: any) -> any: |
| 50 | + # if msg["text"]: |
| 51 | + # return self.get_forecast_by_city(msg["text"]) |
| 52 | + # if msg["latitude"] and msg["longitude"]: |
| 53 | + # return self.get_forecast_by_coords(msg["latitude"], msg["longitude"]) |
| 54 | + # raise RuntimeError("incompatible input") |
| 55 | + |
| 56 | +class CityLookupError(Exception): |
| 57 | + pass |
| 58 | + |
| 59 | +class WeatherForecastLookupError(Exception): |
| 60 | + pass |
0 commit comments