Additional IRC commands and bot tasks for EarwigBot https://en.wikipedia.org/wiki/User:EarwigBot
Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

11 роки тому
11 роки тому
11 роки тому
11 роки тому
11 роки тому
11 роки тому
11 роки тому
11 роки тому
11 роки тому
11 роки тому
11 роки тому
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178
  1. # -*- coding: utf-8 -*-
  2. #
  3. # Copyright (C) 2009-2014 Ben Kurtovic <ben.kurtovic@gmail.com>
  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 datetime import datetime
  23. from json import loads
  24. from urllib import quote
  25. from urllib2 import urlopen
  26. from earwigbot.commands import Command
  27. class Weather(Command):
  28. """Get a weather forecast (via http://www.wunderground.com/)."""
  29. name = "weather"
  30. commands = ["weather", "weat", "forecast", "temperature", "temp"]
  31. def setup(self):
  32. self.config.decrypt(self.config.commands, self.name, "apiKey")
  33. try:
  34. self.key = self.config.commands[self.name]["apiKey"]
  35. except KeyError:
  36. self.key = None
  37. addr = "http://wunderground.com/weather/api/"
  38. config = 'config.commands["{0}"]["apiKey"]'.format(self.name)
  39. log = "Cannot use without an API key from {0} stored as {1}"
  40. self.logger.warn(log.format(addr, config))
  41. def process(self, data):
  42. if not self.key:
  43. addr = "http://wunderground.com/weather/api/"
  44. config = 'config.commands["{0}"]["apiKey"]'.format(self.name)
  45. msg = "I need an API key from {0} stored as \x0303{1}\x0F."
  46. log = "Need an API key from {0} stored as {1}"
  47. self.reply(data, msg.format(addr, config))
  48. self.logger.error(log.format(addr, config))
  49. return
  50. permdb = self.config.irc["permissions"]
  51. if not data.args:
  52. if permdb.has_attr(data.host, "weather"):
  53. location = permdb.get_attr(data.host, "weather")
  54. else:
  55. msg = " ".join(("Where do you want the weather of? You can",
  56. "set a default with '!{0} default City,",
  57. "State' (or 'City, Country' if non-US)."))
  58. self.reply(data, msg.format(data.command))
  59. return
  60. elif data.args[0] == "default":
  61. if data.args[1:]:
  62. value = " ".join(data.args[1:])
  63. permdb.set_attr(data.host, "weather", value)
  64. msg = "\x0302{0}\x0F's default set to \x02{1}\x0F."
  65. self.reply(data, msg.format(data.host, value))
  66. else:
  67. if permdb.has_attr(data.host, "weather"):
  68. value = permdb.get_attr(data.host, "weather")
  69. msg = "\x0302{0}\x0F's default is \x02{1}\x0F."
  70. self.reply(data, msg.format(data.host, value))
  71. else:
  72. self.reply(data, "I need a value to set as your default.")
  73. return
  74. else:
  75. location = " ".join(data.args)
  76. url = "http://api.wunderground.com/api/{0}/conditions/astronomy/q/{1}.json"
  77. location = quote(location, safe="")
  78. query = urlopen(url.format(self.key, location)).read()
  79. res = loads(query)
  80. if "error" in res["response"]:
  81. try:
  82. desc = res["response"]["error"]["description"]
  83. desc = desc[0].upper() + desc[1:]
  84. if desc[-1] not in (".", "!", "?"):
  85. desc += "."
  86. except (KeyError, IndexError):
  87. desc = "An unknown error occurred."
  88. self.reply(data, desc)
  89. elif "current_observation" in res:
  90. msg = self.format_weather(res["current_observation"])
  91. self.reply(data, msg)
  92. elif "results" in res["response"]:
  93. msg = self.format_ambiguous_result(res)
  94. self.reply(data, msg)
  95. else:
  96. self.reply(data, "An unknown error occurred.")
  97. def format_weather(self, data):
  98. """Format the weather (as dict *data*) to be sent through IRC."""
  99. place = data["display_location"]["full"]
  100. icon = self.get_icon(data["icon"], data["local_time_rfc822"],
  101. data["sunrise"], data["sunset"])
  102. weather = data["weather"]
  103. temp_f, temp_c = data["temp_f"], data["temp_c"]
  104. humidity = data["relative_humidity"]
  105. wind_dir = data["wind_dir"]
  106. if wind_dir in ("North", "South", "East", "West"):
  107. wind_dir = wind_dir.lower()
  108. wind = "{0} {1} mph".format(wind_dir, data["wind_mph"])
  109. if float(data["wind_gust_mph"]) > float(data["wind_mph"]):
  110. wind += " ({0} mph gusts)".format(data["wind_gust_mph"])
  111. msg = "\x02{0}\x0F: {1} {2}; {3}°F ({4}°C); {5} humidity; wind {6}"
  112. msg = msg.format(place, icon, weather, temp_f, temp_c, humidity, wind)
  113. if data["precip_today_in"] and float(data["precip_today_in"]) > 0:
  114. msg += "; {0}″ precipitation today".format(data["precip_today_in"])
  115. if data["precip_1hr_in"] and float(data["precip_1hr_in"]) > 0:
  116. msg += " ({0}″ past hour)".format(data["precip_1hr_in"])
  117. return msg
  118. def get_icon(self, condition, local_time, sunrise, sunset):
  119. """Return a unicode icon to describe the given weather condition."""
  120. icons = {
  121. "chanceflurries" : "☃",
  122. "chancerain" : "☂",
  123. "chancesleet" : "☃",
  124. "chancesnow" : "☃",
  125. "chancetstorms" : "☂",
  126. "clear" : "☽☀",
  127. "cloudy" : "☁",
  128. "flurries" : "☃",
  129. "fog" : "☁",
  130. "hazy" : "☁",
  131. "mostlycloudy" : "☁",
  132. "mostlysunny" : "☽☀",
  133. "partlycloudy" : "☁",
  134. "partlysunny" : "☽☀",
  135. "rain" : "☂",
  136. "sleet" : "☃",
  137. "snow" : "☃",
  138. "sunny" : "☽☀",
  139. "tstorms" : "☂",
  140. }
  141. try:
  142. icon = icons[condition]
  143. if len(icon) == 2:
  144. lt_no_tz = local_time.rsplit(" ", 1)[0]
  145. dt = datetime.strptime(lt_no_tz, "%a, %d %b %Y %H:%M:%S")
  146. srise = datetime(year=dt.year, month=dt.month, day=dt.day,
  147. hour=int(sunrise["hour"]),
  148. minute=int(sunrise["minute"]))
  149. sset = datetime(year=dt.year, month=dt.month, day=dt.day,
  150. hour=int(sunset["hour"]),
  151. minute=int(sunset["minute"]))
  152. return icon[int(srise < dt < sset)]
  153. return icon
  154. except KeyError:
  155. return "?"
  156. def format_ambiguous_result(self, res):
  157. """Format a message when there are multiple possible results."""
  158. results = []
  159. for place in res["response"]["results"]:
  160. extra = place["state" if place["state"] else "country"]
  161. results.append("{0}, {1}".format(place["city"], extra))
  162. if len(results) > 21:
  163. extra = len(results) - 20
  164. res = "; ".join(results[:20])
  165. return "Did you mean: {0}... ({1} others)?".format(res, extra)
  166. return "Did you mean: {0}?".format("; ".join(results))