A Python robot that edits Wikipedia and interacts with people over IRC https://en.wikipedia.org/wiki/User:EarwigBot
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

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