def __init__(self, config): self.irc = IRC(config) self.annoying_user_messages = { user: deque([], maxlen=10) for user in ANNOYING_USERS } set_up_logging()
class ChatBot: def __init__(self, generalConfig, serverConfig, channel): self.general = generalConfig self.server = serverConfig self.channel = channel self.irc = IRC(self.server, self.channel) self.socket = self.irc.get_irc_socket_object() self.channel.startjobs(self.irc) def run(self): irc = self.irc sock = self.socket general = self.general while True: data = sock.recv(general['buffer_size']).rstrip() if len(data) == 0: pp('Connection was lost, reconnecting.') sock = self.irc.get_irc_socket_object() if general['debug']: datasplit = data.split('\n') for line in datasplit: pp(line, 'DEBUG') # check for ping, reply with pong irc.check_for_ping(data) if irc.check_for_message(data): message_dict = irc.get_message(data) channel = message_dict['channel'] message = message_dict['message'] username = message_dict['username'] ppi(channel, message, username) cleanmessage = message[1:] commandsplit = cleanmessage.split(' ')[0] # check if message is a command with no arguments if commands.is_valid_command(cleanmessage, self.channel) or commands.is_valid_command(commandsplit, self.channel): command = commands.get_command(cleanmessage if cleanmessage == commandsplit else commandsplit, self.channel) args = cleanmessage.split(' ') args.pop(0) if command: pp("{0} has executed !{1} in {2}".format(username, command.command, channel)) irc.send_message(command.execute(irc, self.channel, username, args)) else: pp("Invalid command !{0} from {1} in {2}".format(command.command, username, channel))
class Bot(object): def __init__(self, config): self.irc = IRC(config) self.annoying_user_messages = { user: deque([], maxlen=10) for user in ANNOYING_USERS } set_up_logging() def get_logs_for_user(self, username): with open("{0}.log".format(username), "r") as f: logs = f.read() return logs def format_response(self, response): return "{0}?".format(response.rstrip(".")) def send_message(self, channel, username, message): self.irc.send_message(channel, username, message) def is_annoying_user(self, username): if username in ANNOYING_USERS: return True return False def handle_annoying_user(self, channel, username, message): self.annoying_user_messages[username].add(message) text_model = markovify.NewlineText("\n".join( self.annoying_user_messages[username])) formatted_response = text_model.make_sentence() if formatted_response: self.send_message(channel, username, formatted_response) def run(self): while True: try: data = self.irc.next_message() if not self.irc.check_for_message(data): continue message_dict = self.irc.get_message(data) channel = message_dict["channel"] message = message_dict["message"] username = message_dict["username"] if self.is_annoying_user(username): self.handle_annoying_user(channel, username, message) except Exception as error: error_message = "{0}\n=>{1}".format(message_dict, error) with open("errors.txt", "a") as f: f.write(error_message)
def __init__(self, generalConfig, serverConfig, channel): self.general = generalConfig self.server = serverConfig self.channel = channel self.irc = IRC(self.server, self.channel) self.socket = self.irc.get_irc_socket_object() self.channel.startjobs(self.irc)
def rehash(self): if self.userfile is not None: self.userfile.save() if self.chanfile is not None: self.chanfile.save() from config import Config self.config = Config() del Config self.hooks = [] if self.irc is not None: del self.irc self.irc = IRC(self)
class Bot: irc = None thread = None session = None userfile = None chanfile = None socket = None config = None server = None buf = '' hooks = None def __init__(self): self.rehash() self.thread = _Thread(self) self.thread.start() self.userfile = Userfile(self.config.userfile) self.chanfile = Chanfile(self.config.chanfile) def rehash(self): if self.userfile is not None: self.userfile.save() if self.chanfile is not None: self.chanfile.save() from config import Config self.config = Config() del Config self.hooks = [] if self.irc is not None: del self.irc self.irc = IRC(self) def reconnect(self): # close connection, if any if self.socket is not None: self.socket.close() self.socket = None self.buf = '' # pick first server in list entry = self.config.servers[0] self.server = dict(addr=(entry[0], entry[1] or 6667,), password=entry[2]) # rotate server list self.config.servers.rotate() # determine address family try: addrinfo = socket.getaddrinfo(self.server['addr'][0], self.server['addr'][1]) self.server['proto'] = addrinfo[0][0] self.server['resolved'] = addrinfo[0][4] except: return # create socket self.socket = socket.socket(self.server['proto'], socket.SOCK_STREAM) # bind address, if any if self.config.bindaddr is not None: self.socket.bind(self.config.bindaddr) # operate in non-blocking mode self.socket.setblocking(0) # connect! try: self.socket.connect(self.server['resolved']) except socket.error as err: # operation in progress if err[0] != 115: self.socket = None # sleep for a little while time.sleep(0.1) # destroy previous session and start a new one if self.session is not None: del self.session self.session = Session() # send password, if any if self.server['password'] is not None: self.send('PASS %s' % (self.server['password'])) # register within server self.send('USER %s "" %s :%s' % (self.config.username, self.server['addr'][0], self.config.realname)) self.send('NICK %s' % (self.config.nickname)) def dispatch(self): while True: if not self.socket: self.reconnect() continue if self.socket is not None: line = self.readline() if line is not None: self.irc.process(line) def send(self, line, queue=0): if self.socket is not None: if queue == -1: try: self.socket.send(line + '\r\n') except socket.error as err: print err else: self.thread.queues[queue].append(line) def readline(self): # check stale bytes first if '\n' in self.buf: line, self.buf = self.buf.split('\n', 1) return line # sleep for a little while time.sleep(0.25) # read from socket try: tmp = self.socket.recv(4096) except socket.error as err: tmp = None # skip "would block" error if err[0] != 11: self.socket = None # if nothing read, nothing read if tmp is None: return None # append to stale self.buf = ''.join([self.buf, tmp]) \ .replace('\r', '\n') \ .replace('\n\n', '\n') # if something read, something read if '\n' in self.buf: line, self.buf = self.buf.split('\n', 1) return line # nothing read then return None def hook(self, event, callback): hooks = self.hooks.get(event, []) hooks.append(callback) self.hooks[event] = hooks def unnook(self, event, callback=None): if callback is None: del self.hooks[event] else: try: self.hooks.get(event, []).remove(callback) except: pass def fire(self, event, *kargs): [callback(*kargs) for callback in self.hooks.get(event, [])]
def main(): main_conf() opers = {} mainconf, tasks, cmds = ( ConfigParser.RawConfigParser(), ConfigParser.RawConfigParser(), ConfigParser.RawConfigParser(), ) mainconf._file, tasks._file, cmds._file = ("taeniurus.cfg", "tasks.cfg", "cmds.cfg") mainconf.read(mainconf._file) tasks.read(tasks._file) cmds.read(cmds._file) pidfile = mainconf.get("info", "pid file") logspath = mainconf.get("info", "logs path") irc = IRC() bgproc = Process(target=header, args=(irc.server, irc.port)) bgproc.start() client = irc.connect() if bgproc.is_alive(): bgproc.terminate() print "\nConnected successfully!" print "Connection: \033[1m\033[92m%s:%d\033[0m" % (irc.server, irc.port) print "Channel: \033[1m\033[92m%s\033[0m" % irc.channel daemon(pidfile) acc_den = 'irc.notice("Access is denied!", nick)' done_msg = 'irc.notice("Done.", nick)' while True: try: data = client.recv(1024) arg, nick, user, joined, window = irc.parse(data) for section in tasks.sections(): if tasks.get(section, "code"): try: exec tasks.get(section, "code") except: for op in opers: irc.notice("A problem in tasks config file!", op) irc.notice("File: %s" % tasks._file, op) irc.notice("Section: %s" % section, op) if arg: args = arg.split() if len(args) < 1: continue try: if args[0] == "!oper" and user not in opers.values() and args[1] and args[2]: if args[1] == mainconf.get("oper", "user"): if hashlib.md5(args[2]).hexdigest() == mainconf.get("oper", "passwd"): opers[nick] = user irc.notice("You are appended into opers list.", nick) else: irc.notice("User or password incorrect!", nick) else: irc.notice("User or password incorrect!", nick) if args[0] in cmds.sections(): if cmds.get(args[0], "access") == "oper" and user not in opers.values(): exec acc_den continue exec cmds.get(args[0], "code") except: irc.notice("It's either an argument error or I'm unable to do it.", nick) if args[0] == "!quit" and user in opers.values(): qmsg = " ".join(args[1:]) if len(args) >= 2 else "Leaving" irc.quit(qmsg) import signal pid = os.getpid() os.kill(int(pid), signal.SIGKILL) except: raise Error(data, logspath)