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 4.9 KiB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152
  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."""
  37. if path.exists(config_path):
  38. load_config()
  39. try:
  40. return _config["encryptPasswords"] # are passwords encrypted?
  41. except KeyError:
  42. return False # assume passwords are not encrypted by default
  43. else:
  44. print "You haven't configured the bot yet!"
  45. choice = raw_input("Would you like to do this now? [y/n] ")
  46. if choice.lower().startswith("y"):
  47. return make_new_config()
  48. else:
  49. exit()
  50. def parse_config(key):
  51. """Store data from our config file in three global variables for easy
  52. access, and use the key to unencrypt passwords. Catch password decryption
  53. errors and report them to the user."""
  54. global components, wiki, irc
  55. load_config() # we might be re-loading unnecessarily here, but no harm in
  56. # that!
  57. try:
  58. components = _config["components"]
  59. except KeyError:
  60. components = []
  61. try:
  62. wiki = _config["wiki"]
  63. except KeyError:
  64. wiki = {}
  65. try:
  66. irc = _config["irc"]
  67. except KeyError:
  68. irc = {}
  69. try:
  70. try:
  71. if _config["encryptPasswords"]:
  72. decrypt(key, "wiki['password']")
  73. decrypt(key, "irc['frontend']['nickservPassword']")
  74. decrypt(key, "irc['watcher']['nickservPassword']")
  75. except KeyError:
  76. pass
  77. except blowfish.BlowfishError as error:
  78. print "\nError decrypting passwords:"
  79. print "{0}: {1}.".format(error.__class__.__name__, error)
  80. exit(1)
  81. def decrypt(key, item):
  82. """Decrypt 'item' with blowfish.decrypt() using the given key and set it to
  83. the decrypted result. 'item' should be a string, like
  84. decrypt(key, "wiki['password']"), NOT decrypt(key, wiki['password'),
  85. because that won't work."""
  86. global irc, wiki
  87. try:
  88. result = blowfish.decrypt(key, eval(item))
  89. except KeyError:
  90. return
  91. exec "{0} = result".format(item)
  92. def schedule(minute, hour, month_day, month, week_day):
  93. """Return a list of tasks that are scheduled to run at the time specified
  94. by the function arguments. The schedule data comes from our config file's
  95. 'schedule' field, which is stored as _config["schedule"]. Call this
  96. function with config.schedule(args)."""
  97. tasks = [] # tasks to run this turn, each as a tuple of either (task_name,
  98. # kwargs), or just task_name
  99. now = {"minute": minute, "hour": hour, "month_day": month_day,
  100. "month": month, "week_day": week_day}
  101. try:
  102. data = _config["schedule"]
  103. except KeyError:
  104. data = []
  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
  121. def make_new_config():
  122. """Make a new config file based on the user's input."""
  123. makedirs(config_dir)
  124. encrypt = raw_input("Would you like to encrypt passwords stored in " +
  125. "config.json? [y/n] ")
  126. if encrypt.lower().startswith("y"):
  127. is_encrypted = True
  128. else:
  129. is_encrypted = False
  130. return is_encrypted