weather2.py 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124
  1. import requests
  2. import re
  3. import json
  4. from event import Event
  5. try:
  6. from basemodule import BaseModule
  7. except ImportError:
  8. from modules.basemodule import BaseModule
  9. class Weather2(BaseModule):
  10. def post_init(self):
  11. weather2 = Event('__.weather2__')
  12. weather2.define(msg_definition='^\.weather')
  13. weather2.subscribe(self)
  14. forecast = Event('__.forecast__')
  15. forecast.define(msg_definition='^\.forecast')
  16. forecast.subscribe(self)
  17. self.bot.register_event(forecast, self)
  18. self.bot.register_event(weather2, self)
  19. self.api_key = "1fe31b3b4cfdab66"
  20. def forecast(self, url, channel):
  21. q = requests.get(url)
  22. try:
  23. q.raise_for_status()
  24. except requests.exceptions.HTTPError:
  25. self.say(channel, "Encountered an error with the WUnderground API")
  26. return None
  27. results = q.json()
  28. # we're only doing two days for now
  29. counter = 0
  30. phrase = ""
  31. for item in results['forecast']['txt_forecast']['forecastday']:
  32. if counter > 3:
  33. break
  34. phrase = phrase + item['title'] + ": " + item['fcttext'] + " "
  35. counter += 1
  36. return phrase[:-1] # super hackish way to remove the trailing comma
  37. def api_request(self, location, channel, command="conditions"):
  38. """location is a search string after the .weather command. This function
  39. will determine whether it is a zip code or a named location and return an
  40. appropriate API call"""
  41. #note for future: if wanted, add further detection of conditions or forecast searching
  42. query = None
  43. try:
  44. # test if is a zipcode or a single city name
  45. a = float(location.split()[0])
  46. if a and len(location.split()[0]) < 5:
  47. self.say(channel,"valid zipcode required, numbnuts")
  48. return None
  49. zipcode = re.match('[0-9]{5}', location)
  50. query = '/q/'+zipcode.string
  51. except ValueError: # it's a city name (or broken encoding on numbers or something)
  52. #create autocomplete search
  53. q = requests.get('http://autocomplete.wunderground.com/aq', params={'query':location})
  54. try:
  55. q.raise_for_status()
  56. except requests.exceptions.HTTPError:
  57. self.say(channel, "Encountered an error contacting the WUnderground API")
  58. return None
  59. results = q.json()
  60. try:
  61. #attempt to grab the 'l' field from the first result
  62. #assuming it exists, this field will be what we use to search the conditions api
  63. query = results['RESULTS'][0]['l']
  64. except (IndexError, KeyError):
  65. #in case there were no results, let channel know
  66. self.say(channel, "No results found")
  67. return None
  68. if query:
  69. #return the full URL of the query we want to make
  70. return 'http://api.wunderground.com/api/'+self.api_key+'/' + command + query+'.json'
  71. return None
  72. def get_conditions(self, query, channel):
  73. """given a fully formed query to the wundeground API, format an output string"""
  74. r = requests.get(query)
  75. try:
  76. r.raise_for_status()
  77. except requests.exceptions.HTTPError:
  78. self.say(channel, "Encountered an error contacting the WUnderground API")
  79. return
  80. weather = r.json()
  81. try:
  82. #grab the relevant data we want for formatting
  83. location = weather['current_observation']['display_location']['full']
  84. conditions = weather['current_observation']['weather']
  85. temp_f = str(weather['current_observation']['temp_f'])
  86. temp_c = str(weather['current_observation']['temp_c'])
  87. humidity = weather['current_observation']['relative_humidity']
  88. except KeyError:
  89. self.say(channel, "Unable to get weather data from results. Sorry.")
  90. return
  91. #return the formatted string of weather data
  92. return location + ': ' + conditions + ', ' + temp_f + 'F (' + temp_c + 'C). Humidity: ' + humidity
  93. def handle(self, event):
  94. #split the line beginning with .weather into 2 parts, the command and the search string
  95. weather_line = event.msg.split(None, 1)
  96. if len(weather_line) > 1:
  97. if event.msg.startswith(".forecast"):
  98. self.say(event.channel, "forecast " + weather_line[1] + ": " + self.forecast(self.api_request(weather_line[1], event.channel, "forecast"), event.channel))
  99. return
  100. #if we're sure there's actually a search string, then continue
  101. query = self.api_request(weather_line[1], event.channel)
  102. if not query:
  103. return
  104. weather = self.get_conditions(query, event.channel)
  105. if not weather:
  106. return
  107. self.say(event.channel, weather)
  108. else:
  109. #chastise the user for being silly and not actually searching for a location
  110. self.say(event.channel, "It would help if you supplied an actual location to search for.")