def shorten_urls(data): """ Shorten and format all URLs. """ jobs = [] for line in data: jobs.append((lambda i: lambda: re.sub("http://[^ ]+", lambda x: url.format(url.shorten(x.group(0))), i))(line)) return util.parallelise(jobs)
def collage(self, server, message, flags, data, user): tapmusic = "http://nsfcd.com/lastfm/collage.php?" if not user: user = message.address.nick lowername = server.lower(user) if lowername in self.users: user = self.users[lowername] defaults = {"user": user, "type": "7day", "size": "3x3"} for i in (flags or []): if i in "cap": defaults[{ "c": "caption", "a": "artistonly", "p": "playcount" }[i]] = "true" if data: for i in data.split(): if "x" in i: defaults["size"] = i else: defaults["type"] = { "7d": "7day", "1m": "1month", "3m": "3month", "6m": "6month", "12m": "12month", "overall": "overall" }[i] return "04│ " + url.format( url.shorten(tapmusic + urlencode(defaults)))
def shortgo(server, message, url): """ Shorten a URL. If no URL is provided, shorten the last posted URL. """ if not url: url = grabber.last(server.lower(message.context)) return "12%s│ %s" % ("🔗" * message.text.startswith("@"), URL.format(URL.shorten(url)))
def latlong_to_addr(latlong): latlong = latlong.replace(";", ",") format_data = "\x0312\x1f%s\x1f\x03" % shorten("https://www.google.com/maps/search/%s" % latlong) if "key" in apikeys: data = requests.get("https://maps.googleapis.com/maps/api/geocode/json", params={"latlng": latlong, "key": apikeys["key"]}).json() try: addr = data["results"][0]["formatted_address"] except: pass else: format_data = addr + " · " + format_data return format_data
def mean_girls(server, msg): params = { "start": random.randrange(1, 75), "safe": "off", "v": "1.0", "rsz": 1, "q": "mean girls quotes" } pic = requests.get( "https://ajax.googleapis.com/ajax/services/search/images", params=params).json()["responseData"]["results"][0]["url"] return url.format(url.shorten(pic))
def image(server, msg, flags, query): """ Image search. Search for the given terms on Google. If a number is given, it will display that result. Code adapted from kochira :v """ params = { "cx": cfg["img"], "key": cfg["key"], "searchType": "image", "safe": "off", "num": deflines[msg.prefix], "q": query } if flags: for i in flags[1:].strip(): if i.isdigit(): params["num"] = min(int(i), maxlines[msg.prefix]) else: params.update({"f": {"imgType": "face"}, "p": {"imgType": "photo"}, "c": {"imgType": "clipart"}, "l": {"imgType": "lineart"}, "g": {"imgType": "animated"}, "s": {"safe": "high"} }[i]) r = requests.get( "https://www.googleapis.com/customsearch/v1", params=params ).json() results = r.get("items", []) for i, result in enumerate(results): server.lasturl = result["link"] yield templates[msg.prefix] % {"color" : [12, 5, 8, 3][i % 4], "url": url.shorten(unquote(result["link"])), "fullurl": result["displayLink"], "width": result["image"]["width"], "height": result["image"]["height"], "content": unescape(re.sub("</?b>", "", result["htmlSnippet"])), "title": unescape(re.sub("</?b>", "", result["htmlTitle"]))} if not results: yield "12Google Images│ No results."
def mean_girls(server, msg): params = { "start": random.randrange(1,75), "safe": "off", "v": "1.0", "rsz": 1, "q": "mean girls quotes" } pic = requests.get( "https://ajax.googleapis.com/ajax/services/search/images", params=params ).json()["responseData"]["results"][0]["url"] return url.format(url.shorten(pic))
def image(server, msg, flags, query): """ Image search. Search for the given terms on Google. If a number is given, it will display that result. Code adapted from kochira :v """ params = { "safe": "off", "v": "1.0", "rsz": deflines[msg.prefix], "q": query } if flags: for i in flags[1:].strip(): if i.isdigit(): params["rsz"] = min(int(i), maxlines[msg.prefix]) else: params.update({"f": {"imgtype": "face"}, "p": {"imgtype": "photo"}, "c": {"imgtype": "clipart"}, "l": {"imgtype": "lineart"}, "g": {"as_filetype": "gif"}, "s": {"safe": "active"} }[i]) r = requests.get( "https://ajax.googleapis.com/ajax/services/search/images", params=params ).json() results = r.get("responseData", {}).get("results", []) for i, result in enumerate(results): server.lasturl = result["url"] yield templates[msg.prefix] % {"color" : [12, 5, 8, 3][i % 4], "url": url.shorten(result["url"]), "fullurl": result["visibleUrl"], "width": result["width"], "height": result["height"], "content": unescape(re.sub("</?b>", "", result["content"])), "title": unescape(re.sub("</?b>", "", result["title"]))} if not results: yield "12Google Images│ No results."
def push_text(push): fields = [] if push["type"] in ["note", "link", "file"]: message_field = [] if "file_url" in push: fields.append(url.format(url.shorten(push["file_url"]))) if "title" in push: message_field.append("\x0303%s\x03" % push["title"]) if "body" in push: message_field.append(push["body"].replace("\n", " · ")) # TODO: temporary if message_field: fields.append(" ".join(message_field)) if "url" in push: try: fields.append(url.format(url.shorten(push["url"]))) except: fields.append(url.format(push["url"])) elif push["type"] == "address": if "name" in push: fields.append("\x0303 📍 %s\x03" % push["name"]) if "address" in push: fields.append(push["address"]) return " · ".join(fields)
def urban_lookup(bot, msg, arg, index): ''' UrbanDictionary lookup. ''' url = 'http://www.urbandictionary.com/iphone/search/define' params = {'term': arg} nick = msg.address.nick try: index = int(index.strip()) - 1 except: index = 0 request = requests.get(url, params=params) data = request.json() defs = None output = "" try: defs = data['list'] if data['result_type'] == 'no_results': return failmsg() % (nick, params['term']) output = "%s 15│ %s" % (defs[index]['word'], re.sub( r"\[(.+?)\]", "\x02\\1\x02", re.sub(r"\[word\](.+?)\[/word\]", "\x02\\1\x02", defs[index]['definition']))) except: return failmsg() % params['term'] output = " ".join(output.split()) sentences = re.split("([!.?]+)", output) output = sentences.pop(0) i = 1 while sentences: s = sentences.pop(0) if i % 2 or len(output) + len(s) < 350: output += s else: sentences = [s] + sentences # put it back gently break i += 1 if sentences: output += '\n15│ Read more: %s' % format( shorten(defs[index]['permalink'])) return "15│ %s" % output
def yo_receive(self, route, evt): if route in self.routes: if "link" in evt: self.server.message( "04│🖐│ Yo, check out \x0312\x1f%s\x1f\x03 · from %s" % (shorten(evt["link"][0]), evt["username"][0]), self.routes[route]) elif "location" in evt: self.server.message( "04│🖐│ Yo, I'm at %s · from %s" % (self.latlong_to_addr( evt["location"][0]), evt["username"][0]), self.routes[route]) else: self.server.message( "04│🖐│ Yo! · from %s" % evt["username"][0], self.routes[route])
def fiftyfifty(server, message, sublist): if not sublist: sublist = random.choice(defaults) else: sublist = [[i for i in x.strip().split() if re.match(subreddit_rx, i)] for x in sublist.split("|")] subs = [random.choice(i) for i in sublist] links = [get_rand_link(i) for i in subs] if None in links: return "\x0304│ 50/50 |\x0304 Couldn't find a link post." link = random.choice(links)["url"] titles = " | ".join(i["title"] for i in links) if len(sublist) > 1: titles = "%s \x0308│\x03 %s" % ("/".join(["%d"%(100//len(sublist))]*len(sublist)), titles) else: titles = re.sub(r"^\[50/50\] ", "50/50 \x0308│\x03 ", titles) return "\x0308│\x03 %s · \x0312\x1f%s" % (titles, url.shorten(link))
def latlong_to_addr(latlong): latlong = latlong.replace(";", ",") format_data = "\x0312\x1f%s\x1f\x03" % shorten( "https://www.google.com/maps/search/%s" % latlong) if "key" in apikeys: data = requests.get( "https://maps.googleapis.com/maps/api/geocode/json", params={ "latlng": latlong, "key": apikeys["key"] }).json() try: addr = data["results"][0]["formatted_address"] except: pass else: format_data = addr + " · " + format_data return format_data
def urban_lookup(bot, msg, arg, index): ''' UrbanDictionary lookup. ''' url = 'http://www.urbandictionary.com/iphone/search/define' params = {'term': arg} nick = msg.address.nick try: index = int(index.strip()) - 1 except: index = 0 request = requests.get(url, params=params) data = request.json() defs = None output = "" try: defs = data['list'] if data['result_type'] == 'no_results': return failmsg() % (nick, params['term']) output = "%s 15│ %s" % (defs[index]['word'], re.sub(r"\[(.+?)\]", "\x02\\1\x02", defs[index]['definition'])) except: return failmsg() % params['term'] output = " ".join(output.split()) sentences = re.split("([!.?]+)", output) output = sentences.pop(0) i = 1 while sentences: s = sentences.pop(0) if i % 2 or len(output) + len(s) < 350: output += s else: sentences = [s] + sentences # put it back gently break i += 1 if sentences: output += '\n15│ Read more: %s' % format(shorten(defs[index]['permalink'])) return "15│ %s" % output
def fiftyfifty(server, message, sublist): if not sublist: sublist = random.choice(defaults) else: sublist = [[i for i in x.strip().split() if re.match(subreddit_rx, i)] for x in sublist.split("|")] subs = [random.choice(i) for i in sublist] links = [get_rand_link(i) for i in subs] if None in links: return "\x0304│ 50/50 |\x0304 Couldn't find a link post." link = random.choice(links)["url"] titles = " | ".join(i["title"] for i in links) if len(sublist) > 1: titles = "%s \x0308│\x03 %s" % ("/".join( ["%d" % (100 // len(sublist))] * len(sublist)), titles) else: titles = re.sub(r"^\[50/50\] ", "50/50 \x0308│\x03 ", titles) warning = " · \x0304NSFW" if any(i["over_18"] for i in links) else "" return "\x0308│\x03 %s · \x0312\x1f%s\x0f%s" % (titles, url.shorten(link), warning)
def collage(self, server, message, flags, data, user): tapmusic = "http://tapmusic.net/lastfm/collage.php?" if not user: user = message.address.nick lowername = server.lower(user) if lowername in self.users: user = self.users[lowername] defaults = {"user": user, "type": "7d", "size": "3x3"} for i in (flags or []): if i in "cap": defaults[{"c":"caption","a":"artistonly","p":"playcount"}[i]] = "true" if data: for i in data.split(): if "x" in i: defaults["size"] = i else: defaults["type"] = {"7d": "7day", "1m": "1month", "3m": "3month", "6m": "6month", "12m": "12month", "overall":"overall"}[i] return "04│ "+url.format(url.shorten(tapmusic + urlencode(defaults)))
def image(server, msg, flags, query): """ Image search. Search for the given terms on Google. If a number is given, it will display that result. Code adapted from kochira :v """ params = { "cx": cfg["img"], "key": cfg["key"], "searchType": "image", "safe": "off", "num": deflines[msg.prefix], "q": query } if flags: for i in flags[1:].strip(): if i.isdigit(): params["num"] = min(int(i), maxlines[msg.prefix]) else: params.update({ "f": { "imgType": "face" }, "p": { "imgType": "photo" }, "c": { "imgType": "clipart" }, "l": { "imgType": "lineart" }, "g": { "imgType": "animated" }, "s": { "safe": "high" } }[i]) r = requests.get("https://www.googleapis.com/customsearch/v1", params=params).json() results = r.get("items", []) for i, result in enumerate(results): server.lasturl = result["link"] yield templates[msg.prefix] % { "color": [12, 5, 8, 3][i % 4], "url": url.shorten(unquote(result["link"])), "fullurl": result["displayLink"], "width": result["image"]["width"], "height": result["image"]["height"], "content": unescape(re.sub("</?b>", "", result["htmlSnippet"])), "title": unescape(re.sub("</?b>", "", result["htmlTitle"])) } if not results: yield "12Google Images│ No results."
def wolfram_format(self, query, category=None, h_max=None): try: answer = self.wolfram(query) except urllib.error.URLError: return "05Wolfram08Alpha failed to respond. Try again later or go to " + URL.format(URL.shorten("http://www.wolframalpha.com/input/?i=%s" % urllib.parse.quote_plus(query))) if not answer: return "05Wolfram08Alpha returned no results for '07%s'" % query for i in self.input_categories: if i in answer: header = answer[i] remove = i break else: header ="'%s'"%query remove = False header = str.join(" ", header.split()) h_max = h_max or self.h_max if not category: results = answer if remove: results = collections.OrderedDict([(k, v) for k, v in answer.items() if k != remove]) if category is not None: # Guess the category for i in self.results: if i in answer: results = {i: results[i]} break else: results = {list(results.keys())[0]: list(results.values())[0]} else: results = max(answer, key=lambda x:difflib.SequenceMatcher(None, category, x).ratio()) results = {results:answer[results]} output = [spacepad("05Wolfram08Alpha 04 ", " %s" % header, self.t_max)] t_max = striplen(output[0]) results = collections.OrderedDict([(k, self.breakdown(v.split("\n"), t_max - 3)) for k, v in results.items()]) total_lines = sum([min(len(results[x]), h_max) for x in results]) if total_lines > self.t_lines: # Too many lines, print the available categories instead. for i in justifiedtable(sorted(results.keys(), key=len) + ["05Categories"], t_max-3): output.append(" 04⎪ %s" % i) output[-1] = " 04⎩" + output[-1][5:] elif results: if len(results) == 1 and len(list(results.values())[0]) == 1: # Single line: Shorten output catname = list(results.keys())[0] if catname in self.results: output = ["08│ %s " % list(results.values())[0][0]] else: output = [spacepad("08│ %s " % list(results.values())[0][0], "07%s" % catname, t_max)] else: for category in results: lines = [x.rstrip() for x in results[category]] output.append(spacepad(" 08⎨ %s " % lines.pop(0), " 07%s" % category, t_max)) truncated = lines[:h_max] for line in truncated: output.append(" 08⎪ " + line) if len(truncated) < len(lines): omission = "%d more lines" % (len(lines) - h_max) length = t_max - len(omission) - 5 output[-1] = " 08⎬�" + ("-"*int(length)) + " 07%s" % omission else: output.append(" 08‣ 05No plaintext results. See " + URL.format(URL.shorten("http://www.wolframalpha.com/input/?i=%s" % urllib.parse.quote_plus(query)))) return "\n".join(i.rstrip() for i in output)
def yo_receive(self, route, evt): if route in self.routes: if "link" in evt: self.server.message("04│🖐│ Yo, check out \x0312\x1f%s\x1f\x03 · from %s" % (shorten(evt["link"][0]), evt["username"][0]), self.routes[route]) elif "location" in evt: self.server.message("04│🖐│ Yo, I'm at %s · from %s" % (self.latlong_to_addr(evt["location"][0]), evt["username"][0]), self.routes[route]) else: self.server.message("04│🖐│ Yo! · from %s" % evt["username"][0], self.routes[route])
def shortgo(message, url): if not url: url = lg.links[server.lower(message.context)][-1] return "12%s│ %s" % ("bit.ly" * message.text.startswith("@"), URL.format(URL.shorten(url)))
def wolfram_format(self, query, category=None, h_max=None, user=None, wasettings={}): try: if self.last is not None: query = query.replace("$_", self.last) answer, url = parallelise([ lambda: self.wolfram(query, **wasettings), lambda: URL.shorten("http://www.wolframalpha.com/input/?i=%s" % urllib.parse.quote_plus(query)) ]) if "Result" in answer and "(" not in answer["Result"]: self.last = answer["Result"] else: self.last = "(%s)" % query except urllib.error.URLError: return "05Wolfram08Alpha failed to respond. Try again later or go to " + URL.format( url) if not answer: return "05Wolfram08Alpha returned no results for '07%s'" % query for i in self.input_categories: if i in answer: header = answer[i] remove = i break else: header = "'%s'" % query remove = False header = str.join(" ", header.split()) h_max = h_max or self.h_max if not category: results = answer if remove: results = collections.OrderedDict([(k, v) for k, v in answer.items() if k != remove]) if category is not None: # Guess the category for i in self.results: if i in answer: results = {i: results[i]} break else: results = { list(results.keys())[0]: list(results.values())[0] } else: results = max(answer, key=lambda x: difflib.SequenceMatcher( None, category, x).ratio()) results = {results: answer[results]} output = [ spacepad("05Wolfram08Alpha 04 ", " %s" % header, self.t_max) ] t_max = striplen(output[0]) results = collections.OrderedDict([ (k, self.breakdown(v.split("\n"), t_max - 3)) for k, v in results.items() ]) total_lines = sum([min(len(results[x]), h_max) for x in results]) if total_lines > self.t_lines: # Too many lines, print the available categories instead. for i in justifiedtable( sorted(results.keys(), key=len) + ["05Categories"], t_max - 3): output.append(" 04⎪ %s" % i) output[-1] = " 04⎩" + output[-1][5:] elif results: if len(results) == 1 and len(list(results.values())[0]) == 1: # Single line: Shorten output catname = list(results.keys())[0] if catname in self.results: output = ["08│ %s " % list(results.values())[0][0]] else: output = [ spacepad("08│ %s " % list(results.values())[0][0], "07%s" % catname, self.t_max) ] else: for category in results: lines = [x.rstrip() for x in results[category]] output.append( spacepad(" 08⎨ %s " % lines.pop(0), " 07%s" % category, t_max)) truncated = lines[:h_max] for line in truncated: output.append(" 08⎪ " + line) if len(truncated) < len(lines): omission = "%d more lines" % (len(lines) - h_max + 1) length = t_max - len(omission) - 6 - len(url) output[-1] = " 08� " + url + " " + ( "-" * int(length)) + " 07%s" % omission else: output.append(" 08‣ 05No plaintext results. See " + URL.format( URL.shorten("http://www.wolframalpha.com/input/?i=%s" % urllib.parse.quote_plus(query)))) return "\n".join(i.rstrip() for i in output)