A Python robot that edits Wikipedia and interacts with people over IRC https://en.wikipedia.org/wiki/User:EarwigBot
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

144 lines
5.6 KiB

  1. # -*- coding: utf-8 -*-
  2. #
  3. # Copyright (C) 2009-2012 Ben Kurtovic <ben.kurtovic@verizon.net>
  4. #
  5. # Permission is hereby granted, free of charge, to any person obtaining a copy
  6. # of this software and associated documentation files (the "Software"), to deal
  7. # in the Software without restriction, including without limitation the rights
  8. # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  9. # copies of the Software, and to permit persons to whom the Software is
  10. # furnished to do so, subject to the following conditions:
  11. #
  12. # The above copyright notice and this permission notice shall be included in
  13. # all copies or substantial portions of the Software.
  14. #
  15. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16. # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  17. # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  18. # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  19. # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  20. # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  21. # SOFTWARE.
  22. from earwigbot import exceptions
  23. from earwigbot import wiki
  24. __all__ = ["Task"]
  25. class Task(object):
  26. """
  27. **EarwigBot: Base Bot Task**
  28. This package provides built-in wiki bot "tasks" EarwigBot runs. Additional
  29. tasks can be installed as plugins in the bot's working directory.
  30. This class (import with ``from earwigbot.tasks import Task``) can be
  31. subclassed to create custom bot tasks.
  32. To run a task, use :py:meth:`bot.tasks.start(name, **kwargs)
  33. <earwigbot.managers.TaskManager.start>`. ``**kwargs`` get passed to the
  34. Task's :meth:`run` method.
  35. """
  36. name = None
  37. number = 0
  38. def __init__(self, bot):
  39. """Constructor for new tasks.
  40. This is called once immediately after the task class is loaded by
  41. the task manager (in :py:meth:`tasks.load()
  42. <earwigbot.managers._ResourceManager.load>`). Don't override this
  43. directly; if you do, remember to place ``super(Task, self).__init()``
  44. first. Use :py:meth:`setup` for typical task-init/setup needs.
  45. """
  46. self.bot = bot
  47. self.config = bot.config
  48. self.logger = bot.tasks.logger.getChild(self.name)
  49. self.setup()
  50. def __repr__(self):
  51. """Return the canonical string representation of the Task."""
  52. res = "Task(name={0!r}, number={1!r}, bot={2!r})"
  53. return res.format(self.name, self.number, self.bot)
  54. def __str__(self):
  55. """Return a nice string representation of the Task."""
  56. res = "<Task {0} ({1}) of {2}>"
  57. return res.format(self.name, self.number, self.bot)
  58. def setup(self):
  59. """Hook called immediately after the task is loaded.
  60. Does nothing by default; feel free to override.
  61. """
  62. pass
  63. def run(self, **kwargs):
  64. """Main entry point to run a given task.
  65. This is called directly by :py:meth:`tasks.start()
  66. <earwigbot.managers.TaskManager.start>` and is the main way to make a
  67. task do stuff. *kwargs* will be any keyword arguments passed to
  68. :py:meth:`~earwigbot.managers.TaskManager.start`, which are entirely
  69. optional.
  70. """
  71. pass
  72. def make_summary(self, comment):
  73. """Make an edit summary by filling in variables in a config value.
  74. :py:attr:`config.wiki["summary"] <earwigbot.config.BotConfig.wiki>` is
  75. used, where ``$2`` is replaced by the main summary body, given by the
  76. *comment* argument, and ``$1`` is replaced by the task number.
  77. If the config value is not found, we'll just return *comment* as-is.
  78. """
  79. try:
  80. summary = self.bot.config.wiki["summary"]
  81. except KeyError:
  82. return comment
  83. return summary.replace("$1", str(self.number)).replace("$2", comment)
  84. def shutoff_enabled(self, site=None):
  85. """Return whether on-wiki shutoff is enabled for this task.
  86. We check a certain page for certain content. This is determined by
  87. our config file: :py:attr:`config.wiki["shutoff"]["page"]
  88. <earwigbot.config.BotConfig.wiki>` is used as the title, with any
  89. embedded ``$1`` replaced by our username and ``$2`` replaced by the
  90. task number; and :py:attr:`config.wiki["shutoff"]["disabled"]
  91. <earwigbot.config.BotConfig.wiki>` is used as the content.
  92. If the page has that exact content or the page does not exist, then
  93. shutoff is "disabled", meaning the bot is supposed to run normally, and
  94. we return ``False``. If the page's content is something other than
  95. what we expect, shutoff is enabled, and we return ``True``.
  96. If a site is not provided, we'll try to use :py:attr:`self.site <site>`
  97. if it's set. Otherwise, we'll use our default site.
  98. """
  99. if not site:
  100. if hasattr(self, "site"):
  101. site = getattr(self, "site")
  102. else:
  103. site = self.bot.wiki.get_site()
  104. try:
  105. cfg = self.config.wiki["shutoff"]
  106. except KeyError:
  107. return False
  108. title = cfg.get("page", "User:$1/Shutoff/Task $2")
  109. username = site.get_user().name
  110. title = title.replace("$1", username).replace("$2", str(self.number))
  111. page = site.get_page(title)
  112. try:
  113. content = page.get()
  114. except exceptions.PageNotFoundError:
  115. return False
  116. if content == cfg.get("disabled", "run"):
  117. return False
  118. self.logger.warn("Emergency task shutoff has been enabled!")
  119. return True