A Python robot that edits Wikipedia and interacts with people over IRC https://en.wikipedia.org/wiki/User:EarwigBot
Não pode escolher mais do que 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

config.py 5.1 KiB

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