A Python robot that edits Wikipedia and interacts with people over IRC https://en.wikipedia.org/wiki/User:EarwigBot
Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

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