A Python robot that edits Wikipedia and interacts with people over IRC https://en.wikipedia.org/wiki/User:EarwigBot
Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

423 rader
15 KiB

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