def plpaste(text, bot): """ :type text: str :type bot: core.bot.CloudBot """ if text in bot.plugin_manager.commands: file_path = bot.plugin_manager.commands[text].module.file_path with open(file_path) as f: return web.haste(f.read(), ext='py') elif text + ".py" in listdir('modules/'): with open('modules/{}.py'.format(text)) as f: return web.haste(f.read(), ext='py') else: return "Could not find specified plugin."
def plpaste(text, bot): """ :type text: str :type bot: core.bot.CloudBot """ if text in bot.plugin_manager.commands: file_path = bot.plugin_manager.commands[text].module.file_path with open(file_path) as f: return web.haste(f.read(), ext="py") elif text + ".py" in listdir("modules/"): with open("modules/{}.py".format(text)) as f: return web.haste(f.read(), ext="py") else: return "Could not find specified plugin."
def get_sound_info(game, search): search = search.replace(" ", "+") try: data = http.get_json("http://p2sounds.blha303.com.au/search/%s/%s?format=json" % (game, search)) except urllib2.HTTPError as e: return "Error: " + json.loads(e.read())["error"] items = [] for item in data["items"]: if "music" in game: textsplit = item["text"].split('"') text = "" for i in xrange(len(textsplit)): if i % 2 != 0 and i < 6: if text: text += " / " + textsplit[i] else: text = textsplit[i] else: text = item["text"] items.append("{} - {} {}".format(item["who"], text if len(text) < 325 else text[:325] + "...", item["listen"])) if len(items) < 1: return "No results" elif len(items) == 1: return items[0] else: return "{} (and {} others: {})".format(items[0], len(items) - 1, web.haste("\n".join(items)))
def plpaste(inp, say='', bot=None): """plpaste <plugin> - Hastebin's a plugin's code and returns the link.""" if inp in bot.commands: with open(bot.commands[inp][0].func_code.co_filename.strip()) as f: say(web.haste(f.read(), 'py')) else: try: if inp[-3:] == '.py': inp = inp[:-3] with open('plugins/%s.py' % inp) as f: say(web.haste(f.read(), 'py')) return except: pass return "Could not find specified plugin."
def get_sound_info(game, search): search = search.replace(" ", "+") try: data = http.get_json("http://p2sounds.blha303.com.au/search/%s/%s?format=json" % (game, search)) except urllib.error.HTTPError as e: return "Error: " + json.loads(e.read())["error"] items = [] for item in data["items"]: if "music" in game: textsplit = item["text"].split('"') text = "" for i in range(len(textsplit)): if i % 2 != 0 and i < 6: if text: text += " / " + textsplit[i] else: text = textsplit[i] else: text = item["text"] items.append("{} - {} {}".format(item["who"], text if len(text) < 325 else text[:325] + "...", item["listen"])) if len(items) == 1: return items[0] else: return "{} (and {} others: {})".format(items[0], len(items) - 1, web.haste("\n".join(items)))
def man(inp, say=''): """.man <command> [section] - Returns man page for specified command, section defaults to 1 if not specified.""" raw = inp.split() command = raw[0] if len(raw) == 2 and raw[1].isdigit(): page = raw[1] else: page = "1" try: manpage = str(http.get_html(base_url, topic=command, section=page)) # If not specified man page if re.match(r'.+(\>No matches for ").+', manpage): page = "all" manpage = str(http.get_html(base_url, topic=command, section=page)) # If man page exists for command if not re.match(r'.+(\>No matches for ").+', manpage) and 1 == 2: if page != "all": say("{} - {}({})".format(web.try_googl(base_url.format(command, page)), command, page)) else: say("{} - {}({}) (No section {})".format((web.try_googl(base_url.format(command, page)), command, page, raw[1]))) else: system_manpage = get_system_manpage(command) if system_manpage: haste_url = web.haste(system_manpage, ext='txt') googl_url = web.try_googl(haste_url) say("{} - {}".format(googl_url, command, page)) else: return "There is no man page for {}.".format(command) except Exception as e: # (http.HTTPError, http.URLError) as e: print(">>> u'HTTP Error: {}'".format(e)) return "HTTP Error, please try again in a few minutes."
def plpaste(inp, say='', bot=None): """.plpaste <plugin> - Hastebin's a plugin's code and returns the link.""" if inp in bot.commands: with open(bot.commands[inp][0].func_code.co_filename.strip()) as f: say(web.haste(f.read(), 'py')) else: try: if inp[-3:] == '.py': inp = inp[:-3] with open('plugins/%s.py' % inp) as f: say(web.haste(f.read(), 'py')) return except: pass return "Could not find specified plugin."
def plpaste(inp): if "/" in inp and inp.split("/")[0] != "util": return "Invalid input" try: with open("plugins/%s.py" % inp) as f: return web.haste(f.read(), ext='py') except IOError: return "Plugin not found (must be in plugins folder)"
def update(): repo = Repo() git = repo.git try: pull = git.pull() except Exception as e: return e if "\n" in pull: return web.haste(pull) else: return pull
def commands(inp, say=None, notice=None, input=None, conn=None, bot=None, db=None): "commands -- Gives a list of commands/help for a command." funcs = {} disabled = bot.config.get('disabled_plugins', []) disabled_comm = bot.config.get('disabled_commands', []) for command, (func, args) in bot.commands.items(): fn = re.match(r'^plugins.(.+).py$', func._filename) if fn.group(1).lower() not in disabled and command not in disabled_comm: # Ignores disabled plugins and commands if args.get('channeladminonly', False) and not user.is_admin(input.mask, input.chan, db, bot): continue if args.get('adminonly', False) and not user.is_globaladmin(input.mask, input.chan, bot): continue if func.__doc__ is not None: if func in funcs: if len(funcs[func]) < len(command): funcs[func] = command else: funcs[func] = command commands = dict((value, key) for key, value in funcs.items()) if not inp: output = [] well = [] line = [] help = "For detailed help, do '{}help <example>' where <example> "\ "is the name of the command you want help for.".format(conn.conf["command_prefix"]) for command in commands: well.append(command) well.sort() for command in well: if output == [] and line == []: line.append("Commands you have access to ({}): {}".format(len(well), str(command))) else: line.append(str(command)) if len(", ".join(line)) > 405: output.append(", ".join(line)) line = [] if len(line) > 0: output.append(", ".join(line)) if len(output) == 1: output.append(help) for line in output: notice(line) else: output = ", ".join(output) haste = web.haste("{}\n\n{}".format(output, help)) notice("Commands you have access to ({}): {}".format(len(well), haste)) elif inp in commands: notice("{}{}".format(conn.conf["command_prefix"], commands[inp].__doc__)) return
def update(inp, bot=None): """.update - Pull latest changes from Git repo (restart may be required).""" repo = Repo() git = repo.git try: pull = git.pull() except Exception as e: return e if "\n" in pull: return web.haste(pull) else: return pull
def linkdump(inp, chan="", say="", db=None): """.linkdump - Gets today's links dumped in channel.""" today = datetime.today() period = float(datetime(today.year, today.month, today.day).strftime('%s')) rows = db.execute("select nick, msg, time from log where uts >= ? and chan = ? and " \ "(msg like '%http://%' or msg like '%https://%')", (period, chan)).fetchall() if not rows: return "No links yet today (beginning with 'http')" links = ["via %s [%s]: %s" % (row[0], re.search(r'(\d+\:\d+:\d+)', row[2]).group(0), re.search(html_re, row[1]).group(0)) for row in rows] say("Today's link dump: " + web.haste('\n'.join(links), 'txt'))
def factoid(code, input): """ `<word> -- Shows what data is associated with <word>. ` <add|delete|info> [args] -- for management """ if len(input.group().strip()) == 1: return # If it's a management command... if input.group().startswith('` '): if not input.admin: return code.reply( '{red}You need to be an admin to use that command!') return factoid_manage(input.group().split(' ', 1)[1], code, input) db = database.get(code.nick, 'factoids') if not db: db = [] if len(input.group(1).strip().split()) <= 1: id, arguments = input.group(1), '' else: id, arguments = input.group(1).split(' ', 1) id = id.lower() if id not in db: # code.say('{red}That command doesn\'t exist. (If Admin, add it with "{purple}` add <name> <data>{red}")') return # It doesn't know the command. Instead of spamming, just act silent. f = db[id] if f.startswith('<py>'): data = f[4:].strip() variables = 'input="""{}"""; nick="{}"; sender="{}"; bot="{}";'.format( arguments.replace('"', '\\"'), input.nick, input.sender, code.nick) result = web.exec_py(variables + data) if 'Traceback (most recent call last)' in result: result = 'Python error: ' + web.haste(result) return code.say(result) elif f.startswith('<act>'): result = f[5:].strip() return code.action(result) elif f.startswith('<url>'): url = f[5:].strip() try: return code.say(web.text(url)) except: return code.say('Failed to fetch the URL.') else: return code.say(f)
def factoid(code, input): """ `<word> -- Shows what data is associated with <word>. ` <add|delete|info> [args] -- for management """ if len(input.group().strip()) == 1: return # If it's a management command... if input.group().startswith('` '): if not input.admin: return code.reply('{red}You need to be an admin to use that command!') return factoid_manage(input.group().split(' ', 1)[1], code, input) db = database.get(code.nick, 'factoids') if not db: db = [] if len(input.group(1).strip().split()) <= 1: id, arguments = input.group(1), '' else: id, arguments = input.group(1).split(' ', 1) if id not in db: return code.say('{red}That command doesn\'t exist. (If Admin, add it with "{purple}` add <name> <data>{red}")') f = db[id] if f.startswith('<py>'): data = f[4:].strip() variables = 'input="""{}"""; nick="{}"; sender="{}"; bot="{}";'.format( arguments.replace('"', '\\"'), input.nick, input.sender, code.nick ) result = web.exec_py(variables + data) if 'Traceback (most recent call last)' in result: result = 'Python error: ' + web.haste(result) return code.say(result) elif f.startswith('<act>'): result = f[5:].strip() return code.action(result) elif f.startswith('<url>'): url = f[5:].strip() try: return code.say(web.get(url).read()) except: return code.say('Failed to fetch the URL.') else: return code.say(f)
def lyrics(inp): """lyrics <search> - Search AZLyrics.com for song lyrics""" if "pastelyrics" in inp: dopaste = True inp = inp.replace("pastelyrics", "").strip() else: dopaste = False soup = http.get_soup(url + inp.replace(" ", "+")) if "Try to compose less restrictive search query" in soup.find( 'div', { 'id': 'inn' }).text: return "No results. Check spelling." div = None for i in soup.findAll('div', {'class': 'sen'}): if "/lyrics/" in i.find('a')['href']: div = i break if div: title = div.find('a').text link = div.find('a')['href'] if dopaste: newsoup = http.get_soup(link) try: lyrics = newsoup.find( 'div', { 'style': 'margin-left:10px;margin-right:10px;' }).text.strip() pasteurl = " " + web.haste(lyrics) except Exception as e: pasteurl = " (\x02Unable to paste lyrics\x02 [{}])".format( str(e)) else: pasteurl = "" artist = div.find('b').text.title() lyricsum = div.find('div').text if "\r\n" in lyricsum.strip(): lyricsum = " / ".join( lyricsum.strip().split("\r\n")[0:4]) # truncate, format else: lyricsum = " / ".join( lyricsum.strip().split("\n")[0:4]) # truncate, format return u"\x02{}\x02 by \x02{}\x02 {}{} - {}".format( title, artist, web.try_isgd(link), pasteurl, lyricsum[:-3]) else: return "No song results. " + url + inp.replace(" ", "+")
def linkdump(inp, chan='', server='', say=None, db=None): """linkdump [-l] - Gets today's links dumped in channel; -l for unshortened links.""" today = datetime.today() period = float(datetime(today.year, today.month, today.day).strftime('%s')) rows = get_linkdump(db, server, chan, period, (True if inp == '-l' else False)) if not rows: return "No links yet today (beginning with 'http')" links = [] for row in rows: nick, slink, title, time = row links.append(u"via {} [{}]: {}".format( nick, re.search(r'(\d+\:\d+:\d+)', time).group(0), (slink + (u" - {}".format(title) if title else "")))) say("Today's link dump: " + web.haste(u'\n'.join(links).encode('utf-8'), 'txt'))
def poll(inp, nick=None, chan=None, say=None): """poll <description>[: choice1, choice2, ..., choice n] - Begins a poll if you do not already have an active poll; choices default to [yes|no]; end poll and get results with 'poll close'.""" global active_polls active_polls[chan] # init if inp == "close": if active_polls.get(chan).get(nick) is None: return "You do not have an active poll." else: active_polls[chan][nick]['results']['total'] = len( active_polls[chan][nick]['votes'].keys()) for choice in active_polls[chan][nick]['choices']: active_polls[chan][nick]['results']['choices'][choice] = len([ x for x in active_polls[chan][nick]['votes'] if active_polls[chan][nick]['votes'][x] == choice ]) results = web.haste( dumps(active_polls.get(chan).get(nick), sort_keys=True, indent=2)) del active_polls[chan][nick] say("Results for {}'s poll: {}".format(nick, results)) elif active_polls.get(chan).get(nick) is not None: return "You already have an active poll: '{}'.".format( active_polls[chan][nick]['description']) else: if ':' in inp: desc, choices = inp.split(':') c = findall(r'([^,]+)', choices) if len(c) == 1: c = findall(r'(\S+)', choices) choices = list(set(x.strip() for x in c)) else: desc = inp choices = ["yes", "no"] active_polls[chan][nick]['description'] = desc active_polls[chan][nick]['choices'] = choices active_polls[chan][nick]['votes'] say("Poll '{1}' started by {0}; to vote use 'vote {0} <{2}>'.".format( nick, desc, "|".join(choices)))
def lyrics(inp): """lyrics <search> - Search AZLyrics.com for song lyrics""" if "pastelyrics" in inp: dopaste = True inp = inp.replace("pastelyrics", "").strip() else: dopaste = False soup = http.get_soup(url + inp.replace(" ", "+")) if "Try to compose less restrictive search query" in soup.find('div', {'id': 'inn'}).text: return "No results. Check spelling." div = None for i in soup.findAll('div', {'class': 'sen'}): if "/lyrics/" in i.find('a')['href']: div = i break if div: title = div.find('a').text link = div.find('a')['href'] if dopaste: newsoup = http.get_soup(link) try: lyrics = newsoup.find('div', {'style': 'margin-left:10px;margin-right:10px;'}).text.strip() pasteurl = " " + web.haste(lyrics) except Exception as e: pasteurl = " (\x02Unable to paste lyrics\x02 [{}])".format(str(e)) else: pasteurl = "" artist = div.find('b').text.title() lyricsum = div.find('div').text if "\r\n" in lyricsum.strip(): lyricsum = " / ".join(lyricsum.strip().split("\r\n")[0:4]) # truncate, format else: lyricsum = " / ".join(lyricsum.strip().split("\n")[0:4]) # truncate, format return u"\x02{}\x02 by \x02{}\x02 {}{} - {}".format(title, artist, web.try_isgd(link), pasteurl, lyricsum[:-3]) else: return "No song results. " + url + inp.replace(" ", "+")
def commands(inp, say=None, notice=None, input=None, conn=None, bot=None, db=None): "commands -- Gives a list of commands/help for a command." funcs = {} disabled = bot.config.get('disabled_plugins', []) disabled_comm = bot.config.get('disabled_commands', []) for command, (func, args) in bot.commands.iteritems(): fn = re.match(r'^plugins.(.+).py$', func._filename) if fn.group(1).lower( ) not in disabled and command not in disabled_comm: # Ignores disabled plugins and commands if args.get('channeladminonly', False) and not user.is_admin( input.mask, input.chan, db, bot): continue if args.get('adminonly', False) and not user.is_globaladmin( input.mask, input.chan, bot): continue if func.__doc__ is not None: if func in funcs: if len(funcs[func]) < len(command): funcs[func] = command else: funcs[func] = command commands = dict((value, key) for key, value in funcs.iteritems()) if not inp: output = [] well = [] line = [] help = "For detailed help, do '{}help <example>' where <example> "\ "is the name of the command you want help for.".format(conn.conf["command_prefix"]) for command in commands: well.append(command) well.sort() for command in well: if output == [] and line == []: line.append("Commands you have access to ({}): {}".format( len(well), str(command))) else: line.append(str(command)) if len(", ".join(line)) > 405: output.append(", ".join(line)) line = [] if len(line) > 0: output.append(", ".join(line)) if len(output) == 1: output.append(help) for line in output: notice(line) else: output = ", ".join(output) haste = web.haste("{}\n\n{}".format(output, help)) notice("Commands you have access to ({}): {}".format( len(well), haste)) elif inp in commands: notice("{}{}".format(conn.conf["command_prefix"], commands[inp].__doc__)) return