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.

129 lines
5.1 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. import imp
  23. from earwigbot.irc import IRCConnection, RC
  24. __all__ = ["Watcher"]
  25. class Watcher(IRCConnection):
  26. """
  27. **EarwigBot: IRC Watcher Component**
  28. The IRC watcher runs on a wiki recent-changes server and listens for
  29. edits. Users cannot interact with this part of the bot. When an event
  30. occurs, we run it through some rules stored in our working directory under
  31. :file:`rules.py`, which can result in wiki bot tasks being started or
  32. messages being sent to channels on the IRC frontend.
  33. """
  34. def __init__(self, bot):
  35. self.bot = bot
  36. cf = bot.config.irc["watcher"]
  37. super().__init__(cf["host"], cf["port"], cf["nick"], cf["ident"],
  38. cf["realname"], bot.logger.getChild("watcher"))
  39. self._prepare_process_hook()
  40. self._connect()
  41. def __repr__(self):
  42. """Return the canonical string representation of the Watcher."""
  43. res = "Watcher(host={0!r}, port={1!r}, nick={2!r}, ident={3!r}, realname={4!r}, bot={5!r})"
  44. return res.format(self.host, self.port, self.nick, self.ident,
  45. self.realname, self.bot)
  46. def __str__(self):
  47. """Return a nice string representation of the Watcher."""
  48. res = "<Watcher {0}!{1} at {2}:{3}>"
  49. return res.format(self.nick, self.ident, self.host, self.port)
  50. def _process_message(self, line):
  51. """Process a single message from IRC."""
  52. if line[1] == "PRIVMSG":
  53. chan = line[2]
  54. # Ignore messages originating from channels not in our list, to
  55. # prevent someone PMing us false data:
  56. if chan not in self.bot.config.irc["watcher"]["channels"]:
  57. return
  58. msg = " ".join(line[3:])[1:]
  59. rc = RC(chan, msg) # New RC object to store this event's data
  60. rc.parse() # Parse a message into pagenames, usernames, etc.
  61. self._process_rc_event(rc)
  62. self.bot.commands.call("rc", rc)
  63. # When we've finished starting up, join all watcher channels:
  64. elif line[1] == "376":
  65. for chan in self.bot.config.irc["watcher"]["channels"]:
  66. self.join(chan)
  67. def _prepare_process_hook(self):
  68. """Create our RC event process hook from information in rules.py.
  69. This will get put in the function self._process_hook, which takes the
  70. Bot object and an RC object and returns a list of frontend channels to
  71. report this event to.
  72. """
  73. # Set a default RC process hook that does nothing:
  74. self._process_hook = lambda bot, rc: ()
  75. path = self.bot.config.root_dir
  76. try:
  77. f, path, desc = imp.find_module("rules", [path])
  78. except ImportError:
  79. return
  80. try:
  81. module = imp.load_module("rules", f, path, desc)
  82. except Exception:
  83. return
  84. finally:
  85. f.close()
  86. self._process_hook_module = module
  87. try:
  88. self._process_hook = module.process
  89. except AttributeError:
  90. e = "RC event rules imported correctly, but no process(bot, rc) function was found"
  91. self.logger.error(e)
  92. return
  93. def _process_rc_event(self, rc):
  94. """Process a recent change event from IRC (or, an RC object).
  95. The actual processing is configurable, so we don't have that hard-coded
  96. here. We simply call our process hook (self._process_hook), created by
  97. self._prepare_process_hook() from information in the "rules" section of
  98. our config.
  99. """
  100. chans = self._process_hook(self.bot, rc)
  101. with self.bot.component_lock:
  102. frontend = self.bot.frontend
  103. if chans and frontend and not frontend.is_stopped():
  104. pretty = rc.prettify()
  105. if len(pretty) > 400:
  106. msg = pretty[:397] + "..."
  107. else:
  108. msg = pretty[:400]
  109. for chan in chans:
  110. frontend.say(chan, msg)