Added example weather callback
parent
fa6d66238a
commit
fb1b973ac5
|
@ -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"""<p>Here is the weather in {entities['GPE0']}:</p>
|
||||||
|
<ul>
|
||||||
|
<li>Weather is described as {owm_content['weather'][0]['description']}.</li>
|
||||||
|
<li>The temperature is {owm_content['main']['temp']}K but it feels like {owm_content['main']['feels_like']}K and has been between {owm_content['main']['temp_min']}K and {owm_content['main']['temp_max']}K today.</li>
|
||||||
|
<li>The pressure is {owm_content['main']['pressure']}hPa.</li>
|
||||||
|
<li>The humidity is {owm_content['main']['humidity']}%.</li>
|
||||||
|
<li>The wind is travelling at {owm_content['wind']['speed']}m/s at a heading of {owm_content['wind']['deg']}.</li>
|
||||||
|
</ul>"""
|
Loading…
Reference in New Issue