A Python robot that edits Wikipedia and interacts with people over IRC https://en.wikipedia.org/wiki/User:EarwigBot
Non puoi selezionare più di 25 argomenti Gli argomenti devono iniziare con una lettera o un numero, possono includere trattini ('-') e possono essere lunghi fino a 35 caratteri.

160 righe
5.6 KiB

  1. # -*- coding: utf-8 -*-
  2. """
  3. EarwigBot's XML Config File Parser
  4. This handles all tasks involving reading and writing to our config file,
  5. including encrypting and decrypting passwords and making a new config file from
  6. scratch at the inital bot run.
  7. Usually you'll just want to do "from core.config import config" and access
  8. config data from within that object.
  9. """
  10. from collections import defaultdict
  11. from os import makedirs, path
  12. from xml.dom import minidom
  13. from xml.parsers.expat import ExpatError
  14. script_dir = path.dirname(path.abspath(__file__))
  15. root_dir = path.split(script_dir)[0]
  16. config_path = path.join(root_dir, "config.xml")
  17. _config = None # holds the parsed DOM object for our config file
  18. config = None # holds an instance of Container() with our config data
  19. class ConfigParseException(Exception):
  20. """Base exception for when we could not parse the config file."""
  21. class TypeMismatchException(ConfigParseException):
  22. """A field does not fit to its expected type; e.g., an arbitrary string
  23. where we expected a boolean or integer."""
  24. class MissingElementException(ConfigParseException):
  25. """An element in the config file is missing a required sub-element."""
  26. class MissingAttributeException(ConfigParseException):
  27. """An element is missing a required attribute to be parsed correctly."""
  28. class Container(object):
  29. """A class to hold information in a nice, accessable manner."""
  30. def _load_config():
  31. """Load data from our XML config file (config.xml) into a DOM object."""
  32. global _config
  33. _config = minidom.parse(config_path)
  34. def verify_config():
  35. """Check to see if we have a valid config file, and if not, notify the
  36. user. If there is no config file at all, offer to make one; otherwise,
  37. exit."""
  38. if path.exists(config_path):
  39. try:
  40. _load_config()
  41. except ExpatError as error:
  42. print "Could not parse config file {0}:\n{1}".format(config_path,
  43. error)
  44. exit()
  45. else:
  46. if not _config.getElementsByTagName("config"):
  47. e = "Config file is missing a <config> tag."
  48. raise MissingElementException(e)
  49. return are_passwords_encrypted()
  50. else:
  51. print "You haven't configured the bot yet!"
  52. choice = raw_input("Would you like to do this now? [y/n] ")
  53. if choice.lower().startswith("y"):
  54. return make_new_config()
  55. else:
  56. exit()
  57. def make_new_config():
  58. """Make a new XML config file based on the user's input."""
  59. makedirs(config_dir)
  60. encrypt = raw_input("Would you like to encrypt passwords stored in " +
  61. "config.xml? [y/n] ")
  62. if encrypt.lower().startswith("y"):
  63. is_encrypted = True
  64. else:
  65. is_encrypted = False
  66. return is_encrypted
  67. def are_passwords_encrypted():
  68. """Determine if the passwords in our config file are encrypted, returning
  69. either True or False."""
  70. element = _config.getElementsByTagName("config")[0]
  71. return attribute_to_bool(element, "encrypt-passwords", default=False)
  72. def attribute_to_bool(element, attribute, default=None):
  73. """Return True if the value of element's attribute is 'true', '1', or 'on';
  74. return False if it is 'false', '0', or 'off' (regardless of
  75. capitalization); return default if it is empty; raise TypeMismatchException
  76. if it does match any of those."""
  77. value = element.getAttribute(attribute).lower()
  78. if value in ["true", "1", "on"]:
  79. return True
  80. elif value in ["false", "0", "off"]:
  81. return False
  82. elif value == '':
  83. return default
  84. else:
  85. e = ("Expected a bool in attribute '{0}' of element '{1}', but " +
  86. "got '{2}'.").format(attribute, element.tagName, value)
  87. raise TypeMismatchException(e)
  88. def parse_config(key):
  89. """Parse config data from a DOM object into the 'config' global variable.
  90. The key is used to unencrypt passwords stored in the XML config file."""
  91. _load_config() # we might be re-loading unnecessarily here, but no harm in
  92. # that!
  93. data = _config.getElementsByTagName("config")[0]
  94. cfg = Container()
  95. cfg.components = parse_components(data)
  96. cfg.wiki = parse_wiki(data, key)
  97. cfg.irc = parse_irc(data, key)
  98. cfg.schedule = parse_schedule(data)
  99. cfg.watcher = parse_watcher(data)
  100. global config
  101. config = cfg
  102. def parse_components(data):
  103. """Parse everything within the <components> XML tag of our config file.
  104. The components object here will exist as config.components, and is a dict
  105. of our enabled components: components[name] = True if it is enabled, False
  106. if it is disabled."""
  107. components = defaultdict(lambda: False) # all components are disabled by
  108. # default
  109. element = data.getElementsByTagName("components")
  110. if not element:
  111. e = "<config> is missing a required <components> tag."
  112. raise MissingElementException(e)
  113. element = element[0] # select the first <components> tag out of our list
  114. # of tags, even though we should only have one
  115. component_tags = element.getElementsByTagName("component")
  116. for component in component_tags:
  117. name = component.getAttribute("name")
  118. if not name:
  119. e = "A <component> tag is missing the required attribute 'name'."
  120. raise MissingAttributeException(e)
  121. is_enabled = attribute_to_bool(component, "enabled", False)
  122. components[name] = is_enabled
  123. return components
  124. def parse_wiki(data, key):
  125. pass
  126. def parse_irc(data, key):
  127. pass
  128. def parse_schedule(data):
  129. pass
  130. def parse_watcher(data):
  131. pass