From fb1b973ac5348e106c433c0cb1de3cba5aefe541 Mon Sep 17 00:00:00 2001 From: TechieDamien Date: Mon, 22 Nov 2021 18:39:21 +0000 Subject: [PATCH] Added example weather callback --- examples/weather_callback.py | 34 ++++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 examples/weather_callback.py diff --git a/examples/weather_callback.py b/examples/weather_callback.py new file mode 100644 index 0000000..c0334da --- /dev/null +++ b/examples/weather_callback.py @@ -0,0 +1,34 @@ +import requests + +def create_message(message, entities): + # Check that we have a city to check on. + if 'GPE0' not in entities.keys(): + return "ERROR: No GPE detected. Please include a location in your weather request." + # Read the api key to authenticate ourselves with. + with open('.openweathermapkey', 'r') as f: + apikey = f.readline().strip('\n') # Note that we need to strip the trailing \n + # Create the request using the location and key + owm_url = f"https://api.openweathermap.org/data/2.5/weather?q={entities['GPE0']}&appid={apikey}" + owm_resp = requests.get(owm_url) + # Handle error codes + if owm_resp.status_code == 401: + return "ERROR: Sorry, there was an error with the api key for open weather map" + elif owm_resp.status_code == 404: + return f"ERROR: Sorry, open weather map does not recognise {entities['GPE0']} as a valid city" + elif owm_resp.status_code == 429: + return "ERROR: Sorry, it seems that there have been too many requests to get weather recently. Please try again later." + elif owm_resp.status_code in [500, 502, 503, 504]: + return "ERROR: How on Earth did you manage to break things this badly! Let Damien know what shenanigans you pulled to make this message appear." + elif owm_resp.status_code != 200: + return f"ERROR: I got {owm_resp.status_code} as a response from open weather map" + + # Reponse is JSON, so simply parse and use to create response + owm_content = owm_resp.json() + return f"""

Here is the weather in {entities['GPE0']}:

+"""