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.

166 line
6.4 KiB

  1. # -*- coding: utf-8 -*-
  2. #
  3. # Copyright (C) 2009-2012 by 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. """
  23. EarwigBot's IRC Command Manager
  24. This package provides the IRC "commands" used by the bot's front-end component.
  25. This module contains the BaseCommand class (import with
  26. `from earwigbot.commands import BaseCommand`) and an internal CommandManager
  27. class. This can be accessed through `bot.commands`.
  28. """
  29. import imp
  30. from os import listdir, path
  31. from re import sub
  32. from threading import Lock
  33. __all__ = ["BaseCommand", "CommandManager"]
  34. class BaseCommand(object):
  35. """A base class for commands on IRC.
  36. This docstring is reported to the user when they use !help <command>.
  37. """
  38. # This is the command's name, as reported to the user when they use !help:
  39. name = None
  40. # Hooks are "msg", "msg_private", "msg_public", and "join". "msg" is the
  41. # default behavior; if you wish to override that, change the value in your
  42. # command subclass:
  43. hooks = ["msg"]
  44. def __init__(self, bot):
  45. """Constructor for new commands.
  46. This is called once when the command is loaded (from
  47. commands._load_command()). `bot` is out base Bot object. Generally you
  48. shouldn't need to override this; if you do, call
  49. super(Command, self).__init__() first.
  50. """
  51. self.bot = bot
  52. self.logger = bot.commands.getLogger(self.name)
  53. def _execute(self, data):
  54. """Make a quick connection alias and then process() the message."""
  55. self.connection = self.bot.frontend
  56. self.process(data)
  57. def check(self, data):
  58. """Return whether this command should be called in response to 'data'.
  59. Given a Data() instance, return True if we should respond to this
  60. activity, or False if we should ignore it or it doesn't apply to us.
  61. Most commands return True if data.command == self.name, otherwise they
  62. return False. This is the default behavior of check(); you need only
  63. override it if you wish to change that.
  64. """
  65. return data.is_command and data.command == self.name
  66. def process(self, data):
  67. """Main entry point for doing a command.
  68. Handle an activity (usually a message) on IRC. At this point, thanks
  69. to self.check() which is called automatically by the command handler,
  70. we know this is something we should respond to, so something like
  71. `if data.command != "command_name": return` is usually unnecessary.
  72. Note that
  73. """
  74. pass
  75. class CommandManager(object):
  76. def __init__(self, bot):
  77. self.bot = bot
  78. self.logger = bot.logger.getLogger("commands")
  79. self._commands = {}
  80. self._command_access_lock = Lock()
  81. def _load_command(self, name, path):
  82. """Load a specific command from a module, identified by name and path.
  83. We'll first try to import it using imp magic, and if that works, make
  84. an instance of the 'Command' class inside (assuming it is an instance
  85. of BaseCommand), add it to self._commands, and log the addition. Any
  86. problems along the way will either be ignored or logged.
  87. """
  88. f, path, desc = imp.find_module(name, [path])
  89. try:
  90. module = imp.load_module(name, f, path, desc)
  91. except Exception:
  92. e = "Couldn't load module {0} from {1}"
  93. self.logger.exception(e.format(name, path))
  94. return
  95. finally:
  96. f.close()
  97. try:
  98. command_class = module.Command
  99. except AttributeError:
  100. return # No command in this module
  101. try:
  102. command = command_class(self.bot)
  103. except Exception:
  104. e = "Error initializing Command() class in {0} (from {1})"
  105. self.logger.exception(e.format(name, path))
  106. return
  107. if not isinstance(command, BaseCommand):
  108. return
  109. self._commands[command.name] = command
  110. self.logger.debug("Added command {0}".format(command.name))
  111. def load(self):
  112. """Load (or reload) all valid commands into self._commands."""
  113. with self._command_access_lock:
  114. self._commands.clear()
  115. dirs = [path.join(path.dirname(__file__), "commands"),
  116. path.join(self.bot.config.root_dir, "commands")]
  117. for dir in dirs:
  118. files = listdir(dir)
  119. files = [sub("\.pyc?$", "", f) for f in files if f[0] != "_"]
  120. files = list(set(files)) # Remove duplicates
  121. for filename in sorted(files):
  122. self._load_command(filename, dir)
  123. msg = "Found {0} commands: {1}"
  124. commands = ", ".join(self._commands.keys())
  125. self.logger.info(msg.format(len(self._commands), commands))
  126. def get_all(self):
  127. """Return our dict of all loaded commands."""
  128. return self._commands
  129. def check(self, hook, data):
  130. """Given an IRC event, check if there's anything we can respond to."""
  131. with self._command_access_lock:
  132. for command in self._commands.values():
  133. if hook in command.hooks:
  134. if command.check(data):
  135. try:
  136. command._execute(data)
  137. except Exception:
  138. e = "Error executing command '{0}':"
  139. self.logger.exception(e.format(data.command))
  140. break