def run(self): ''' run() -> None Run a loop forever in the background and replies to PING requests from the IRC server. ''' buffr = '' while self.parent.connected: buffr += self.parent.irc.recv(1024) temp = string.split(buffr, '\n') buffr = temp.pop() for line in temp: line = string.rstrip(line) pingmatch = re.match('^PING :(.*)$', line) # Answer to PINGs from the IRC server. if pingmatch != None: self.parent.irc.send('PONG %s\r\n' % \ (pingmatch.group(1))) self.ircbuffer.append(line) out.info("Connection connection.StayAwake().run(self) terminated.")
def connect(self): self.irc = socket.socket() # Trying to bind vhost if self.ipaddr: try: self.irc.bind((self.ipaddr, self.port)) out.info("bound IP-address: %s " % self.ipaddr) except: out.warn("could not bind IP-address: %s " % self.ipaddr) self.irc.connect((self.server, self.port)) self.irc.send(u'NICK %s\n' % (self.nick)) self.irc.send(u'USER %s %s bla :%s\n' % (self.ident, self.server, self.name)) for channel in self.channels: self.irc.send(u'JOIN #%s\n' % channel) out.info("Connected to %s" % self.server) out.newline() self.connected = True stayawake = self.StayAwake(self) stayawake.start()
def __init__(self): ''' Load the core modules, as well as the user defined extra modules defined in the config file (config.conf). ''' self.enabled = True self.mcore = {} self.mextra = [] self.mplugin = [] self.cmdlist = {} self.cfg = '' import module.core.configmanager as cfg self.cfg = cfg.BrunobotConfig() self.cfg.printConfig() self.mcore['cfg'] = self.cfg # setting configuration for the output object out.setcfg(self.mcore['cfg']) self.loadCore() out.info('Core modules loaded ') for module in self.mcore: out.info('%s' % module) out.newline() import module.core.loadmodule as loadmodule self.moduleLoader = loadmodule.DynamicLoad(self) for module in self.cfg.list('modules'): thread.start_new_thread(self.loadModule, (module, ) )
def run(self): ''' run() Starting the process manager, invoked by self.start(). ''' while self.running: for proc in self.proccesses: duration = proc.duration() maxDuration = self.cfg.get('max_run_time',proc.module.name) try: maxDuration = int(maxDuration) except: try: maxDuration = int(self.cfg.get('module','max_run_time')) except: maxDuration = 5 if not proc.is_alive(): self.proccesses.remove(proc) elif duration >= maxDuration: self.communication.say(proc.data['channel'], 'Running of %s took too long (limit=%ds).' % (proc.module.name, maxDuration)) out.warn('Running of %s took too long (limit=%ds)' % (proc.module.name, maxDuration)) proc.stop() self.proccesses.remove(proc) time.sleep(0.3) out.info('ThreadedManager threadmanager.ThreadedManager().run(self) terminated.')
def download(self,url,verbose=False): ''' Downloading a python module from the web and loads it using the load method. It will try to download the file and write it to disk. If the module is valid then it will be loaded. ''' response = None html = None try: response = urllib2.urlopen(url) html = response.readlines() except: result = emptyResult() result['errors'] = [['Download module','error: could not read file from URL.']] return None, result try: f = open('module/extra/tmp_module.py','w') for line in html: f.write(line) f.close() except: result = emptyResult() result['errors'] = [['Download module','error: could not write to tempfile']] return None, result #def validateModule(self,name): module, result = self.validateModule('tmp_module',verbose) if inspect.ismodule(module) and result['valid']: try: f = open('module/extra/%s.py' % module.name,'w') for line in html: f.write(line) f.close() except: result = emptyResult() result['errors'] = [['Download module','error: could not write module to module/extra/%s.py.' % name]] return None, result else: try: del sys.modules['module.extra.tmp_module'] except: out.warn('Could not clean up tmp_module import') return None, result out.info('Module "%s" downloaded from %s' % (module.name, url)) os.remove('module/extra/tmp_module.py') return module, result
def run(self): while self.running: while len(self.buffr)>0: line = self.buffr.pop() self.parser.parse(line) time.sleep(0.1) out.info("Core Parser cparser.BufferReader().run(self) terminated.")
def run(self): while self.running: while len(self.buffr) > 0: line = self.buffr.pop() self.parser.parse(line) time.sleep(0.1) out.info("Core Parser cparser.BufferReader().run(self) terminated.")
def load(self,name, verbose=False): ''' Load a module based on its name. Will validate it using the ModuleLoader. Tries to validate the module based the name. If the module is a valid module it will be injected with the required core modules asked for by the module. return (Module, unittest) if successful return (None, unittest) if unsuccessful ''' result = emptyResult() if self.modules.extra(name): result['errors'] == [['Load module','module with name "%s" already loaded.' % name]] return None, result module, result = self.validateModule(name,verbose) # injecting depcendencies if (inspect.ismodule(module)) and result['valid']: if 'cmd' in module.listen: for cmd in module.cmd: self.modules.cmdlist[cmd] = module for coremodule in module.require: if coremodule is 'presist': vars(module)['presist'] = presist.Presist(module,module.presist) module.presist.load() else: vars(module)[coremodule] = self.modules.mcore[coremodule] vars(module)['filename'] = name self.modules.mextra.append(module) self.cfg.set('modules','%s' % name) out.info('extra module loaded: %s %s' % (name, module.version)) return (module,result) else: try: del sys.modules['module.extra.' + name] except: ''' do nothing ''' return None, result
def parsecmd(self, nick, ident, host, channel, cmd): ''' Parse a command sent to the bot and decide what to do Keyword arguments: nick -- nick of sender ident -- ident of sender host -- host of sender channel -- channel the message was sent to cmd -- command that was sent ''' command = cmd.split() data = { 'type': 'cmd', 'nick': nick, 'ident': ident, 'host': host, 'channel': channel, 'cmd': command[0] } try: data['argv'] = command[1:] except: data['argv'] = None coreCmd = self.modules.mcore['corecmd'].parse_cmd(data) if not coreCmd: cmdModules = self.modules.listening('cmd') try: module = self.modules.cmdlist[data['cmd']] out.info("running: %s" % module) if module: try: self.threadmanager.runModule(module, data) #thread.start_new_thread(module.main, (data, ) ) except Exception as error: out.verbose(error) out.error("Module '%s %s' failed to run." % (module.name, module.version)) if self.modules.requires(module, 'presist'): module.presist.save() except: out.warn("could not find module that listens to %s." % data['cmd'])
def parse_cmd(self,data): ''' Parsing the command to check if it is a part of the core commands. Returns true if, false otherwise. ''' cmd = data['cmd'] if cmd == 'cmd' and data['argv']: try: info_cmd = self.cmd[data['argv'][0]] used = ", ".join(info_cmd.cmd) info = "[%s] usage: %s" % (used, info_cmd.usage) descr = "%sdescription: %s" % (" "*len(used), info_cmd.description) self.communication.say(data['channel'],"%s" % info) self.communication.say(data['channel'],"%s" % descr) except: self.communication.say(data['channel'],"Could not find info for %s" % data['argv'][0]) return True elif cmd == 'reloadcmd': self.load_cmds() self.communication.say(data['channel'], '%d core commands modules reloaded.' % len(self.cmd)) self.cfg.load() out.info("Reloaded core commands and config file.") return True elif cmd == 'listcmd': listofcmd = ", ".join(self.cmd.keys()) self.communication.say(data['channel'], 'Found %d core commands: %s. (+ reloadcmd, cmd, listcmd)' % (len(self.cmd), listofcmd)) elif cmd in self.cmd: try: self.cmd[cmd].main(self.modules, data) except Exception as error: out.error('Module [%s] in corecmd failed.' % cmd) out.verbose(error) #print '-'*60 #traceback.print_exc(file=sys.stdout) #print '-'*60 return True return False
def main(modules, data): argv = data['argv'] channel = data['channel'] connection = modules.mcore['connection'] auth = modules.mcore['auth'] user = data['nick'] ident = data['ident'] host = data['host'] if auth.isOwner(user, ident, host): try: #connection.connected = False #connection.irc.send(u'QUIT \n') #connection.quit() modules.quit() out.info('Bot is shutting down by request of: %s!%s@%s' % (user, ident, host)) out.newline() except: ''' Nothing '''
def main(modules, data): argv = data['argv'] channel = data['channel'] connection = modules.mcore['connection'] auth = modules.mcore['auth'] cfg = modules.mcore['cfg'] user = data['nick'] ident = data['ident'] host = data['host'] if argv: if auth.isOwner(user, ident, host): try: nick = argv[0] connection.irc.send(u'NICK %s\n' % nick) out.info('changed nick to: %s ' % nick) cfg.set('connection','nick', '%s' % nick) except: ''' Nothing '''
def main(modules, data): argv = data['argv'] user = data['nick'] ident = data['ident'] host = data['host'] channel = data['channel'] cfg = modules.mcore['cfg'] auth = modules.mcore['auth'] communication = modules.mcore['communication'] if argv: if auth.isOwner(user, ident, host): if argv[0] == 'get': if len(argv) == 3: result = cfg.get(argv[1], argv[2]) elif len(argv) == 2: result = "[%s]" % (", ".join(cfg.list(argv[1]))) communication.say(channel, result) elif argv[0] == 'set': if len(argv) == 3: cfg.set(argv[1], argv[2]) result = "set variable '%s' in %s" % (argv[2], argv[1]) elif len(argv) == 4: cfg.set(argv[1], argv[2], argv[3]) result = "set variable '%s = %s' in %s" % ( argv[2], argv[3], argv[1]) communication.say(channel, result) out.info("config: %s " % result) elif argv[0] == 'rem': if len(argv) == 3: cfg.rem(argv[1], argv[2]) communication.say( channel, "unset value '%s' in %s" % (argv[2], argv[1])) out.info("config: unset variable '%s' in %s" % (argv[2], argv[1]))
def main(modules, data): argv = data['argv'] channel = data['channel'] connection = modules.mcore['connection'] auth = modules.mcore['auth'] cfg = modules.mcore['cfg'] user = data['nick'] ident = data['ident'] host = data['host'] if argv: if auth.isOwner(user, ident, host): try: nick = argv[0] connection.irc.send(u'NICK %s\n' % nick) out.info('changed nick to: %s ' % nick) cfg.set('connection', 'nick', '%s' % nick) except: ''' Nothing '''
def parsecmd(self, nick, ident, host, channel, cmd): ''' Parse a command sent to the bot and decide what to do Keyword arguments: nick -- nick of sender ident -- ident of sender host -- host of sender channel -- channel the message was sent to cmd -- command that was sent ''' command = cmd.split() data = {'type' :'cmd', 'nick' :nick, 'ident' :ident, 'host' :host, 'channel' :channel, 'cmd' :command[0]} try: data['argv'] = command[1:] except: data['argv'] = None coreCmd = self.modules.mcore['corecmd'].parse_cmd(data) if not coreCmd: cmdModules = self.modules.listening('cmd') try: module = self.modules.cmdlist[data['cmd']] out.info("running: %s" % module) if module: try: self.threadmanager.runModule(module, data) #thread.start_new_thread(module.main, (data, ) ) except Exception as error: out.verbose(error) out.error("Module '%s %s' failed to run." % (module.name, module.version)) if self.modules.requires(module,'presist'): module.presist.save() except: out.warn("could not find module that listens to %s." % data['cmd'])
def main(modules, data): argv = data['argv'] channel = data['channel'] connection = modules.mcore['connection'] communication = modules.mcore['communication'] auth = modules.mcore['auth'] cfg = modules.mcore['cfg'] user = data['nick'] ident = data['ident'] host = data['host'] if argv: if auth.isOwner(user, ident, host): try: chan = argv[0] connection.irc.send('JOIN %s\n' % chan) communication.say(channel, 'Joining %s ...' % chan) out.info('joined channel: %s ' % chan) cfg.set('channels','%s' % chan[1:]) except: ''' Nothing '''
def unload(self,name): ''' Unload a module based on its name. return (True, msg) if successful return (True, errorMSG) if unsuccessful ''' mod = self.modules.extra(name) if (mod): self.cfg.rem('modules','%s' % name) try: del sys.modules['module.extra.' + name] except: return (False, 'Could not unimport "module.extra.%s" module from python runtime.' % name) self.modules.mextra.remove(mod) out.info("extra module unloaded: %s" % name) return (True, 'Module "%s" unloaded.' % name) else: return (False, 'Could not find module %s.' % name)
def run(self): ''' run() Starting the process manager, invoked by self.start(). ''' while self.running: for proc in self.proccesses: duration = proc.duration() maxDuration = self.cfg.get('max_run_time', proc.module.name) try: maxDuration = int(maxDuration) except: try: maxDuration = int( self.cfg.get('module', 'max_run_time')) except: maxDuration = 5 if not proc.is_alive(): self.proccesses.remove(proc) elif duration >= maxDuration: self.communication.say( proc.data['channel'], 'Running of %s took too long (limit=%ds).' % (proc.module.name, maxDuration)) out.warn('Running of %s took too long (limit=%ds)' % (proc.module.name, maxDuration)) proc.stop() self.proccesses.remove(proc) time.sleep(0.3) out.info( 'ThreadedManager threadmanager.ThreadedManager().run(self) terminated.' )
def printConfig(self): out.info("Configuration [connection]") out.info(" server: %s (%s)" % (self.get('connection','server'),self.get('connection','port'))) out.info(" nick: %s (%s, %s)" % (self.get('connection','nick'), self.get('connection','ident'), self.get('connection','name'))) out.info(" channels: %s " % ", ".join(self.list('channels'))) out.newline() out.info("Configuration [module]") out.info(" max_run_time: %s" % (self.get('module','max_run_time'))) out.info(" prefix: %s" % (self.get('module','prefix'))) for module in self.list('modules'): out.info(" module: %s" % module) out.newline() out.info("Configuration [owners]") for owner in self.list('owners'): user, ident, host = owner.replace(' ','').split(',') out.info(" owner: %s!%s@%s" % (user, ident, host)) out.newline()