A Python robot that edits Wikipedia and interacts with people over IRC https://en.wikipedia.org/wiki/User:EarwigBot
您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

86 行
2.9 KiB

  1. # -*- coding: utf-8 -*-
  2. import config
  3. import wiki
  4. class BaseTask(object):
  5. """A base class for bot tasks that edit Wikipedia."""
  6. name = None
  7. number = 0
  8. def __init__(self):
  9. """Constructor for new tasks.
  10. This is called once immediately after the task class is loaded by
  11. the task manager (in tasks._load_task()).
  12. """
  13. pass
  14. def run(self, **kwargs):
  15. """Main entry point to run a given task.
  16. This is called directly by tasks.start() and is the main way to make a
  17. task do stuff. kwargs will be any keyword arguments passed to start()
  18. which are entirely optional.
  19. The same task instance is preserved between runs, so you can
  20. theoretically store data in self (e.g.
  21. start('mytask', action='store', data='foo')) and then use it later
  22. (e.g. start('mytask', action='save')).
  23. """
  24. pass
  25. def make_summary(self, comment):
  26. """Makes an edit summary by filling in variables in a config value.
  27. config.wiki["summary"] is used, where $2 is replaced by the main
  28. summary body, given as a method arg, and $1 is replaced by the task
  29. number.
  30. If the config value is not found, we just return the arg as-is.
  31. """
  32. try:
  33. summary = config.wiki["summary"]
  34. except KeyError:
  35. return comment
  36. return summary.replace("$1", str(self.number)).replace("$2", comment)
  37. def shutoff_enabled(self, site=None):
  38. """Returns whether on-wiki shutoff is enabled for this task.
  39. We check a certain page for certain content. This is determined by
  40. our config file: config.wiki["shutoff"]["page"] is used as the title,
  41. with $1 replaced by our username and $2 replaced by the task number,
  42. and config.wiki["shutoff"]["disabled"] is used as the content.
  43. If the page has that content or the page does not exist, then shutoff
  44. is "disabled", meaning the bot is supposed to run normally, and we
  45. return False. If the page's content is something other than what we
  46. expect, shutoff is enabled, and we return True.
  47. If a site is not provided, we'll try to use self.site if it's set.
  48. Otherwise, we'll use our default site.
  49. """
  50. if not site:
  51. try:
  52. site = self.site
  53. except AttributeError:
  54. site = wiki.get_site()
  55. try:
  56. cfg = config.wiki["shutoff"]
  57. except KeyError:
  58. return False
  59. title = cfg.get("page", "User:$1/Shutoff/Task $2")
  60. username = site.get_user().name()
  61. title = title.replace("$1", username).replace("$2", self.number)
  62. page = site.get_page(title)
  63. try:
  64. content = page.get()
  65. except wiki.PageNotFoundError:
  66. return False
  67. if content == cfg.get("disabled", "run"):
  68. return False
  69. return True