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.

412 lines
15 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. from hashlib import sha256
  24. import logging
  25. import logging.handlers
  26. from os import mkdir, path
  27. from Crypto.Cipher import Blowfish
  28. import bcrypt
  29. import yaml
  30. from earwigbot.exceptions import NoConfigError
  31. __all__ = ["BotConfig"]
  32. class BotConfig(object):
  33. """
  34. **EarwigBot: YAML Config File Manager**
  35. This handles all tasks involving reading and writing to our config file,
  36. including encrypting and decrypting passwords and making a new config file
  37. from scratch at the inital bot run.
  38. BotConfig has a few attributes and methods, including the following:
  39. - :py:attr:`root_dir`: bot's working directory; contains
  40. :file:`config.yml`, :file:`logs/`
  41. - :py:attr:`path`: path to the bot's config file
  42. - :py:attr:`components`: enabled components
  43. - :py:attr:`wiki`: information about wiki-editing
  44. - :py:attr:`irc`: information about IRC
  45. - :py:attr:`commands`: information about IRC commands
  46. - :py:attr:`tasks`: information for bot tasks
  47. - :py:attr:`metadata`: miscellaneous information
  48. - :py:meth:`schedule`: tasks scheduled to run at a given time
  49. BotConfig also has some methods used in config loading:
  50. - :py:meth:`load`: loads (or reloads) and parses our config file
  51. - :py:meth:`decrypt`: decrypts an object in the config tree
  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_cipher = None
  59. self._data = None
  60. self._components = _ConfigNode()
  61. self._wiki = _ConfigNode()
  62. self._irc = _ConfigNode()
  63. self._commands = _ConfigNode()
  64. self._tasks = _ConfigNode()
  65. self._metadata = _ConfigNode()
  66. self._nodes = [self._components, self._wiki, self._irc, self._commands,
  67. self._tasks, self._metadata]
  68. self._decryptable_nodes = [ # Default nodes to decrypt
  69. (self._wiki, ("password",)),
  70. (self._wiki, ("search", "credentials", "key")),
  71. (self._wiki, ("search", "credentials", "secret")),
  72. (self._irc, ("frontend", "nickservPassword")),
  73. (self._irc, ("watcher", "nickservPassword")),
  74. ]
  75. def __repr__(self):
  76. """Return the canonical string representation of the BotConfig."""
  77. res = "BotConfig(root_dir={0!r}, level={1!r})"
  78. return res.format(self.root_dir, self.logging_level)
  79. def __str__(self):
  80. """Return a nice string representation of the BotConfig."""
  81. return "<BotConfig at {0}>".format(self.root_dir)
  82. def _load(self):
  83. """Load data from our JSON config file (config.yml) into self._data."""
  84. filename = self._config_path
  85. with open(filename, 'r') as fp:
  86. try:
  87. self._data = yaml.load(fp)
  88. except yaml.YAMLError:
  89. print "Error parsing config file {0}:".format(filename)
  90. raise
  91. def _setup_logging(self):
  92. """Configures the logging module so it works the way we want it to."""
  93. log_dir = self._log_dir
  94. logger = logging.getLogger("earwigbot")
  95. logger.handlers = [] # Remove any handlers already attached to us
  96. logger.setLevel(logging.DEBUG)
  97. if self.metadata.get("enableLogging"):
  98. hand = logging.handlers.TimedRotatingFileHandler
  99. formatter = _BotFormatter()
  100. color_formatter = _BotFormatter(color=True)
  101. logfile = lambda f: path.join(log_dir, f)
  102. if not path.isdir(log_dir):
  103. if not path.exists(log_dir):
  104. mkdir(log_dir, 0700)
  105. else:
  106. msg = "log_dir ({0}) exists but is not a directory!"
  107. print msg.format(log_dir)
  108. return
  109. main_handler = hand(logfile("bot.log"), "midnight", 1, 7)
  110. error_handler = hand(logfile("error.log"), "W6", 1, 4)
  111. debug_handler = hand(logfile("debug.log"), "H", 1, 6)
  112. main_handler.setLevel(logging.INFO)
  113. error_handler.setLevel(logging.WARNING)
  114. debug_handler.setLevel(logging.DEBUG)
  115. for h in (main_handler, error_handler, debug_handler):
  116. h.setFormatter(formatter)
  117. logger.addHandler(h)
  118. self._stream_handler = stream = logging.StreamHandler()
  119. stream.setLevel(self._logging_level)
  120. stream.setFormatter(color_formatter)
  121. logger.addHandler(stream)
  122. def _decrypt(self, node, nodes):
  123. """Try to decrypt the contents of a config node. Use self.decrypt()."""
  124. try:
  125. node._decrypt(self._decryption_cipher, nodes[:-1], nodes[-1])
  126. except ValueError:
  127. print "Error decrypting passwords:"
  128. raise
  129. def _make_new(self):
  130. """Make a new config file based on the user's input."""
  131. #m = "Would you like to encrypt passwords stored in config.yml? [y/n] "
  132. #encrypt = raw_input(m)
  133. #if encrypt.lower().startswith("y"):
  134. # is_encrypted = True
  135. #else:
  136. # is_encrypted = False
  137. raise NotImplementedError()
  138. # yaml.dumps() config.yml file (self._config_path)
  139. # Create root_dir/, root_dir/commands/, root_dir/tasks/
  140. # Give a reasonable message after config has been created regarding
  141. # what to do next...
  142. @property
  143. def root_dir(self):
  144. """The bot's root directory containing its config file and more."""
  145. return self._root_dir
  146. @property
  147. def logging_level(self):
  148. """The minimum logging level for messages logged via stdout."""
  149. return self._logging_level
  150. @logging_level.setter
  151. def logging_level(self, level):
  152. self._logging_level = level
  153. self._stream_handler.setLevel(level)
  154. @property
  155. def path(self):
  156. """The path to the bot's config file."""
  157. return self._config_path
  158. @property
  159. def log_dir(self):
  160. """The directory containing the bot's logs."""
  161. return self._log_dir
  162. @property
  163. def data(self):
  164. """The entire config file as a decoded JSON object."""
  165. return self._data
  166. @property
  167. def components(self):
  168. """A dict of enabled components."""
  169. return self._components
  170. @property
  171. def wiki(self):
  172. """A dict of information about wiki-editing."""
  173. return self._wiki
  174. @property
  175. def irc(self):
  176. """A dict of information about IRC."""
  177. return self._irc
  178. @property
  179. def commands(self):
  180. """A dict of information for IRC commands."""
  181. return self._commands
  182. @property
  183. def tasks(self):
  184. """A dict of information for bot tasks."""
  185. return self._tasks
  186. @property
  187. def metadata(self):
  188. """A dict of miscellaneous information."""
  189. return self._metadata
  190. def is_loaded(self):
  191. """Return ``True`` if our config file has been loaded, or ``False``."""
  192. return self._data is not None
  193. def is_encrypted(self):
  194. """Return ``True`` if passwords are encrypted, otherwise ``False``."""
  195. return self.metadata.get("encryptPasswords", False)
  196. def load(self):
  197. """Load, or reload, our config file.
  198. First, check if we have a valid config file, and if not, notify the
  199. user. If there is no config file at all, offer to make one, otherwise
  200. exit.
  201. Data from the config file is stored in six
  202. :py:class:`~earwigbot.config._ConfigNode`\ s (:py:attr:`components`,
  203. :py:attr:`wiki`, :py:attr:`irc`, :py:attr:`commands`, :py:attr:`tasks`,
  204. :py:attr:`metadata`) for easy access (as well as the lower-level
  205. :py:attr:`data` attribute). If passwords are encrypted, we'll use
  206. :py:func:`~getpass.getpass` for the key and then decrypt them. If the
  207. config is being reloaded, encrypted items will be automatically
  208. decrypted if they were decrypted earlier.
  209. """
  210. if not path.exists(self._config_path):
  211. print "Config file not found:", self._config_path
  212. choice = raw_input("Would you like to create a config file now? [y/n] ")
  213. if choice.lower().startswith("y"):
  214. self._make_new()
  215. else:
  216. raise NoConfigError()
  217. self._load()
  218. data = self._data
  219. self.components._load(data.get("components", {}))
  220. self.wiki._load(data.get("wiki", {}))
  221. self.irc._load(data.get("irc", {}))
  222. self.commands._load(data.get("commands", {}))
  223. self.tasks._load(data.get("tasks", {}))
  224. self.metadata._load(data.get("metadata", {}))
  225. self._setup_logging()
  226. if self.is_encrypted():
  227. if not self._decryption_cipher:
  228. key = getpass("Enter key to decrypt bot passwords: ")
  229. self._decryption_cipher = Blowfish.new(sha256(key).digest())
  230. signature = self.metadata["signature"]
  231. assert bcrypt.hashpw(key, signature) == signature
  232. for node, nodes in self._decryptable_nodes:
  233. self._decrypt(node, nodes)
  234. def decrypt(self, node, *nodes):
  235. """Decrypt an object in our config tree.
  236. :py:attr:`_decryption_cipher` is used as our key, retrieved using
  237. :py:func:`~getpass.getpass` in :py:meth:`load` if it wasn't already
  238. specified. If this is called when passwords are not encrypted (check
  239. with :py:meth:`is_encrypted`), nothing will happen. We'll also keep
  240. track of this node if :py:meth:`load` is called again (i.e. to reload)
  241. and automatically decrypt it.
  242. Example usage::
  243. >>> config.decrypt(config.irc, "frontend", "nickservPassword")
  244. # decrypts config.irc["frontend"]["nickservPassword"]
  245. """
  246. signature = (node, nodes)
  247. if signature in self._decryptable_nodes:
  248. return # Already decrypted
  249. self._decryptable_nodes.append(signature)
  250. if self.is_encrypted():
  251. self._decrypt(node, nodes)
  252. def schedule(self, minute, hour, month_day, month, week_day):
  253. """Return a list of tasks scheduled to run at the specified time.
  254. The schedule data comes from our config file's ``schedule`` field,
  255. which is stored as :py:attr:`self.data["schedule"] <data>`.
  256. """
  257. # Tasks to run this turn, each as a list of either [task_name, kwargs],
  258. # or just the task_name:
  259. tasks = []
  260. now = {"minute": minute, "hour": hour, "month_day": month_day,
  261. "month": month, "week_day": week_day}
  262. data = self._data.get("schedule", [])
  263. for event in data:
  264. do = True
  265. for key, value in now.items():
  266. try:
  267. requirement = event[key]
  268. except KeyError:
  269. continue
  270. if requirement != value:
  271. do = False
  272. break
  273. if do:
  274. try:
  275. tasks.extend(event["tasks"])
  276. except KeyError:
  277. pass
  278. return tasks
  279. class _ConfigNode(object):
  280. def __iter__(self):
  281. for key in self.__dict__:
  282. yield key
  283. def __getitem__(self, item):
  284. return self.__dict__.__getitem__(item)
  285. def _dump(self):
  286. data = self.__dict__.copy()
  287. for key, val in data.iteritems():
  288. if isinstance(val, _ConfigNode):
  289. data[key] = val._dump()
  290. return data
  291. def _load(self, data):
  292. self.__dict__ = data.copy()
  293. def _decrypt(self, cipher, intermediates, item):
  294. base = self.__dict__
  295. for inter in intermediates:
  296. try:
  297. base = base[inter]
  298. except KeyError:
  299. return
  300. if item in base:
  301. ciphertext = base[item].decode("hex")
  302. base[item] = cipher.decrypt(ciphertext).rstrip("\x00")
  303. def get(self, *args, **kwargs):
  304. return self.__dict__.get(*args, **kwargs)
  305. def keys(self):
  306. return self.__dict__.keys()
  307. def values(self):
  308. return self.__dict__.values()
  309. def items(self):
  310. return self.__dict__.items()
  311. def iterkeys(self):
  312. return self.__dict__.iterkeys()
  313. def itervalues(self):
  314. return self.__dict__.itervalues()
  315. def iteritems(self):
  316. return self.__dict__.iteritems()
  317. class _BotFormatter(logging.Formatter):
  318. def __init__(self, color=False):
  319. self._format = super(_BotFormatter, self).format
  320. if color:
  321. fmt = "[%(asctime)s %(lvl)s] %(name)s: %(message)s"
  322. self.format = lambda record: self._format(self.format_color(record))
  323. else:
  324. fmt = "[%(asctime)s %(levelname)-8s] %(name)s: %(message)s"
  325. self.format = self._format
  326. datefmt = "%Y-%m-%d %H:%M:%S"
  327. super(_BotFormatter, self).__init__(fmt=fmt, datefmt=datefmt)
  328. def format_color(self, record):
  329. l = record.levelname.ljust(8)
  330. if record.levelno == logging.DEBUG:
  331. record.lvl = l.join(("\x1b[34m", "\x1b[0m")) # Blue
  332. if record.levelno == logging.INFO:
  333. record.lvl = l.join(("\x1b[32m", "\x1b[0m")) # Green
  334. if record.levelno == logging.WARNING:
  335. record.lvl = l.join(("\x1b[33m", "\x1b[0m")) # Yellow
  336. if record.levelno == logging.ERROR:
  337. record.lvl = l.join(("\x1b[31m", "\x1b[0m")) # Red
  338. if record.levelno == logging.CRITICAL:
  339. record.lvl = l.join(("\x1b[1m\x1b[31m", "\x1b[0m")) # Bold red
  340. return record