def main(): # Define parser options parser = optparse.OptionParser() parser.add_option('-L', '--log-level', dest='log_level', help='Override the default logging level. Valid: debug, info, warning error, critical') parser.add_option('-c', '--conf-dir', dest='conf_dir', default=os.path.join(os.path.dirname(os.path.abspath(__file__)), 'confs'), help='Override the default conf directory.') options, args = parser.parse_args() # Set the default logging level, if valid if options.log_level is not None: LEVELS = {'debug': logging.DEBUG, 'info': logging.INFO, 'warning': logging.WARNING, 'error': logging.ERROR, 'critical': logging.CRITICAL} level = LEVELS.get(options.log_level, logging.NOTSET) logging.basicConfig(level=level) # Check conf dir exists and retrieve list of yaml files if not os.path.isdir(options.conf_dir): print 'Config dir "%s" does not exist or is not a directory' % options.conf_dir sys.exit(1) conf_files = [] for fname in os.listdir(options.conf_dir): if fname.endswith('.yaml'): conf_files.append(os.path.join(options.conf_dir, fname)) # Load one client for each yaml file, and start app = IRCApp() for conf_file in conf_files: app.addClient(BotClient(conf_file)) app.run()
class Minion(Thread): def __init__(self, nick, room="#minions", description="This minion does not have a description."): Thread.__init__(self) self.nick = nick self.description = description self.room = room self.matches = [] def connect_callback(cli): print "Connected." # helpers.join(cli, "#inforum") self.app = IRCApp() self.client = IRCClient(host="irc.imaginarynet.org.uk", port=6667, nick=nick, connect_cb=connect_callback) self.client.command_handler = MyHandler(self, self.msg_handler, self.room) self.app.addClient(self.client) # Default minion commands self.register("GO AWAY", lambda: helpers.quit(self.client), require.name) self.register("WHO ARE YOU", lambda: self.description, require.name) def run(self): thread = Thread() self.app.run() print "Minion started." def wait(self): self.join() def write(self, msg): helpers.msg(self.client, self.room, msg) def msg_handler(self, msg): """Called when the bot recieves a message.""" print "Minion recieved: %s" % msg simplemsg = simplify(msg) # Check to see if any of the registered matches match this message. for (match, callback, requires) in self.matches: if simplemsg.find(match) > -1: # Test if all of the requires for the match succeed. if min([require(self, simplemsg) for require in requires]): print "Calling callback for %s" % match # Call the callback, if it returns a string, send it to the client. result = callback() if isinstance(result, str): self.write(result) else: print "Callback didn't return a string." def register(self, match, callback, requires): """Registers a string to be matched against all received messages, with a callback to execute if the string matches, and a list of requirements that must be fulfilled before the callback is called.""" if not isinstance(requires, list): requires = [requires] self.matches += [(match, callback, requires)]
def __init__(self): IRCApp.__init__(self) self.conf = configuration.Configuration() self.conf.load("../config/flipper.conf") client = IRCClient(commandhandler.CommandHandler, host=self.conf.SERVER, port=self.conf.PORT, nick=self.conf.NICK, blocking=True) client.command_handler.channels_to_join = self.conf.CHANNELS self.addClient(client, autoreconnect=True)
def make_app(): import logging import sys logging.basicConfig(level=logging.DEBUG, format='%(asctime)s %(levelname)s %(message)s') def connect_cb(c): for room in sys.argv[2:]: helpers.join(c, '#%s' % room) app = IRCApp() cli = IRCClient(LoggingHandler, nick="oyoyo", host=sys.argv[1], port=6667, connect_cb=connect_cb) app.addClient(cli) def msg_dunk(): helpers.msg(cli, "#test", "hello!") app.addTimer(15, msg_dunk) app.run()
def __init__(self, nick, room="#minions", description="This minion does not have a description."): Thread.__init__(self) self.nick = nick self.description = description self.room = room self.matches = [] def connect_callback(cli): print "Connected." # helpers.join(cli, "#inforum") self.app = IRCApp() self.client = IRCClient(host="irc.imaginarynet.org.uk", port=6667, nick=nick, connect_cb=connect_callback) self.client.command_handler = MyHandler(self, self.msg_handler, self.room) self.app.addClient(self.client) # Default minion commands self.register("GO AWAY", lambda: helpers.quit(self.client), require.name) self.register("WHO ARE YOU", lambda: self.description, require.name)
def _cmd_UTC(self, nick, mask, chan, arg): """utc - Responds with the current time, UTC.""" self._msg(chan, "%s: %s" % (nick, datetime.datetime.utcnow().replace(microsecond=0).isoformat(' '))) if __name__ == '__main__': if len(sys.argv) > 1: conf = sys.argv[1] else: conf = 'config.yaml' with open(conf) as f: config = yaml.safe_load(f) app = IRCApp() schema = CorpSchema(config['database']['path']) access = CorpAccess(config, schema) clients = {} for server, conf in config['servers'].iteritems(): client = IRCClient( CorpHandler, host=server, port=conf['port'], nick=conf['nick'], real_name=conf['name'], ) clients[server] = client app.addClient(client, autoreconnect=True)
def main(): argparser = argparse.ArgumentParser(description="P1tr TNG - IRC bot.") argparser.add_argument("-c", "--conf", help="path to configuration file", action="store", default="config.cfg") argparser.add_argument( "-m", "--mkconf", help="launches the configuration wizard", action="store_const", const=True, default=False ) argparser.add_argument( "-t", "--test", help="runs plugin test suites and exits afterwards. Requires valid \ configuration", action="store_const", const=True, default=False, ) args = argparser.parse_args() clients = dict() connections = dict() config_path = args.conf # Launch configuration wizard, if desired, before bot launch if args.mkconf: config_path = config_wizard() config_loaded = False while not config_loaded: try: config = load_config(config_path) config_loaded = True except BotError: error("No configuration file at the given path. Starting wizard...") config_path = config_wizard() loglevel = read_or_default(config, "General", "loglevel", logging.ERROR, lambda val: getattr(logging, val)) set_loglevel(loglevel) # Run tests if the flag is set if args.test: run_tests(config) return # Exit after tests application = IRCApp() application.sleep_time = read_or_default(config, "General", "sleeptime", 0.2, lambda val: float(val)) info("Connecting to servers...") for section in config: if section != "General" and not "|" in section: try: clients[section] = IRCClient( BotHandler, host=section, port=config.getint(section, "port"), nick=config.get(section, "nick"), connect_cb=on_connect, ) clients[section].command_handler.load_config(config) clients[section].command_handler.load_plugins() application.addClient(clients[section], autoreconnect=True) except (KeyError, configparser.NoOptionError): pass # Not a server. except ValueError as ve: info("Config section " + section + " will be ignored: " + str(ve)) info("Startup complete.") try: application.run() except KeyboardInterrupt: for client in clients: clients[client].command_handler.exit() application.stop() info("All clients terminated. Goodbye!")
def make_app(): """ main entry point """ print "make_app()" import logging import sys from oyoyo_bot import db global app global config config = make_config() logging.basicConfig(level=getattr(logging, config['logging']['level']), format='%(asctime)s %(levelname)s %(message)s', filename=config['logging']['filename'], filemode=config['logging']['filemode']) db.engine = db.create_engine(config['database']['uri'], echo=config['database'].as_bool('echo')) db.Session.configure(bind=db.engine) db.session = db.Session() app = IRCApp() def serverOrDefault(server, key): try: return config[server][key] except KeyError: return config['server default'][key] args = [a for a in config['auth']['args'].strip().split(' ') if a] auth = loadAuthPlugin(config['auth']['plugin'], args) for key in config.iterkeys(): if not key.startswith('server ') or key == 'server default': continue server = key.split(' ', 1)[1] rooms = serverOrDefault(key, 'rooms').split(' ') identify = serverOrDefault(key, 'identify') def connect_cb(c): if identify: helpers.ns(c, "IDENTIFY", identify) for room in rooms: helpers.join(c, "#"+room) cli = IRCClient( nick=serverOrDefault(key, 'nick'), realname=serverOrDefault(key, 'realname'), host=server, port=int(serverOrDefault(key, 'port')), connect_cb=connect_cb) cli.command_handler = OyoyoBotCommandHandler( cli, BotCommands(cli), auth) app.addClient(cli, autoreconnect=True) db.meta.create_all(db.engine) extendConfig('oyoyo_bot.config') config.filename = 'lastrun.ini' config.write() # to just write a config if '-c' in sys.argv: return app.run() print "done."
helpers.nick(self.client, nick+'_') def privmsg(self, sender, chan, msg): if msg[0] == '!': s = msg.split(' ') if is_command_pattern.match(s[0]): command = s[0][1:] arguments = s[1:] nick = sender.split('!')[0] if hasattr(commands, command) and callable(getattr(commands, command)): try: response = getattr(commands, command)(nick, chan, arguments, sender, config, self) except: exc_type, exc_value, exc_traceback = sys.exc_info() traceback.print_exception(exc_type, exc_value, exc_traceback, limit=2, file=sys.stdout) response = 'Coś poszło nie tak…' if response is not None: helpers.msg(self.client, chan, nick+": "+response) cli = IRCClient(IRCHandler, host=config.get('irc', 'server'), port=config.getint('irc', 'port'), nick=config.get('irc', 'nick')) app = IRCApp() app.addClient( cli ) try: app.run() except KeyboardInterrupt: quit()
def chanTopic(self, chan, topic): '''Update Chan topic''' newTopic = str(topic) # Split the new topic into segments newSegments = [item.strip() for item in newTopic.split('-')] # Fetch old topic segments, if any exist try: f = open('%s.txt' % chan, 'r') oldSegments = [item.strip() for item in f.readlines()] f.close() except IOError: oldSegments = [] # Save and tweet new segments for newSegment in newSegments: if newSegment not in oldSegments: f = open('%s.txt' % chan, 'a') f.write(newSegment + '\n') f.close() api['Channel'].PostUpdate(newSegment) cli = IRCClient(MyHandler, host="irc.server.org", port=6667, nick="TwitterBot") cli.blocking = True app = IRCApp() app.addClient(cli) app.run()