diff --git a/modules/Weather.py b/modules/Weather.py index 68240ac..9049d09 100644 --- a/modules/Weather.py +++ b/modules/Weather.py @@ -81,6 +81,10 @@ class Weather(Module): # current weather query results = self.get_conditions_for_query(queryitems[1:]) return self.reply(connection, event, results) + elif queryitems[0] == "forecast": + # forecast query + results = self.get_forecast_for_query(queryitems[1:]) + return self.reply(connection, event, results) else: # assume they wanted current weather results = self.get_conditions_for_query(queryitems) @@ -198,6 +202,48 @@ class Weather(Module): self.log.exception(e) return "Error parsing results." + def get_forecast_for_query(self, queryitems): + """Make a wunderground forecast call, return as string.""" + + # recombine the query into a string + query = ' '.join(queryitems) + query = query.replace(' ', '_') + + try: + url = self.wu_base + ('{0:s}/q/{1:s}.json'.format('forecast', + query)) + json_resp = urllib2.urlopen(url) + forecast_data = json.load(json_resp) + except IOError as e: + self.log.error("error while making forecast query") + self.log.exception(e) + raise + + # forecast data is loaded. the rest of this is obviously specific to + # http://www.wunderground.com/weather/api/d/docs?d=data/forecast + self.log.debug(json.dumps(forecast_data, sort_keys=True, indent=4)) + + try: + # just see if we have forecast data + forecasts = forecast_data['forecast']['txt_forecast'] + except KeyError as e: + # now we really know something is wrong + self.log.error("error or bad query in forecast lookup") + self.log.exception(e) + return "No results." + else: + try: + reply = "Forecast: " + for forecast in forecasts['forecastday'][0:5]: + reply += "{0:s}: {1:s} ".format(forecast['title'], + forecast['fcttext']) + + return self._prettify_weather_strings(reply.rstrip()) + except KeyError as e: + self.log.error("error or unexpected results in forecast reply") + self.log.exception(e) + return "Error parsing results." + def _get_api_key_from_db(self): """Get the API key string from the database, or None if unset."""