Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on Jun 20th, 2012  |  syntax: None  |  size: 1.90 KB  |  hits: 12  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1.  
  2.  
  3. # Just some dictionary to hold references to functions to be called when a
  4. # particular command comes in. The key is the command name, e.g. "PRIVMSG", the
  5. # value is a list of functions.
  6. COMMAND_HANDLERS = {}
  7.  
  8. def register_command(command, callback):
  9.     # Get the existing list for 'command' if one exists, otherwise create a new
  10.     # one and add it to the dictinoary.
  11.     lst = COMMAND_HANDLERS.setdefault(command, [])
  12.     # Append the callback to the list.
  13.     lst.append(callback)
  14.  
  15.  
  16.  
  17. class Bot:
  18.     # Convenience method to make it easy to reply from a function below
  19.     def send(self, fmt, *args):
  20.         if args:
  21.             fmt %= args
  22.         self.sock.send(fmt + '\r\n')
  23.  
  24.     def quit(self):
  25.         self.running = False
  26.  
  27.     # Handle a single received line.
  28.     def do_once(self):
  29.         # Split up the line a bit, figure out what the command was.
  30.         self.mybuff = self.sock.recv ( 4096 )
  31.         command, rest = self.mybuff.split(' ', 1)
  32.  
  33.         # Lookup the function list for the command in the handler dictionary,
  34.         # returning an empty list of no list exists for the current command in
  35.         # that dictinoary.
  36.         for callback in COMMAND_HANDLERS.get(command, []):
  37.             # For each callback function in the list, call it with a reference
  38.             # to the bot, and a reference to the received line.
  39.             callback(self, self.mybuff)
  40.  
  41.     def run(self):
  42.         while self.running:
  43.             self.do_once() # just avoids mad indentation
  44.  
  45.  
  46.  
  47.  
  48. def handle_ping(bot, buf):
  49.     bot.send('PONG %s', buf.split()[1] )
  50.  
  51. register_command('PING', handle_ping)
  52.  
  53.  
  54.  
  55. def handle_command(bot, buf):
  56.     if '!bot' not in buf:
  57.         return
  58.  
  59.     bits = buf.split()
  60.     if len(bits) < 2:
  61.         return
  62.  
  63.     command = bits[1]
  64.     if command == 'quit':
  65.         bot.send('QUIT')
  66.         bot.stop()
  67.  
  68. register_command('PRIVMSG', handle_command)