def api(name=None): config = {} try: for key, value in bot.config().iteritems(): # Add configuration to web-requests, but ensure # no passwords exists to prevent security issues if 'pass' not in key.lower(): config[key] = value data = { 'nick': bot.nick, 'chan_data': bot.chan, 'channels': bot.chan.keys(), 'modules': sorted(bot.modules), 'docs': bot.doc, 'config': config, 'bot_startup': hrt(bot.bot_startup)[0], 'irc_startup': hrt(bot.irc_startup)[0], 'muted': bot.muted, # bot.webserver_data allows any plugin to add data to the api 'other': bot.webserver_data, 'server': bot.server_options, 'logs_all': bot.logs, 'bans': bot.bans } data['logs'] = [] for log in bot.logs['bot']: tmp = log tmp['timestamp'] = datetime.datetime.fromtimestamp( float(tmp['time'])).strftime(fmt) data['logs'].append(tmp) if name and name != 'all': if ',' in name: try: names = list(name.replace(' ', '').split(',')) tmp = {} for item in names: if item in names: tmp[item] = data[item] return tmp except: return {} else: try: return {name: data[name]} except: return {} return data except: return {}
def api(name=None): config = {} try: for key, value in bot.config().iteritems(): # Add configuration to web-requests, but ensure # no passwords exists to prevent security issues if 'pass' not in key.lower(): config[key] = value data = { 'nick': bot.nick, 'chan_data': bot.chan, 'channels': bot.chan.keys(), 'modules': sorted(bot.modules), 'docs': bot.doc, 'config': config, 'bot_startup': hrt(bot.bot_startup)[0], 'irc_startup': hrt(bot.irc_startup)[0], 'muted': bot.muted, # bot.webserver_data allows any plugin to add data to the api 'other': bot.webserver_data, 'server': bot.server_options, 'logs_all': bot.logs, 'bans': bot.bans } data['logs'] = [] for log in bot.logs['bot']: tmp = log tmp['timestamp'] = datetime.datetime.fromtimestamp(float(tmp['time'])).strftime(fmt) data['logs'].append(tmp) if name and name != 'all': if ',' in name: try: names = list(name.replace(' ', '').split(',')) tmp = {} for item in names: if item in names: tmp[item] = data[item] return tmp except: return {} else: try: return {name: data[name]} except: return {} return data except: return {}
def findandreplace(code, input): if not input.sender.startswith('#'): return target, replacement, flags = input.groups() if flags is not None: flags = flags.strip() else: flags = "" if len(target) == 0: return code.say('{red}Nothing to replace!') # Replace unlimited times if /g flag, else once count = 'g' in flags and -1 or 1 if 'i' in flags: regex = re.compile(re.escape(target), re.U | re.I) repl = lambda s: re.sub(regex, '{b}' + replacement + '{b}', s, count == 1) else: repl = lambda s: s.replace(target, '{b}' + replacement + '{b}', count) channel_messages = list(reversed(code.logs['channel'][input.sender])) msg_index = None for i in range(len(channel_messages)): if channel_messages[i]['message'].startswith('(me)') or \ ' s/' in channel_messages[i]['message'].lower() or \ channel_messages[i]['message'].lower().startswith('s/') or \ channel_messages[i]['nick'] == code.nick: continue new_msg = repl(channel_messages[i]['message']) if new_msg != channel_messages[i]['message']: # we are done msg_index = i break if msg_index is None: return code.say('{red}Nothing to replace!') if not new_msg or new_msg == channel_messages[msg_index]['message']: return # Save the new "edited" message. # Remember, the above index is reversed so unreverse it. new_id = (len(channel_messages) - 1) - msg_index code.logs['channel'][input.sender][new_id]['message'] = new_msg info = code.logs['channel'][input.sender][new_id] code.say('({b}%s{b} ago) <{b}%s{b}> %s' % (hrt(info['time'])[0], info['nick'], info['message']))
def do_GET(self): init_time = float(time.time()) def readfile(fn): if not os.path.isfile('webserver/%s' % fn): return False try: with open('webserver/%s' % fn, 'r') as f: return f.read() except: return False def finish(data='', content='application/json', code=200): self.send_response(code) self.send_header("Content-type", content) self.end_headers() done = float(time.time()) - init_time if bot.debug: output.info('Finished request for %s (took %f seconds)' % (self.path, done), 'WEBSERVER') if isinstance(data, dict): data = json.dumps(data, indent=2) self.wfile.write(data) args = {} if bot.debug: output.warning('Request for "%s" (%s)' % (self.path, ', '.join([self.command, self.request_version, list(self.client_address)[0]])), 'WEBSERVER') path = self.path.replace('?callback=?', '') if path.startswith('/?'): tmp = path.split('?', 1)[1] args = urlparse.parse_qs(tmp) # Manage here try: if 'pass' not in args: return finish({'success': False, 'message': 'Password required. Example: http://localhost:8888/?pass=mypassword'}, code=403) if args['pass'][0] != password: return finish({'success': False, 'message': 'Password incorrect'}, code=403) # Authenticated.. Now we need to find some variables in the args # 1. args (used for IRC commands) # 2. data (The argument for the IRC command (the arguments # argument!)) if 'execute' in args: cmd = args['execute'][0] if cmd == 'mute': bot.mute() if cmd == 'unmute': bot.unmute() if cmd == 'restart': bot.restart() if cmd == 'quit': bot.quit() if cmd == 'reloadall': reload.reload_all_modules(bot) return finish({'success': True, 'message': 'Reloaded all modules!'}) if cmd == 'reload': tmp = reload.reload_module(bot, args['data'][0]) return finish({'success': True, 'message': 'Reloaded %s!' % tmp['name']}) if 'args' not in args: config = {} for key, value in bot.config().iteritems(): # Add configuration to web-requests, but ensure # no passwords exists to prevent security issues if 'pass' not in key.lower(): config[key] = value data = { 'nick': bot.nick, 'chan_data': bot.chan, 'modules': sorted(bot.modules), 'docs': bot.doc, 'config': config, 'bot_startup': hrt(bot.bot_startup)[0], 'irc_startup': hrt(bot.irc_startup)[0], 'muted': bot.muted, 'other': bot.webserver_data, 'server': bot.server_options, 'logs1': bot.logs } data['logs'] = [] for log in bot.logs['bot']: tmp = log tmp['hrt'] = hrt(tmp['time'])[0] data['logs'].append(tmp) return finish({'success': True, 'data': data}) if 'data' in args: bot.write( args['args'][0].split(), bot.format(args['data'][0])) else: bot.write(args['args'][0].split()) return finish({'success': True, 'message': 'Data sent to server'}) except Exception as e: return finish({'success': False, 'message': 'An exception has occured', 'error': list(e)}, code=500) elif path.endswith('/'): target = path + 'index.html' filetype = 'text/html' else: target = path if '.' in path: filetype = 'text/' + path.split('.')[-1] else: filetype = 'text/html' if filetype == 'text/js': filetype = 'application/javascript' f = readfile(target.strip('/')) if not f: return finish('404 file now found', content='text/html', code=400) return finish(f, content=filetype, code=200)