A Python robot that edits Wikipedia and interacts with people over IRC https://en.wikipedia.org/wiki/User:EarwigBot
25'ten fazla konu seçemezsiniz Konular bir harf veya rakamla başlamalı, kısa çizgiler ('-') içerebilir ve en fazla 35 karakter uzunluğunda olabilir.

config.py 5.0 KiB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153
  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 three global variables and one function:
  9. * config.components - a list of enabled components
  10. * config.wiki - a dict of config information for wiki-editing
  11. * config.irc - a dict of config information for IRC
  12. * config.schedule() - returns a list of tasks scheduled to run now
  13. """
  14. import json
  15. from os import makedirs, path
  16. from lib import blowfish
  17. script_dir = path.dirname(path.abspath(__file__))
  18. root_dir = path.split(script_dir)[0]
  19. config_path = path.join(root_dir, "config.json")
  20. _config = None # holds data loaded from our config file
  21. # set our three easy-config-access global variables to None
  22. components, wiki, irc = (None, None, None)
  23. def load_config():
  24. """Load data from our JSON config file (config.json) into _config."""
  25. global _config
  26. with open(config_path, 'r') as fp:
  27. try:
  28. _config = json.load(fp)
  29. except ValueError as error:
  30. print "Error parsing config file {0}:".format(config_path)
  31. print error
  32. exit(1)
  33. def verify_config():
  34. """Check to see if we have a valid config file, and if not, notify the
  35. user. If there is no config file at all, offer to make one; otherwise,
  36. exit. If everything goes well, return True if stored passwords are
  37. encrypted in the file, or False if they are not."""
  38. if path.exists(config_path):
  39. load_config()
  40. try:
  41. return _config["encryptPasswords"] # are passwords encrypted?
  42. except KeyError:
  43. return False # assume passwords are not encrypted by default
  44. else:
  45. print "You haven't configured the bot yet!"
  46. choice = raw_input("Would you like to do this now? [y/n] ")
  47. if choice.lower().startswith("y"):
  48. return make_new_config()
  49. else:
  50. exit()
  51. def parse_config(key):
  52. """Store data from our config file in three global variables for easy
  53. access, and use the key to unencrypt passwords. Catch password decryption
  54. errors and report them to the user."""
  55. global components, wiki, irc
  56. load_config() # we might be re-loading unnecessarily here, but no harm in
  57. # that!
  58. try:
  59. components = _config["components"]
  60. except KeyError:
  61. components = []
  62. try:
  63. wiki = _config["wiki"]
  64. except KeyError:
  65. wiki = {}
  66. try:
  67. irc = _config["irc"]
  68. except KeyError:
  69. irc = {}
  70. try:
  71. try:
  72. if _config["encryptPasswords"]:
  73. decrypt(key, "wiki['password']")
  74. decrypt(key, "irc['frontend']['nickservPassword']")
  75. decrypt(key, "irc['watcher']['nickservPassword']")
  76. except KeyError:
  77. pass
  78. except blowfish.BlowfishError as error:
  79. print "\nError decrypting passwords:"
  80. print "{0}: {1}.".format(error.__class__.__name__, error)
  81. exit(1)
  82. def decrypt(key, item):
  83. """Decrypt 'item' with blowfish.decrypt() using the given key and set it to
  84. the decrypted result. 'item' should be a string, like
  85. decrypt(key, "wiki['password']"), NOT decrypt(key, wiki['password'),
  86. because that won't work."""
  87. global irc, wiki
  88. try:
  89. result = blowfish.decrypt(key, eval(item))
  90. except KeyError:
  91. return
  92. exec "{0} = result".format(item)
  93. def schedule(minute, hour, month_day, month, week_day):
  94. """Return a list of tasks that are scheduled to run at the time specified
  95. by the function arguments. The schedule data comes from our config file's
  96. 'schedule' field, which is stored as _config["schedule"]. Call this
  97. function with config.schedule(args)."""
  98. tasks = [] # tasks to run this turn, each as a tuple of either (task_name,
  99. # kwargs), or just task_name
  100. now = {"minute": minute, "hour": hour, "month_day": month_day,
  101. "month": month, "week_day": week_day}
  102. try:
  103. data = _config["schedule"]
  104. except KeyError:
  105. data = []
  106. for event in data:
  107. do = True
  108. for key, value in now.items():
  109. try:
  110. requirement = event[key]
  111. except KeyError:
  112. continue
  113. if requirement != value:
  114. do = False
  115. break
  116. if do:
  117. try:
  118. tasks.extend(event["tasks"])
  119. except KeyError:
  120. pass
  121. return tasks
  122. def make_new_config():
  123. """Make a new config file based on the user's input."""
  124. makedirs(config_dir)
  125. encrypt = raw_input("Would you like to encrypt passwords stored in " +
  126. "config.json? [y/n] ")
  127. if encrypt.lower().startswith("y"):
  128. is_encrypted = True
  129. else:
  130. is_encrypted = False
  131. return is_encrypted