Additional IRC commands and bot tasks for EarwigBot https://en.wikipedia.org/wiki/User:EarwigBot
您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符
 
 

166 行
7.0 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", "weat", "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. permdb = self.config.irc["permissions"]
  50. if not data.args:
  51. if permdb.has_attr(data.host, "weather"):
  52. location = permdb.get_attr(data.host, "weather")
  53. else:
  54. msg = " ".join(("Where do you want the weather of? You can",
  55. "set a default with '!{0} default City,",
  56. "State' (or 'City, Country' if non-US)."))
  57. self.reply(data, msg.format(data.command))
  58. return
  59. elif data.args[0] == "default":
  60. if data.args[1:]:
  61. value = " ".join(data.args[1:])
  62. permdb.set_attr(data.host, "weather", value)
  63. msg = "\x0302{0}\x0F's default set to \x02{1}\x0F."
  64. self.reply(data, msg.format(data.host, value))
  65. else:
  66. if permdb.has_attr(data.host, "weather"):
  67. value = permdb.get_attr(data.host, "weather")
  68. msg = "\x0302{0}\x0F's default is \x02{1}\x0F."
  69. self.reply(data, msg.format(data.host, value))
  70. else:
  71. self.reply(data, "I need a value to set as your default.")
  72. return
  73. else:
  74. location = " ".join(data.args)
  75. url = "http://api.wunderground.com/api/{0}/conditions/q/{1}.json"
  76. location = quote(location, safe="")
  77. query = urlopen(url.format(self.key, location)).read()
  78. res = loads(query)
  79. if "error" in res["response"]:
  80. try:
  81. desc = res["response"]["error"]["description"]
  82. desc = desc[0].upper() + desc[1:]
  83. if desc[-1] not in (".", "!", "?"):
  84. desc += "."
  85. except (KeyError, IndexError):
  86. desc = "An unknown error occurred."
  87. self.reply(data, desc)
  88. elif "current_observation" in res:
  89. msg = self.format_weather(res["current_observation"])
  90. self.reply(data, msg)
  91. elif "results" in res["response"]:
  92. msg = self.format_ambiguous_result(res)
  93. self.reply(data, msg)
  94. else:
  95. self.reply(data, "An unknown error occurred.")
  96. def format_weather(self, data):
  97. """Format the weather (as dict *data*) to be sent through IRC."""
  98. place = data["display_location"]["full"]
  99. icon = self.get_icon(data["icon"])
  100. weather = data["weather"]
  101. temp_f, temp_c = data["temp_f"], data["temp_c"]
  102. humidity = data["relative_humidity"]
  103. wind_dir = data["wind_dir"]
  104. if wind_dir in ("North", "South", "East", "West"):
  105. wind_dir = wind_dir.lower()
  106. wind = "{0} {1} mph".format(wind_dir, data["wind_mph"])
  107. if float(data["wind_gust_mph"]) > float(data["wind_mph"]):
  108. wind += " ({0} mph gusts)".format(data["wind_gust_mph"])
  109. msg = "\x02{0}\x0F: {1} {2}; {3}°F ({4}°C); {5} humidity; wind {6}"
  110. msg = msg.format(place, icon, weather, temp_f, temp_c, humidity, wind)
  111. if data["precip_today_in"] and float(data["precip_today_in"]) > 0:
  112. msg += "; {0}″ precipitation today".format(data["precip_today_in"])
  113. if data["precip_1hr_in"] and float(data["precip_1hr_in"]) > 0:
  114. msg += " ({0}″ past hour)".format(data["precip_1hr_in"])
  115. return msg
  116. def get_icon(self, condition):
  117. """Return a unicode icon to describe the given weather condition."""
  118. icons = {
  119. "chanceflurries" : "☃",
  120. "chancerain" : "☂",
  121. "chancesleet" : "☃",
  122. "chancesnow" : "☃",
  123. "chancetstorms" : "☂",
  124. "clear" : "☀",
  125. "cloudy" : "☁",
  126. "flurries" : "☃",
  127. "fog" : "☁",
  128. "hazy" : "☁",
  129. "mostlycloudy" : "☁",
  130. "mostlysunny" : "☀",
  131. "partlycloudy" : "☁",
  132. "partlysunny" : "☀",
  133. "rain" : "☂",
  134. "sleet" : "☃",
  135. "snow" : "☃",
  136. "sunny" : "☀",
  137. "tstorms" : "☂",
  138. }
  139. try:
  140. return icons[condition]
  141. except KeyError:
  142. return "?"
  143. def format_ambiguous_result(self, res):
  144. """Format a message when there are multiple possible results."""
  145. results = []
  146. for place in res["response"]["results"]:
  147. extra = place["state" if place["state"] else "country"]
  148. results.append("{0}, {1}".format(place["city"], extra))
  149. if len(results) > 21:
  150. extra = len(results) - 20
  151. res = "; ".join(results[:20])
  152. return "Did you mean: {0}... ({1} others)?".format(res, extra)
  153. return "Did you mean: {0}?".format("; ".join(results))