A Python robot that edits Wikipedia and interacts with people over IRC https://en.wikipedia.org/wiki/User:EarwigBot
選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

config.py 6.1 KiB

13年前
13年前
13年前
13年前
13年前
13年前
13年前
13年前
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189
  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 global variables and functions:
  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, there are functions used in 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. import logging
  23. from os import path
  24. import blowfish
  25. script_dir = path.dirname(path.abspath(__file__))
  26. root_dir = path.split(script_dir)[0]
  27. config_path = path.join(root_dir, "config.json")
  28. log_dir = path.join(root_dir, "logs")
  29. _config = None # Holds data loaded from our config file
  30. # Set our easy-config-access global variables to None
  31. components, wiki, tasks, irc, metadata = None, None, None, None, None
  32. def _load():
  33. """Load data from our JSON config file (config.json) into _config."""
  34. global _config
  35. with open(config_path, 'r') as fp:
  36. try:
  37. _config = json.load(fp)
  38. except ValueError as error:
  39. print "Error parsing config file {0}:".format(config_path)
  40. print error
  41. exit(1)
  42. def _setup_logging():
  43. """Configures the logging module so it works the way we want it to."""
  44. logger = logging.getLogger()
  45. logger.setLevel(logging.DEBUG)
  46. if metadata.get("enableLogging"):
  47. import logging.handlers
  48. hand = logging.handlers.TimedRotatingFileHandler
  49. fmt = "[%(asctime)s %(levelname)-8s] %(name)s: %(message)s"
  50. formatter = logging.Formatter(fmt=fmt, datefmt="%Y-%m-%d %H:%M:%S")
  51. logfile = lambda f: path.join(log_dir, f)
  52. main_handler = hand(logfile("bot.log"), "midnight", 1. 7)
  53. error_handler = hand(logfile("error.log"), "W", 6, 4)
  54. debug_handler = hand(logfile("debug.log"), "H", 1, 6)
  55. main_handler.setLevel(logging.INFO)
  56. error_handler.setLevel(logging.ERROR)
  57. debug_handler.setLevel(logging.DEBUG)
  58. handlers = (main_handler, error_handler, debug_handler)
  59. for h in handlers:
  60. h.setFormatter(formatter)
  61. logger.addHandler(h)
  62. else:
  63. logger.addHandler(logging.NullHandler())
  64. def _make_new():
  65. """Make a new config file based on the user's input."""
  66. encrypt = raw_input("Would you like to encrypt passwords stored in config.json? [y/n] ")
  67. if encrypt.lower().startswith("y"):
  68. is_encrypted = True
  69. else:
  70. is_encrypted = False
  71. return is_encrypted
  72. def is_loaded():
  73. """Return True if our config file has been loaded, otherwise False."""
  74. return _config is not None
  75. def load():
  76. """Load, or reload, our config file.
  77. First, check if we have a valid config file, and if not, notify the user.
  78. If there is no config file at all, offer to make one, otherwise exit.
  79. Store data from our config file in five global variables (components, wiki,
  80. tasks, irc, metadata) for easy access (as well as the internal _config
  81. variable).
  82. If everything goes well, return True if stored passwords are
  83. encrypted in the file, or False if they are not.
  84. """
  85. global components, wiki, tasks, irc, metadata
  86. if not path.exists(config_path):
  87. print "You haven't configured the bot yet!"
  88. choice = raw_input("Would you like to do this now? [y/n] ")
  89. if choice.lower().startswith("y"):
  90. return _make_new()
  91. else:
  92. exit(1)
  93. _load()
  94. components = _config.get("components", [])
  95. wiki = _config.get("wiki", {})
  96. tasks = _config.get("tasks", {})
  97. irc = _config.get("irc", {})
  98. metadata = _config.get("metadata", {})
  99. _setup_logging()
  100. # Are passwords encrypted?
  101. return metadata.get("encryptPasswords", False)
  102. def decrypt(key):
  103. """Use the key to decrypt passwords in our config file.
  104. Call this if load() returns True. Catch password decryption errors and
  105. report them to the user.
  106. """
  107. global irc, wiki
  108. try:
  109. item = wiki.get("password")
  110. if item:
  111. wiki["password"] = blowfish.decrypt(key, item)
  112. item = irc.get("frontend").get("nickservPassword")
  113. if item:
  114. irc["frontend"]["nickservPassword"] = blowfish.decrypt(key, item)
  115. item = irc.get("watcher").get("nickservPassword")
  116. if item:
  117. irc["watcher"]["nickservPassword"] = blowfish.decrypt(key, item)
  118. except blowfish.BlowfishError as error:
  119. print "\nError decrypting passwords:"
  120. print "{0}: {1}.".format(error.__class__.__name__, error)
  121. exit(1)
  122. def schedule(minute, hour, month_day, month, week_day):
  123. """Return a list of tasks scheduled to run at the specified time.
  124. The schedule data comes from our config file's 'schedule' field, which is
  125. stored as _config["schedule"]. Call this function as config.schedule(args).
  126. """
  127. # Tasks to run this turn, each as a list of either [task_name, kwargs], or
  128. # just the task_name:
  129. tasks = []
  130. now = {"minute": minute, "hour": hour, "month_day": month_day,
  131. "month": month, "week_day": week_day}
  132. data = _config.get("schedule", [])
  133. for event in data:
  134. do = True
  135. for key, value in now.items():
  136. try:
  137. requirement = event[key]
  138. except KeyError:
  139. continue
  140. if requirement != value:
  141. do = False
  142. break
  143. if do:
  144. try:
  145. tasks.extend(event["tasks"])
  146. except KeyError:
  147. pass
  148. return tasks