
Untitled
By: a guest on
Jun 20th, 2012 | syntax:
None | size: 1.90 KB | hits: 12 | expires: Never
# Just some dictionary to hold references to functions to be called when a
# particular command comes in. The key is the command name, e.g. "PRIVMSG", the
# value is a list of functions.
COMMAND_HANDLERS = {}
def register_command(command, callback):
# Get the existing list for 'command' if one exists, otherwise create a new
# one and add it to the dictinoary.
lst = COMMAND_HANDLERS.setdefault(command, [])
# Append the callback to the list.
lst.append(callback)
class Bot:
# Convenience method to make it easy to reply from a function below
def send(self, fmt, *args):
if args:
fmt %= args
self.sock.send(fmt + '\r\n')
def quit(self):
self.running = False
# Handle a single received line.
def do_once(self):
# Split up the line a bit, figure out what the command was.
self.mybuff = self.sock.recv ( 4096 )
command, rest = self.mybuff.split(' ', 1)
# Lookup the function list for the command in the handler dictionary,
# returning an empty list of no list exists for the current command in
# that dictinoary.
for callback in COMMAND_HANDLERS.get(command, []):
# For each callback function in the list, call it with a reference
# to the bot, and a reference to the received line.
callback(self, self.mybuff)
def run(self):
while self.running:
self.do_once() # just avoids mad indentation
def handle_ping(bot, buf):
bot.send('PONG %s', buf.split()[1] )
register_command('PING', handle_ping)
def handle_command(bot, buf):
if '!bot' not in buf:
return
bits = buf.split()
if len(bits) < 2:
return
command = bits[1]
if command == 'quit':
bot.send('QUIT')
bot.stop()
register_command('PRIVMSG', handle_command)