A Python robot that edits Wikipedia and interacts with people over IRC https://en.wikipedia.org/wiki/User:EarwigBot
Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

130 строки
5.1 KiB

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