def __init__(self): '''Initialize the bot: Only called on when the bot is first launched, not subsequent reconnects.''' log.msg("Initializing bot...") # Configure internals intent.service.link(self) moduleLoader.loadModules()
def __init__(self): """Initialize the bot: Only called on when the bot is first launched, not subsequent reconnects.""" log.msg("Initializing bot...") # Configure internals intent.service.link(self) moduleLoader.loadModules()
def admincheck(self, bot, room, user, args): if user.admin: return f(self, bot, room, user, args) else: log.msg("User {0} ({1}) attempted to run a function without authorization.".format(user['nick'], user.uid)) user.send("That function requires you to be an administrator. You aren't.") return True
def refreshAvailableModules(self): self._available_modules = {} errors = False #Check to see if we've installed any new modules reload(fb.modules) for name in fb.modules.__all__: if name[0] == '_': continue #Not a real module fullname = "fb.modules." + name try: if fullname in sys.modules: reload(sys.modules[fullname]) if 'module' in sys.modules[fullname].__dict__: for child in sys.modules[fullname].module.children: reload(child) else: _module = __import__(fullname, globals(), locals(), ['module'], -1) except: log.msg("Error loading module: " + fullname + "\n" + traceback.format_exc(), log.ERROR) errors = True continue if 'module' in sys.modules[fullname].__dict__: self._available_modules[name] = sys.modules[fullname].module log.msg("Available modules: " + str(self._available_modules.keys())) return errors
def __init__(self): self._children = {} for child in self.children: try: self._children[child.__name__] = child.module() except: log.msg("Error loading %s child module %s:" % (self.uid, child.__name__), log.ERROR) raise
def parseMessage(self, body, room, user): '''Parse an incoming message.''' address = self.addressedToBot(body, room) if address is not None: body = address #Check to see if this is a command if address is not None or room is None: if user.banned and not user.admin: user.send("You've lost your bot privledges, reason: " + user["banned"]) return True words = cutString(body) for command in self._commands.values(): for rex in command['keywords']: for i in reversed(range(1, len(words) + 1)): match = rex.search(cleanString(' '.join(words[:i]))) if match is not None: #Pull out any matched groups... args = [] for k in match.groups(): args.append(k) if room is not None and room.squelched and command['core'] == False: user.send("I'm sorry, I can't do '{0}' right now as I am shut up in {2} for the next {1}.".format(command['name'], room.squelched, room.uid)) return True #Since we got a valid function we should say we handled it. else: #Anything left is added to the args args.extend(words[i:]) try: return command['function'](self._bot, room, user, args) except: log.msg("Error in command parser %s: %s" % (command["name"], traceback.format_exc()), log.ERROR) return False if room is None or (room is not None and room.squelched == False): if user.banned: return False for listener in self._listeners.values(): for rex in listener['patterns']: match = rex.search(body) if match is not None: handled = listener['function'](self._bot, room, user, match) if handled: return False if room is None: user.send('Huh?') elif address is not None: room.send('Huh?') return False
def uninstallModule(self, name): if name in cfg.bot.modules: log.msg("Attempted to uninstall core module " + name) raise ValueError log.msg("Uninstalling module: " + name) self._modules[name].unregister() del self._modules[name] db.db.modules.update({"name": name}, {"name": name, "installed": False}, upsert=True)
def receivedPrivateChat(self, user, body): '''Triggered when someone messages the bot directly.''' if body is None: return body = body.encode("utf-8") log.msg(u"Private chat: <{0}>: {1}".format(user['nick'], body)) wasCommand = intent.service.parseMessage(body, None, user) self.addHistory(None, user, user['nick'], body, wasCommand)
def receivedPrivateChat(self, user, body): """Triggered when someone messages the bot directly.""" if body is None: return body = body.encode("utf-8") log.msg(u"Private chat: <{0}>: {1}".format(user["nick"], body)) wasCommand = intent.service.parseMessage(body, None, user) self.addHistory(None, user, user["nick"], body, wasCommand)
def __init__(self): self._modules = {} self._available_modules = {} for module in cfg.bot.modules: # Force initial install of all core modules self._modules[module] = True previously_installed = db.db.modules.find({"installed": True}) for module in previously_installed: self._modules[module['name']] = True log.msg("Preloading modules: " + str(self._modules))
def ratelimited(self, bot, room, user, args): if room: if name in room.ratelimit and room.ratelimit[name] > datetime.now(): log.msg("Almost executed {0} in {1} but it was too soon.".format(name, room)) if message: user.send(message) return not passthrough else: room.ratelimit[name] = datetime.now() + timedelta(seconds=rate) log.msg("Won't execute {0} again until {1}.".format(name, room.ratelimit[name])) return f(self, bot, room, user, args) else: #user case return f(self, bot, room, user, args)
def registerModule(self, name, module, static_dir = None): assert name not in ['static', 'web', 'moduleassist'], "Module name %s has been reserved" % name log.msg("Registering API path " + name) if name in self.children: del self.children[name] self.putChild(name, module) if static_dir: self.staticRoot.putChild(name, File(path.join('fb', 'modules', static_dir, ''))) self.moduleAssist.addModule(name, static_dir) return module
def responder(self, bot, room, user, args): out = f(self, bot, room, user, args) if out is None: return False if type(out) == type(u'') or type(out) == type(''): if room is not None: room.send(out) else: user.send(out) return True log.msg("Invalid type returned by function wrapped by @response: {0} - {1}".format(out, type(out))) return False
def registerModule(self, name, module, static_dir=None): assert name not in ['static', 'web', 'moduleassist' ], "Module name %s has been reserved" % name log.msg("Registering API path " + name) if name in self.children: del self.children[name] self.putChild(name, module) if static_dir: self.staticRoot.putChild( name, File(path.join('fb', 'modules', static_dir, ''))) self.moduleAssist.addModule(name, static_dir) return module
def receivedGroupChat(self, room, user, body, nick=None, history=False): '''Triggered when a group chat is recieved in a room the bot is in''' if body is None: return body = body.encode('utf-8') #Validate that the user is NOT the bot itself! wasCommand = False if nick is None: nick = user['nick'] log.msg(u"Group chat: <{0}/{1}>: {2}".format(room.uid, nick, body)) wasCommand = intent.service.parseMessage(body, room, user) self.addHistory(room, user, nick, body, wasCommand)
def receivedGroupChat(self, room, user, body, nick=None, history=False): """Triggered when a group chat is recieved in a room the bot is in""" if body is None: return body = body.encode("utf-8") # Validate that the user is NOT the bot itself! wasCommand = False if nick is None: nick = user["nick"] log.msg(u"Group chat: <{0}/{1}>: {2}".format(room.uid, nick, body)) wasCommand = intent.service.parseMessage(body, room, user) self.addHistory(room, user, nick, body, wasCommand)
def register(self): """Functionality to register the module with the intent & api services.""" for key, command in self.commands.items(): isCore = False if 'core' in command and command['core']: isCore = True try: fb.intent.service.registerCommand(command['keywords'], getattr(self, command['function']), self.uid + ":command." + key, isCore) except: log.msg("Error registering %s command %s:" % (self.uid, key), log.ERROR) raise for key, listener in self.listeners.items(): try: fb.intent.service.registerListener(listener['keywords'], getattr(self, listener['function']), self.uid + ":listener." + key) except: log.msg("Error registering %s listener %s:" % (self.uid, key), log.ERROR) raise for path, module in self.apis.items(): if type(module) == type(()): api.registerModule(path, module[0], module[1]) else: api.registerModule(path, module) for name, child in self._children.items(): try: child.register() except: log.msg("Error registering %s child module %s:" % (self.uid, name), log.ERROR) raise
def registerModule(self, module, name): log.msg("Registering module: " + name) try: moduleobject = module() except: log.msg("Error initializing module " + name, log.ERROR) raise self._modules[name] = moduleobject try: moduleobject.register() except: log.msg("Error registering module " + name + "\nSystem may be in a bad state.", log.ERROR) raise
def makeService(self, options): import sys from fb.config import cfg cfg.loadConfig(options['configs']) if options['showconfig']: cfg._cfg.dump(sys.stdout) from fb.audit import log # Friendly warning - I ran into this once, hopefully this will help others in the future. try: from OpenSSL import SSL except: log.msg("Warning, we can't import SSL. You may have trouble connecting to some servers. If so, try installing pyOpenSSL.") if cfg.connect.method not in cfg.connect: log.msg("Connector %s specified but not found in settings." % config.connect.method) sys.exit(1) try: connector = __import__('fb.connectors.' + cfg.connect.method, globals(), locals(), ['createService'], -1) except ImportError: log.msg("Coudln't import connector: %s" % cfg.connect.method) raise log.msg("Successfully loaded connector %s" % cfg.connect.method) app = service.MultiService() connector.createService().setServiceParent(app) from fb.api.core import api api.launch(app) return app
def loadModules(self): log.msg("Loading modules...") #reload the config, in case it's changed since we started try: cfg.loadConfig() except: log.msg("Error loading config:\n" + traceback.format_exc(), log.ERROR) return True errors = self.refreshAvailableModules() # Register active modules. for name in self._modules.keys(): if name in self._available_modules: self.registerModule(self._available_modules[name], name) else: log.msg("%s not found in available modules, cannot be activated." % name, log.ERROR) return errors
def leaveRoom(self, room): '''Leave a room''' log.msg("Left " + room.uid) self._connection.leaveRoom(room) room.active = False del self.rooms[room.uid]
def registerConnector(self, connector): log.msg("Connecting bot to requested chat service...") self._connection = connector
def initRoom(self, room): """Joined a room, add it to the list.""" log.msg("Connected to " + room.uid) room.active = True self.rooms[room.uid] = room
def leaveRoom(self, room): """Leave a room""" log.msg("Left " + room.uid) self._connection.leaveRoom(room) room.active = False del self.rooms[room.uid]
def launch(self, service): log.msg("Starting up the API...") TCPServer(cfg.api.port, Site(self)).setServiceParent(service)
def initRoom(self, room): '''Joined a room, add it to the list.''' log.msg("Connected to " + room.uid) room.active = True self.rooms[room.uid] = room