A Python robot that edits Wikipedia and interacts with people over IRC https://en.wikipedia.org/wiki/User:EarwigBot
Nie możesz wybrać więcej, niż 25 tematów Tematy muszą się zaczynać od litery lub cyfry, mogą zawierać myślniki ('-') i mogą mieć do 35 znaków.

341 wiersze
12 KiB

  1. # -*- coding: utf-8 -*-
  2. #
  3. # Copyright (C) 2009-2012 by 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 getpass import getpass
  23. import logging
  24. import logging.handlers
  25. from os import mkdir, path
  26. import yaml
  27. from earwigbot import blowfish
  28. __all__ = ["BotConfig"]
  29. class BotConfig(object):
  30. """
  31. EarwigBot's YAML Config File Manager
  32. This handles all tasks involving reading and writing to our config file,
  33. including encrypting and decrypting passwords and making a new config file
  34. from scratch at the inital bot run.
  35. BotConfig has a few properties and functions, including the following:
  36. * config.root_dir - bot's working directory; contains config.yml, logs/
  37. * config.path - path to the bot's config file
  38. * config.components - enabled components
  39. * config.wiki - information about wiki-editing
  40. * config.tasks - information for bot tasks
  41. * config.irc - information about IRC
  42. * config.metadata - miscellaneous information
  43. * config.schedule() - tasks scheduled to run at a given time
  44. BotConfig also has some functions used in config loading:
  45. * config.load() - loads and parses our config file, returning True if
  46. passwords are stored encrypted or False otherwise;
  47. can also be used to easily reload config
  48. * config.decrypt() - given a key, decrypts passwords inside our config
  49. variables, and remembers to decrypt the password if
  50. config is reloaded; won't do anything if passwords
  51. aren't encrypted
  52. """
  53. def __init__(self, root_dir):
  54. self._root_dir = root_dir
  55. self._config_path = path.join(self._root_dir, "config.yml")
  56. self._log_dir = path.join(self._root_dir, "logs")
  57. self._decryption_key = None
  58. self._data = None
  59. self._components = _ConfigNode()
  60. self._wiki = _ConfigNode()
  61. self._tasks = _ConfigNode()
  62. self._irc = _ConfigNode()
  63. self._metadata = _ConfigNode()
  64. self._nodes = [self._components, self._wiki, self._tasks, self._irc,
  65. self._metadata]
  66. self._decryptable_nodes = []
  67. def _load(self):
  68. """Load data from our JSON config file (config.yml) into self._data."""
  69. filename = self._config_path
  70. with open(filename, 'r') as fp:
  71. try:
  72. self._data = yaml.load(fp)
  73. except yaml.YAMLError as error:
  74. print "Error parsing config file {0}:".format(filename)
  75. raise
  76. def _setup_logging(self):
  77. """Configures the logging module so it works the way we want it to."""
  78. log_dir = self._log_dir
  79. logger = logging.getLogger("earwigbot")
  80. logger.setLevel(logging.DEBUG)
  81. if self.metadata.get("enableLogging"):
  82. hand = logging.handlers.TimedRotatingFileHandler
  83. formatter = _BotFormatter()
  84. color_formatter = _BotFormatter(color=True)
  85. logfile = lambda f: path.join(log_dir, f)
  86. if not path.isdir(log_dir):
  87. if not path.exists(log_dir):
  88. mkdir(log_dir, 0700)
  89. else:
  90. msg = "log_dir ({0}) exists but is not a directory!"
  91. print msg.format(log_dir)
  92. return
  93. main_handler = hand(logfile("bot.log"), "midnight", 1, 7)
  94. error_handler = hand(logfile("error.log"), "W6", 1, 4)
  95. debug_handler = hand(logfile("debug.log"), "H", 1, 6)
  96. main_handler.setLevel(logging.INFO)
  97. error_handler.setLevel(logging.WARNING)
  98. debug_handler.setLevel(logging.DEBUG)
  99. for h in (main_handler, error_handler, debug_handler):
  100. h.setFormatter(formatter)
  101. logger.addHandler(h)
  102. stream_handler = logging.StreamHandler()
  103. stream_handler.setLevel(logging.DEBUG)
  104. stream_handler.setFormatter(color_formatter)
  105. logger.addHandler(stream_handler)
  106. def _decrypt(self, node, nodes):
  107. """Try to decrypt the contents of a config node. Use self.decrypt()."""
  108. try:
  109. node._decrypt(self._decryption_key, nodes[:-1], nodes[-1])
  110. except blowfish.BlowfishError as error:
  111. print "Error decrypting passwords:"
  112. raise
  113. def _make_new(self):
  114. """Make a new config file based on the user's input."""
  115. #m = "Would you like to encrypt passwords stored in config.yml? [y/n] "
  116. #encrypt = raw_input(m)
  117. #if encrypt.lower().startswith("y"):
  118. # is_encrypted = True
  119. #else:
  120. # is_encrypted = False
  121. raise NotImplementedError()
  122. # yaml.dumps()
  123. @property
  124. def root_dir(self):
  125. return self._root_dir
  126. @property
  127. def path(self):
  128. return self._config_path
  129. @property
  130. def log_dir(self):
  131. return self._log_dir
  132. @property
  133. def data(self):
  134. """The entire config file."""
  135. return self._data
  136. @property
  137. def components(self):
  138. """A dict of enabled components."""
  139. return self._components
  140. @property
  141. def wiki(self):
  142. """A dict of information about wiki-editing."""
  143. return self._wiki
  144. @property
  145. def tasks(self):
  146. """A dict of information for bot tasks."""
  147. return self._tasks
  148. @property
  149. def irc(self):
  150. """A dict of information about IRC."""
  151. return self._irc
  152. @property
  153. def metadata(self):
  154. """A dict of miscellaneous information."""
  155. return self._metadata
  156. def is_loaded(self):
  157. """Return True if our config file has been loaded, otherwise False."""
  158. return self._data is not None
  159. def is_encrypted(self):
  160. """Return True if passwords are encrypted, otherwise False."""
  161. return self.metadata.get("encryptPasswords", False)
  162. def load(self):
  163. """Load, or reload, our config file.
  164. First, check if we have a valid config file, and if not, notify the
  165. user. If there is no config file at all, offer to make one, otherwise
  166. exit.
  167. Store data from our config file in five _ConfigNodes (components,
  168. wiki, tasks, irc, metadata) for easy access (as well as the internal
  169. _data variable).
  170. If config is being reloaded, encrypted items will be automatically
  171. decrypted if they were decrypted beforehand.
  172. """
  173. if not path.exists(self._config_path):
  174. print "Config file not found:", self._config_path
  175. choice = raw_input("Would you like to create a config file now? [y/n] ")
  176. if choice.lower().startswith("y"):
  177. self._make_new()
  178. else:
  179. exit(1)
  180. self._load()
  181. data = self._data
  182. self.components._load(data.get("components", {}))
  183. self.wiki._load(data.get("wiki", {}))
  184. self.tasks._load(data.get("tasks", {}))
  185. self.irc._load(data.get("irc", {}))
  186. self.metadata._load(data.get("metadata", {}))
  187. self._setup_logging()
  188. if self.is_encrypted():
  189. if not self._decryption_key:
  190. key = getpass("Enter key to decrypt bot passwords: ")
  191. self._decryption_key = key
  192. for node, nodes in self._decryptable_nodes:
  193. self._decrypt(node, nodes)
  194. def decrypt(self, node, *nodes):
  195. """Use self._decryption_key to decrypt an object in our config tree.
  196. If this is called when passwords are not encrypted (check with
  197. config.is_encrypted()), nothing will happen. We'll also keep track of
  198. this node if config.load() is called again (i.e. to reload) and
  199. automatically decrypt it.
  200. Example usage:
  201. config.decrypt(config.irc, "frontend", "nickservPassword")
  202. -> decrypts config.irc["frontend"]["nickservPassword"]
  203. """
  204. self._decryptable_nodes.append((node, nodes))
  205. if self.is_encrypted():
  206. self._decrypt(node, nodes)
  207. def schedule(self, minute, hour, month_day, month, week_day):
  208. """Return a list of tasks scheduled to run at the specified time.
  209. The schedule data comes from our config file's 'schedule' field, which
  210. is stored as self._data["schedule"]. Call this function as
  211. config.schedule(args).
  212. """
  213. # Tasks to run this turn, each as a list of either [task_name, kwargs],
  214. # or just the task_name:
  215. tasks = []
  216. now = {"minute": minute, "hour": hour, "month_day": month_day,
  217. "month": month, "week_day": week_day}
  218. data = self._data.get("schedule", [])
  219. for event in data:
  220. do = True
  221. for key, value in now.items():
  222. try:
  223. requirement = event[key]
  224. except KeyError:
  225. continue
  226. if requirement != value:
  227. do = False
  228. break
  229. if do:
  230. try:
  231. tasks.extend(event["tasks"])
  232. except KeyError:
  233. pass
  234. return tasks
  235. class _ConfigNode(object):
  236. def __iter__(self):
  237. for key in self.__dict__.iterkeys():
  238. yield key
  239. def __getitem__(self, item):
  240. return self.__dict__.__getitem__(item)
  241. def _dump(self):
  242. data = self.__dict__.copy()
  243. for key, val in data.iteritems():
  244. if isinstance(val, _ConfigNode):
  245. data[key] = val._dump()
  246. return data
  247. def _load(self, data):
  248. self.__dict__ = data.copy()
  249. def _decrypt(self, key, intermediates, item):
  250. base = self.__dict__
  251. try:
  252. for inter in intermediates:
  253. base = base[inter]
  254. except KeyError:
  255. return
  256. if item in base:
  257. base[item] = blowfish.decrypt(key, base[item])
  258. def get(self, *args, **kwargs):
  259. return self.__dict__.get(*args, **kwargs)
  260. class _BotFormatter(logging.Formatter):
  261. def __init__(self, color=False):
  262. self._format = super(_BotFormatter, self).format
  263. if color:
  264. fmt = "[%(asctime)s %(lvl)s] %(name)s: %(message)s"
  265. self.format = lambda record: self._format(self.format_color(record))
  266. else:
  267. fmt = "[%(asctime)s %(levelname)-8s] %(name)s: %(message)s"
  268. self.format = self._format
  269. datefmt = "%Y-%m-%d %H:%M:%S"
  270. super(_BotFormatter, self).__init__(fmt=fmt, datefmt=datefmt)
  271. def format_color(self, record):
  272. l = record.levelname.ljust(8)
  273. if record.levelno == logging.DEBUG:
  274. record.lvl = l.join(("\x1b[34m", "\x1b[0m")) # Blue
  275. if record.levelno == logging.INFO:
  276. record.lvl = l.join(("\x1b[32m", "\x1b[0m")) # Green
  277. if record.levelno == logging.WARNING:
  278. record.lvl = l.join(("\x1b[33m", "\x1b[0m")) # Yellow
  279. if record.levelno == logging.ERROR:
  280. record.lvl = l.join(("\x1b[31m", "\x1b[0m")) # Red
  281. if record.levelno == logging.CRITICAL:
  282. record.lvl = l.join(("\x1b[1m\x1b[31m", "\x1b[0m")) # Bold red
  283. return record