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.

155 lines
5.9 KiB

  1. # -*- coding: utf-8 -*-
  2. #
  3. # Copyright (C) 2009-2015 Ben Kurtovic <ben.kurtovic@gmail.com>
  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:
  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().__init()`` first.
  44. 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. number = self.config.tasks.get(self.name, {}).get("number")
  50. if number is not None:
  51. self.number = number
  52. self.setup()
  53. def __repr__(self):
  54. """Return the canonical string representation of the Task."""
  55. res = "Task(name={0!r}, number={1!r}, bot={2!r})"
  56. return res.format(self.name, self.number, self.bot)
  57. def __str__(self):
  58. """Return a nice string representation of the Task."""
  59. res = "<Task {0} ({1}) of {2}>"
  60. return res.format(self.name, self.number, self.bot)
  61. def setup(self):
  62. """Hook called immediately after the task is loaded.
  63. Does nothing by default; feel free to override.
  64. """
  65. pass
  66. def run(self, **kwargs):
  67. """Main entry point to run a given task.
  68. This is called directly by :py:meth:`tasks.start()
  69. <earwigbot.managers.TaskManager.start>` and is the main way to make a
  70. task do stuff. *kwargs* will be any keyword arguments passed to
  71. :py:meth:`~earwigbot.managers.TaskManager.start`, which are entirely
  72. optional.
  73. """
  74. pass
  75. def unload(self):
  76. """Hook called immediately before the task is unloaded.
  77. Does nothing by default; feel free to override.
  78. """
  79. pass
  80. def make_summary(self, comment):
  81. """Make an edit summary by filling in variables in a config value.
  82. :py:attr:`config.wiki["summary"] <earwigbot.config.BotConfig.wiki>` is
  83. used, where ``$2`` is replaced by the main summary body, given by the
  84. *comment* argument, and ``$1`` is replaced by the task number.
  85. If the config value is not found, we'll just return *comment* as-is.
  86. """
  87. try:
  88. summary = self.bot.config.wiki["summary"]
  89. except KeyError:
  90. return comment
  91. return summary.replace("$1", str(self.number)).replace("$2", comment)
  92. def shutoff_enabled(self, site=None):
  93. """Return whether on-wiki shutoff is enabled for this task.
  94. We check a certain page for certain content. This is determined by
  95. our config file: :py:attr:`config.wiki["shutoff"]["page"]
  96. <earwigbot.config.BotConfig.wiki>` is used as the title, with any
  97. embedded ``$1`` replaced by our username and ``$2`` replaced by the
  98. task number; and :py:attr:`config.wiki["shutoff"]["disabled"]
  99. <earwigbot.config.BotConfig.wiki>` is used as the content.
  100. If the page has that exact content or the page does not exist, then
  101. shutoff is "disabled", meaning the bot is supposed to run normally, and
  102. we return ``False``. If the page's content is something other than
  103. what we expect, shutoff is enabled, and we return ``True``.
  104. If a site is not provided, we'll try to use :py:attr:`self.site <site>`
  105. if it's set. Otherwise, we'll use our default site.
  106. """
  107. if not site:
  108. if hasattr(self, "site"):
  109. site = getattr(self, "site")
  110. else:
  111. site = self.bot.wiki.get_site()
  112. try:
  113. cfg = self.config.wiki["shutoff"]
  114. except KeyError:
  115. return False
  116. title = cfg.get("page", "User:$1/Shutoff/Task $2")
  117. username = site.get_user().name
  118. title = title.replace("$1", username).replace("$2", str(self.number))
  119. page = site.get_page(title)
  120. try:
  121. content = page.get()
  122. except exceptions.PageNotFoundError:
  123. return False
  124. if content == cfg.get("disabled", "run"):
  125. return False
  126. self.logger.warn("Emergency task shutoff has been enabled!")
  127. return True