""" ircbot.py - basic IRC bot implementation v0.1 Copyright (C) 2007 Jay Sherby I originally made this basic implementation of an IRC bot for a bot called MafiaBot. I purposely wrote this class to be very general so I can use it on other IRC bots I may choose to write in the future. This actual file was never meant to be run as-is. It is meant to be imported in other programs to utilize the Bot class. """ import sys, socket, string, asyncore, asynchat class Bot(asynchat.async_chat): def __init__(self, nick, channels, verbose = None): asynchat.async_chat.__init__(self) self.set_terminator('\r\n') self.buffer = [] self.nick = nick self.user = nick self.name = nick if verbose is None: verbose = False self.verbose = verbose self.channels = channels def write(self, args, text = None): if text is not None: message = ' '.join(args) + ' :' + text self.push(message + '\r\n') else: message = ' '.join(args) self.push(message + '\r\n') if self.verbose: print '[CLIENT] ' + message def run(self, host, port = 6667): self.initiate_connect(host, port) def initiate_connect(self, host, port): self.create_socket(socket.AF_INET, socket.SOCK_STREAM) try: self.connect((host, port)) except socket.error, (errno, strerror): print >> sys.stderr, "Socket Error(%s): %s" % (errno, strerror) self.close() asyncore.loop() def handle_connect(self): self.write(('NICK', self.nick)) self.write(('USER', self.user, '+iw', self.nick), self.name) for channel in self.channels: self.write(('JOIN', channel)) def collect_incoming_data(self, data): self.buffer.append(data) def found_terminator(self): message = self.buffer.pop() if self.verbose: print '[SERVER] ' + message if message[:4] == 'PING': self.write(('PONG', message[5:])) #else: