our/cmds/weather

62 lines
2.1 KiB
Python
Executable File

#!/usr/bin/env python3
######################################################
# Takes a location, e.g. "New York" as an argument #
# and returns the current weather conditions. Uses #
# the weather data API courtesy of metaweather.com #
######################################################
######################################################
# Written by ~xaphania 2022-04-22 #
# For use on tilde.town with the 'our' IRC bot #
# Please send comments or suggestions via town mail #
# to xaphania@tilde.town #
# v0.1 #
# TO DO - customise weather strings, add emoji? #
# TO DO - more features: detailed reports, future #
# and past weather conditions, etc #
######################################################
import sys
import json
import urllib.request
# get argument, replace spaces with %20
search = sys.argv[1].replace(" ","%20")
# Get Where on Earth ID for specified location
searchUrl = "https://www.metaweather.com/api/location/search/?query=" + search
try:
locationData = json.loads(urllib.request.urlopen(searchUrl).read())
except:
print("Couldn't contact metaweather. Service may be down, please try later.")
exit()
try:
locationID = locationData[0]["woeid"]
except:
search = search.replace("%20"," ")
print(f"Sorry, I couldn't find location {search}")
exit()
# Get weather data for that woeid
weatherUrl = "https://www.metaweather.com/api/location/"+str(locationID)+"/"
try:
weatherData = json.loads(urllib.request.urlopen(weatherUrl).read())
except:
print("Couldn't contact metaweather. Service may be down, please try later.")
exit()
try:
state = weatherData["consolidated_weather"][0]["weather_state_name"]
temp = round(weatherData["consolidated_weather"][0]["the_temp"])
location = weatherData["title"]
parent = weatherData["parent"]["title"]
print(f"In {location}, {parent} it's {temp}°c and {state}" \
+" (Weather Data from www.metaweather.com)")
except:
print("Sorry, there was an error retreiving weather data. Please try later.")