weather.py 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. import urllib2
  2. import json
  3. class Weather:
  4. def __init__(self, events=None, printer_handle=None, bot=None, say=None):
  5. self.events = events
  6. self.printer = printer_handle
  7. self.interests = ['__.weather__']
  8. self.bot = bot
  9. self.say = say
  10. self.help = ".weather <zipcode>, .weather <city> <state>"
  11. for event in events:
  12. if event._type in self.interests:
  13. # print "DEBUG: registering to ",
  14. # print event
  15. event.subscribe(self)
  16. def handle(self, event):
  17. _z = event.line.split()
  18. if _z[-1] != "":
  19. #print event.msg.split()[1:]
  20. try:
  21. # for specifying by name
  22. if len(event.msg.split()[1:]) > 1: # looking for .weather san francisco ca
  23. autocomplete_url = 'http://autocomplete.wunderground.com/aq?query=' + " " .join(event.msg.split()[1:]) # should be everything after weather
  24. response = urllib2.urlopen(autocomplete_url)
  25. try:
  26. j = response.read()
  27. except urllib2.HTTPError:
  28. self.printer("PRIVMSG " + event.channel + " :Wunderground appears down. Sorry\n")
  29. return
  30. parsed = json.loads(j)
  31. try:
  32. zipcode = parsed['RESULTS'][0]['zmw']
  33. except IndexError:
  34. return
  35. url = 'http://api.wunderground.com/api/1fe31b3b4cfdab66/conditions/lang:EN/q/'+zipcode[:5]+'.json'
  36. # by zipcode
  37. else:
  38. zipcode = _z[-1] # zipcode should be last word on line (.weather 95928, eg)
  39. url = 'http://api.wunderground.com/api/1fe31b3b4cfdab66/conditions/lang:EN/q/'+zipcode+'.json'
  40. try:
  41. response = urllib2.urlopen(url)
  42. # catch timeouts
  43. except urllib2.HTTPError:
  44. self.printer("PRIVMSG " + event.channel + " :Wunderground appears down. Sorry\n")
  45. return
  46. json_string = response.read()
  47. parsed_json = json.loads(json_string)
  48. #print json_string
  49. self.printer("PRIVMSG " + event.channel + " :" + parsed_json['current_observation']['display_location']['city'] + ", " + parsed_json['current_observation']['display_location']['state'] + ": " + parsed_json['current_observation']['weather'] + ", " + parsed_json['current_observation']['feelslike_string'] + ", " + parsed_json['current_observation']['relative_humidity'] +" humidity"+ '\n')
  50. #self.printer("PRIVMSG " + event.channel + " :For complete info: http://www.wunderground.com/cgi-bin/findweather/hdfForecast?query="+zipcode + '\n')
  51. except KeyError, e:
  52. pass