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.

154 lines
4.9 KiB

  1. # -*- coding: utf-8 -*-
  2. """
  3. EarwigBot's JSON 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 import config" and access config data
  8. from within config's four global variables and one function:
  9. * config.components - a list of enabled components
  10. * config.wiki - a dict of information about wiki-editing
  11. * config.irc - a dict of information about IRC
  12. * config.metadata - a dict of miscellaneous information
  13. * config.schedule() - returns a list of tasks scheduled to run at a given time
  14. Additionally, functions related to config loading:
  15. * config.load() - loads and parses our config file, returning True if
  16. passwords are stored encrypted or False otherwise
  17. * config.decrypt() - given a key, decrypts passwords inside our config
  18. variables; won't work if passwords aren't encrypted
  19. """
  20. import json
  21. from os import path
  22. import blowfish
  23. script_dir = path.dirname(path.abspath(__file__))
  24. root_dir = path.split(script_dir)[0]
  25. config_path = path.join(root_dir, "config.json")
  26. _config = None # Holds data loaded from our config file
  27. # Set our four easy-config-access global variables to None
  28. components, wiki, irc, metadata = None, None, None, None
  29. def _load():
  30. """Load data from our JSON config file (config.json) into _config."""
  31. global _config
  32. with open(config_path, 'r') as fp:
  33. try:
  34. _config = json.load(fp)
  35. except ValueError as error:
  36. print "Error parsing config file {0}:".format(config_path)
  37. print error
  38. exit(1)
  39. def _make_new():
  40. """Make a new config file based on the user's input."""
  41. encrypt = raw_input("Would you like to encrypt passwords stored in config.json? [y/n] ")
  42. if encrypt.lower().startswith("y"):
  43. is_encrypted = True
  44. else:
  45. is_encrypted = False
  46. return is_encrypted
  47. def is_loaded():
  48. """Return True if our config file has been loaded, otherwise False."""
  49. return _config is not None
  50. def load():
  51. """Load, or reload, our config file.
  52. First, check if we have a valid config file, and if not, notify the user.
  53. If there is no config file at all, offer to make one, otherwise exit.
  54. Store data from our config file in four global variables (components, wiki,
  55. irc, metadata) for easy access (as well as the internal _config variable).
  56. If everything goes well, return True if stored passwords are
  57. encrypted in the file, or False if they are not.
  58. """
  59. global components, wiki, irc, metadata
  60. if not path.exists(config_path):
  61. print "You haven't configured the bot yet!"
  62. choice = raw_input("Would you like to do this now? [y/n] ")
  63. if choice.lower().startswith("y"):
  64. return _make_new()
  65. else:
  66. exit(1)
  67. _load()
  68. components = _config.get("components", [])
  69. wiki = _config.get("wiki", {})
  70. irc = _config.get("irc", {})
  71. metadata = _config.get("metadata", {})
  72. # Are passwords encrypted?
  73. return metadata.get("encryptPasswords", False)
  74. def decrypt(key):
  75. """Use the key to decrypt passwords in our config file.
  76. Call this if load() returns True. Catch password decryption errors and
  77. report them to the user.
  78. """
  79. global irc, wiki
  80. try:
  81. item = wiki.get("password")
  82. if item:
  83. wiki["password"] = blowfish.decrypt(key, item)
  84. item = irc.get("frontend").get("nickservPassword")
  85. if item:
  86. irc["frontend"]["nickservPassword"] = blowfish.decrypt(key, item)
  87. item = irc.get("watcher").get("nickservPassword")
  88. if item:
  89. irc["watcher"]["nickservPassword"] = blowfish.decrypt(key, item)
  90. except blowfish.BlowfishError as error:
  91. print "\nError decrypting passwords:"
  92. print "{0}: {1}.".format(error.__class__.__name__, error)
  93. exit(1)
  94. def schedule(minute, hour, month_day, month, week_day):
  95. """Return a list of tasks scheduled to run at the specified time.
  96. The schedule data comes from our config file's 'schedule' field, which is
  97. stored as _config["schedule"]. Call this function as config.schedule(args).
  98. """
  99. # Tasks to run this turn, each as a list of either [task_name, kwargs], or
  100. # just the task_name:
  101. tasks = []
  102. now = {"minute": minute, "hour": hour, "month_day": month_day,
  103. "month": month, "week_day": week_day}
  104. data = _config.get("schedule", [])
  105. for event in data:
  106. do = True
  107. for key, value in now.items():
  108. try:
  109. requirement = event[key]
  110. except KeyError:
  111. continue
  112. if requirement != value:
  113. do = False
  114. break
  115. if do:
  116. try:
  117. tasks.extend(event["tasks"])
  118. except KeyError:
  119. pass
  120. return tasks