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.

68 lines
2.4 KiB

  1. # -*- coding: utf-8 -*-
  2. # A module to manage IRC commands.
  3. import os
  4. import traceback
  5. commands = []
  6. def init_commands(connection, silent=False):
  7. """load all valid command classes from irc/commmands/ into the commands variable"""
  8. files = os.listdir(os.path.join("irc", "commands")) # get all files in irc/commands/
  9. for f in files:
  10. if f.startswith("_") or not f.endswith(".py"): # ignore non-python files or files beginning with "_"
  11. continue
  12. module = f[:-3] # strip .py from end
  13. try:
  14. exec "from irc.commands import %s" % module
  15. except: # importing the file failed for some reason...
  16. if not silent:
  17. print "Couldn't load file %s:" % f
  18. traceback.print_exc()
  19. continue
  20. m = eval(module) # 'module' is a string, so get the actual object for processing
  21. process_module(connection, m)
  22. if not silent:
  23. pretty_cmnds = map(lambda c: c.__class__.__name__, commands)
  24. print "Found %s command classes: %s." % (len(commands), ', '.join(pretty_cmnds))
  25. def process_module(connection, module):
  26. """go through all objects in a module and add valid command classes to the commands variable"""
  27. global commands
  28. objects = dir(module)
  29. for this_obj in objects: # go through everything in the file
  30. obj = eval("module.%s" % this_obj) # this_obj is a string, so get the actual object corresponding to that string
  31. try:
  32. bases = obj.__bases__
  33. except AttributeError: # object isn't a valid class, so ignore it
  34. continue
  35. for base in bases:
  36. if base.__name__ == "BaseCommand": # this inherits BaseCommand, so it must be a command class
  37. command = obj(connection) # initialize a new command object
  38. commands.append(command)
  39. print "Added command class %s from %s..." % (this_obj, module.__name__)
  40. continue
  41. def get_commands():
  42. """get our commands"""
  43. return commands
  44. def check(hook, data):
  45. """given an event on IRC, check if there's anything we can respond to by calling each command class"""
  46. data.parse_args() # parse command arguments into data.command and data.args
  47. for command in commands:
  48. if command.get_hook() == hook:
  49. if command.check(data):
  50. command.process(data)
  51. break