From 7e262d4b777f2f98fe721da9e4a1fd063628fe7e Mon Sep 17 00:00:00 2001 From: Schanihbg Date: Tue, 22 Oct 2024 15:15:49 +0200 Subject: [PATCH] Fix weather Now fetches data directly from the SMHI API --- marvin_actions.py | 32 +++++++++++++++++++++++--------- marvin_strings.json | 4 +++- 2 files changed, 26 insertions(+), 10 deletions(-) diff --git a/marvin_actions.py b/marvin_actions.py index c4eb2f3..3c877cf 100644 --- a/marvin_actions.py +++ b/marvin_actions.py @@ -304,20 +304,34 @@ def marvinWeather(row): """ Check what the weather prognosis looks like. """ - msg = None + msg = "" if any(r in row for r in ["väder", "vädret", "prognos", "prognosen", "smhi"]): - url = getString("smhi", "url") + forecast = "" + observation = "" + try: - soup = BeautifulSoup(urlopen(url)) - msg = "{}. {}. {}".format( - soup.h1.text, - soup.h4.text, - soup.h4.findNextSibling("p").text - ) + station_req = requests.get(getString("smhi", "station_url"), timeout=5) + weather_code:int = int(station_req.json().get("value")[0].get("value")) + + weather_codes_req = requests.get(getString("smhi", "weather_codes_url"), timeout=5) + weather_codes_arr: list = weather_codes_req.json().get("entry") + + current_weather_req = requests.get(getString("smhi", "current_weather_url"), timeout=5) + current_w_data: list = current_weather_req.json().get("timeSeries")[0].get("parameters") + + for curr_w in current_w_data: + if curr_w.get("name") == "t": + forecast = curr_w.get("values")[0] + + for code in weather_codes_arr: + if code.get("key") == weather_code: + observation = code.get("value") + + msg = f"Karlskrona just nu: {forecast} °C. {observation}." except Exception as e: LOG.error("Failed to get weather: %s", e) - msg = getString("smhi", "failed") + msg: str = getString("smhi", "failed") return msg diff --git a/marvin_strings.json b/marvin_strings.json index 4933f6b..592b892 100644 --- a/marvin_strings.json +++ b/marvin_strings.json @@ -197,7 +197,9 @@ }, "smhi": { - "url": "http://www.smhi.se/weatherSMHI2/landvader/prognos15_2.htm", + "station_url": "https://opendata-download-metobs.smhi.se/api/version/1.0/parameter/13/station/65090/period/latest-hour/data.json", + "current_weather_url": "https://opendata-download-metfcst.smhi.se/api/category/pmp3g/version/2/geotype/point/lon/15.5890/lat/56.1500/data.json", + "weather_codes_url": "https://opendata-download-metobs.smhi.se/api/version/1.0/parameter/13/codes.json", "failed": "Något har hänt med SMHI, de svarar inte." },