Additional IRC commands and bot tasks for EarwigBot https://en.wikipedia.org/wiki/User:EarwigBot
No puede seleccionar más de 25 temas Los temas deben comenzar con una letra o número, pueden incluir guiones ('-') y pueden tener hasta 35 caracteres de largo.
 
 

134 líneas
5.3 KiB

  1. # -*- coding: utf-8 -*-
  2. #
  3. # Copyright (C) 2009-2013 Ben Kurtovic <ben.kurtovic@verizon.net>
  4. #
  5. # Permission is hereby granted, free of charge, to any person obtaining a copy
  6. # of this software and associated documentation files (the "Software"), to deal
  7. # in the Software without restriction, including without limitation the rights
  8. # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  9. # copies of the Software, and to permit persons to whom the Software is
  10. # furnished to do so, subject to the following conditions:
  11. #
  12. # The above copyright notice and this permission notice shall be included in
  13. # all copies or substantial portions of the Software.
  14. #
  15. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16. # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  17. # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  18. # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  19. # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  20. # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  21. # SOFTWARE.
  22. from json import loads
  23. from urllib import quote
  24. from urllib2 import urlopen
  25. from earwigbot.commands import Command
  26. class Weather(Command):
  27. """Get a weather forecast (via http://www.wunderground.com/)."""
  28. name = "weather"
  29. commands = ["weather", "forecast", "temperature", "temp"]
  30. def setup(self):
  31. self.config.decrypt(self.config.commands, self.name, "apiKey")
  32. try:
  33. self.key = self.config.commands[self.name]["apiKey"]
  34. except KeyError:
  35. self.key = None
  36. addr = "http://wunderground.com/weather/api/"
  37. config = 'config.commands["{0}"]["apiKey"]'.format(self.name)
  38. log = "Cannot use without an API key from {0} stored as {1}"
  39. self.logger.warn(log.format(addr, config))
  40. def process(self, data):
  41. if not self.key:
  42. addr = "http://wunderground.com/weather/api/"
  43. config = 'config.commands["{0}"]["apiKey"]'.format(self.name)
  44. msg = "I need an API key from {0} stored as \x0303{1}\x0F."
  45. log = "Need an API key from {0} stored as {1}"
  46. self.reply(data, msg.format(addr, config))
  47. self.logger.error(log.format(addr, config))
  48. return
  49. if not data.args:
  50. self.reply(data, "Where do you want the weather of?")
  51. return
  52. url = "http://api.wunderground.com/api/{0}/conditions/q/{1}.json"
  53. location = quote("_".join(data.args), safe="")
  54. query = urlopen(url.format(self.key, location)).read()
  55. res = loads(query)
  56. if "error" in res:
  57. try:
  58. desc = res["error"]["description"]
  59. desc[0] = desc[0].upper()
  60. if desc[-1] not in (".", "!", "?"):
  61. desc += "."
  62. except (KeyError, IndexError):
  63. desc = "An unknown error occurred."
  64. self.reply(data, desc)
  65. elif "current_observation" in res:
  66. msg = self.format_weather(res["current_observation"])
  67. self.reply(data, msg)
  68. elif "results" in res["response"]:
  69. results = []
  70. for place in res["response"]["results"]:
  71. extra = place["state" if place["state"] else "country_iso3166"]
  72. results.append("{0}, {1}".format(place["city"], extra))
  73. msg = "Did you mean: {0}?".format("; ".join(results))
  74. self.reply(data, msg)
  75. else:
  76. self.reply(data, "An unknown error occurred.")
  77. def format_weather(self, data):
  78. """Format the weather (as dict *data*) to be sent through IRC."""
  79. place = data["display_location"]["full"]
  80. icon = self.get_icon(data["icon"])
  81. weather = data["weather"]
  82. temp_f, temp_c = data["temp_f"], data["temp_c"]
  83. humidity = data["relative_humidity"]
  84. wind = "{0} {1} mph".format(data["wind_dir"], data["wind_mph"])
  85. if int(data["wind_gust_mph"]) > int(data["wind_mph"]):
  86. wind += " ({0} mph gusts)".format(data["wind_gust_mph"])
  87. precip_today = data["precip_today_in"]
  88. precip_hour = data["precip_1hr_in"]
  89. msg = "\x02{0}\x0F: {1} {2}; {3}°F ({4}°C); {5} humidity; wind {6}; "
  90. msg += "{7}″ precipitation today ({8}″ past hour)"
  91. msg = msg.format(place, icon, weather, temp_f, temp_c, humidity, wind,
  92. precip_today, precip_hour)
  93. return msg
  94. def get_icon(self, condition):
  95. """Return a unicode icon to describe the given weather condition."""
  96. icons = {
  97. "chanceflurries" : "☃",
  98. "chancerain" : "☂",
  99. "chancesleet" : "☃",
  100. "chancesnow" : "☃",
  101. "chancetstorms" : "☂",
  102. "clear" : "☀",
  103. "cloudy" : "☁",
  104. "flurries" : "☃",
  105. "fog" : "☁",
  106. "hazy" : "☁",
  107. "mostlycloudy" : "☁",
  108. "mostlysunny" : "☀",
  109. "partlycloudy" : "☁",
  110. "partlysunny" : "☀",
  111. "rain" : "☂",
  112. "sleet" : "☃",
  113. "snow" : "☃",
  114. "sunny" : "☀",
  115. "tstorms" : "☂",
  116. }
  117. try:
  118. return icons[condition]
  119. except KeyError:
  120. return "?"