From ee340e621b9e0fa736f1b2819818d408dc4c2e3b Mon Sep 17 00:00:00 2001 From: Ben Kurtovic Date: Sat, 15 Nov 2014 18:12:50 -0600 Subject: [PATCH] Support time-dependent icons for !weather. --- commands/weather.py | 29 +++++++++++++++++++++-------- 1 file changed, 21 insertions(+), 8 deletions(-) diff --git a/commands/weather.py b/commands/weather.py index 01219e1..5bf33c5 100644 --- a/commands/weather.py +++ b/commands/weather.py @@ -20,6 +20,7 @@ # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. +from datetime import datetime from json import loads from urllib import quote from urllib2 import urlopen @@ -79,7 +80,7 @@ class Weather(Command): else: location = " ".join(data.args) - url = "http://api.wunderground.com/api/{0}/conditions/q/{1}.json" + url = "http://api.wunderground.com/api/{0}/conditions/astronomy/q/{1}.json" location = quote(location, safe="") query = urlopen(url.format(self.key, location)).read() res = loads(query) @@ -105,7 +106,8 @@ class Weather(Command): def format_weather(self, data): """Format the weather (as dict *data*) to be sent through IRC.""" place = data["display_location"]["full"] - icon = self.get_icon(data["icon"]) + icon = self.get_icon(data["icon"], data["local_time_rfc822"], + data["sunrise"], data["sunset"]) weather = data["weather"] temp_f, temp_c = data["temp_f"], data["temp_c"] humidity = data["relative_humidity"] @@ -124,7 +126,7 @@ class Weather(Command): msg += " ({0}″ past hour)".format(data["precip_1hr_in"]) return msg - def get_icon(self, condition): + def get_icon(self, condition, local_time, sunrise, sunset): """Return a unicode icon to describe the given weather condition.""" icons = { "chanceflurries" : "☃", @@ -132,23 +134,34 @@ class Weather(Command): "chancesleet" : "☃", "chancesnow" : "☃", "chancetstorms" : "☂", - "clear" : "☀", + "clear" : "☽☀", "cloudy" : "☁", "flurries" : "☃", "fog" : "☁", "hazy" : "☁", "mostlycloudy" : "☁", - "mostlysunny" : "☀", + "mostlysunny" : "☽☀", "partlycloudy" : "☁", - "partlysunny" : "☀", + "partlysunny" : "☽☀", "rain" : "☂", "sleet" : "☃", "snow" : "☃", - "sunny" : "☀", + "sunny" : "☽☀", "tstorms" : "☂", } try: - return icons[condition] + icon = icons[condition] + if len(icon) == 2: + lt_no_tz = local_time.rsplit(" ", 1)[0] + dt = datetime.strptime(lt_no_tz, "%a, %d %b %Y %H:%M:%S") + srise = datetime(year=dt.year, month=dt.month, day=dt.day, + hour=int(sunrise["hour"]), + minute=int(sunrise["minute"])) + sset = datetime(year=dt.year, month=dt.month, day=dt.day, + hour=int(sunset["hour"]), + minute=int(sunset["minute"])) + return icon[int(srise < dt < sset)] + return icon except KeyError: return "?"