def now_playing(self, message, lastnum, username): difftime = collections.OrderedDict() difftime["start"] = time.time() colors = [1, 14, 15] if not username: username = message.address.nick if lastnum: lastnum = -int(lastnum) lowername = cb.bot.lower(username) if lowername in self.users: username = self.users[lowername] user = self.network.get_user(username) trackdata = {i:"" for i in ("duration", "timeago", "title", "artist", "link", "listens", "loved", "barelink", "tad", "album", "dotlink")} difftime["user"] = time.time() track, recent = util.parallelise([user.get_now_playing, lambda: user.get_recent_tracks(limit=lastnum or 1)]) difftime["np"] = time.time() if not track or lastnum: recent = recent[-1] since = time.time() - int(recent.timestamp) # Calculate colour scolour = colors[min(2, int(math.log(since/60 +1, 60)))] trackdata["timeago"] = "%.2d⌚ %s " % (scolour, pretty_date(since)) trackdata["tad"] = "· %s" % trackdata["timeago"] track = recent.track difftime["recent"] = time.time() trackdata["duration"] = "⌛ %dm%.2ds" % divmod(track.get_duration()/1000, 60) trackdata["artist"], trackdata["title"] = (track.get_artist(), track.get_title()) trackname = "%(artist)s - %(title)s" % trackdata jobs = [lambda: self.get_yt_data(trackname), lambda: self.get_listens(username, track.get_mbid()), lambda: self.get_album(track)] if message.prefix in "!@": # Provide full template template = "04Last.FM│ %(loved)s%(artist)s%(album)s · %(title)s\n"\ "04Last.FM│ %(listens)s%(timeago)s%(duration)s %(link)s" else: template = "04│ %(loved)s%(artist)s · %(title)s (%(duration)s) %(tad)s%(dotlink)s" difftime["template"] = time.time() for i in util.parallelise(jobs): trackdata.update(i) final = time.time() for i in difftime: print("[Last.FM] %s: %f" % (i, final - difftime[i])) return template % trackdata
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 get_time(self, server, message, user): if not user: user = message.address.nick # No arguments, get sender's time try: try: location = self.get_user_locid(user) # Try treating the argument as a user except KeyError: try: location = self.get_locid(user) # Try treating argument as a location except KeyError: return "04│ ☀ │ I don't know where you live! Set your location with .set location \x02city\x02 or specify it manually." except LookupError: return "04│ ☀ │ No timezone information for your location." wurl = "http://api.wunderground.com/api/%s/conditions/q/%s" % (apikey, location) lurl = "http://api.wunderground.com/api/%s/astronomy/q/%s" % (apikey, location) self.throttle.acquire() self.throttle.acquire() weather, astro = util.parallelise([lambda: requests.get(wurl).json(), lambda: requests.get(lurl).json()]) try: weather = weather["current_observation"] astro = astro["moon_phase"] except: return "04│ ☀ │ No timezone data." sunrise, now, sunset = ( (int(astro["sunrise"]["hour"]), int(astro["sunrise"]["minute"])), (int(astro["current_time"]["hour"]), int(astro["current_time"]["minute"])), (int(astro["sunset"]["hour"]), int(astro["sunset"]["minute"])), ) if sunrise < now < sunset: sigil = "\x0307☀\x03" else: sigil = "\x032🌙\x03" localtime = int(weather["local_epoch"]) timezone = weather["local_tz_offset"] polarity, hours, mins = timezone[0], int(timezone[1:3]), int(timezone[3:5]) offset = hours * 60 * 60 + mins * 60 localtime = localtime + offset if polarity == "+" else localtime - offset localtime = datetime.datetime.utcfromtimestamp(localtime) date = "%(weekday)s, %(month)s %(day)s, %(year)s" % { "weekday": weekdays[localtime.weekday()], "month": months[localtime.month - 1], "day": localtime.day, "year": localtime.year, } return "2│ %(sigil)s %(hour).2d:%(minute).2d:%(second).2d %(ampm)s \x0315%(timezone)s\x03 · %(date)s" % { "timezone": weather["local_tz_short"], "sigil": sigil, "hour": localtime.hour % 12, "minute": localtime.minute, "second": localtime.second, "date": date, "ampm": "am" if localtime.hour < 12 else "pm", }
def youtube(server, message, nresults, query): if nresults: nresults = min(-int(nresults.strip()), lines[message.prefix]) else: nresults = lines[message.prefix] results = yt.search(query, results=nresults) for i in results: data = {"title": i["snippet"]["title"], "url": i["id"]["videoId"]} if message.prefix != ".": channelinfo, stats = parallelise([lambda: yt.get_channel_info(i["snippet"]["channelId"]), lambda: yt.stats(i["id"]["videoId"])]) data["likebar"] = likebar(int(stats["likeCount"]), int(stats["dislikeCount"])) data["views"] = "{:,}".format(int(stats["viewCount"])) data["channel"] = channelinfo["title"] else: channelinfo = yt.get_channel_info(i["snippet"]["channelId"]) data["channel"] = channelinfo["title"] yield templates[message.prefix] % data
def youtube(server, message, nresults, query): if nresults: nresults = min(-int(nresults.strip()), lines[message.prefix]) else: nresults = lines[message.prefix] results = yt.search(query, results=nresults) for i in results: data = {"title": i["snippet"]["title"], "url": i["id"]["videoId"]} if message.prefix != ".": channelinfo, stats = parallelise([ lambda: yt.get_channel_info(i["snippet"]["channelId"]), lambda: yt.stats(i["id"]["videoId"]) ]) data["likebar"] = likebar(int(stats["likeCount"]), int(stats["dislikeCount"])) data["views"] = "{:,}".format(int(stats["viewCount"])) data["channel"] = channelinfo["title"] else: channelinfo = yt.get_channel_info(i["snippet"]["channelId"]) data["channel"] = channelinfo["title"] yield templates[message.prefix] % data
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)
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)
def get_time(self, server, message, user): if not user: user = message.address.nick # No arguments, get sender's time try: try: location = self.get_user_locid(user) # Try treating the argument as a user except KeyError: try: location = self.get_locid(user) # Try treating argument as a location except KeyError: return "04│ ☀ │ I don't know where you live! Set your location with .set location \x02city\x02 or specify it manually." except LookupError: return "04│ ☀ │ No timezone information for your location." wurl = "http://api.wunderground.com/api/%s/conditions/q/%s" % ( apikey, location) lurl = "http://api.wunderground.com/api/%s/astronomy/q/%s" % (apikey, location) self.throttle.acquire() self.throttle.acquire() weather, astro = util.parallelise([ lambda: requests.get(wurl).json(), lambda: requests.get(lurl).json() ]) try: weather = weather["current_observation"] astro = astro["moon_phase"] except: return "04│ ☀ │ No timezone data." sunrise, now, sunset = (int( astro["sunrise"]["hour"]), int(astro["sunrise"]["minute"])), ( int(astro["current_time"]["hour"]), int(astro["current_time"]["minute"])), (int( astro["sunset"]["hour"]), int(astro["sunset"]["minute"])) if sunrise < now < sunset: sigil = "\x0307☀\x03" else: sigil = "\x032🌙\x03" localtime = int(weather["local_epoch"]) timezone = weather["local_tz_offset"] polarity, hours, mins = timezone[0], int(timezone[1:3]), int( timezone[3:5]) offset = hours * 60 * 60 + mins * 60 localtime = localtime + offset if polarity == "+" else localtime - offset localtime = datetime.datetime.utcfromtimestamp(localtime) date = "%(weekday)s, %(month)s %(day)s, %(year)s" % { "weekday": weekdays[localtime.weekday()], "month": months[localtime.month - 1], "day": localtime.day, "year": localtime.year } return "2│ %(sigil)s %(hour).2d:%(minute).2d:%(second).2d %(ampm)s \x0315%(timezone)s\x03 · %(date)s" % { "timezone": weather["local_tz_short"], "sigil": sigil, "hour": localtime.hour % 12, "minute": localtime.minute, "second": localtime.second, "date": date, "ampm": "am" if localtime.hour < 12 else "pm" }
def now_playing(self, server, message, lastnum, username): difftime = collections.OrderedDict() difftime["start"] = time.time() colors = [1, 14, 15] if not username: username = message.address.nick if lastnum: lastnum = -int(lastnum) lowername = server.lower(username) if lowername in self.users: username = self.users[lowername] user = self.network.get_user(username) trackdata = { i: "" for i in ("duration", "timeago", "title", "artist", "link", "listens", "loved", "barelink", "tad", "album", "dotlink") } difftime["user"] = time.time() track, recent = util.parallelise([ user.get_now_playing, lambda: user.get_recent_tracks(limit=lastnum or 1) ]) difftime["np"] = time.time() if not track or lastnum: recent = recent[-1] since = time.time() - int(recent.timestamp) # Calculate colour scolour = colors[min(2, int(math.log(since / 60 + 1, 60)))] trackdata["timeago"] = "%.2d⌚ %s " % (scolour, pretty_date(since)) trackdata["tad"] = "· %s" % trackdata["timeago"] track = recent.track difftime["recent"] = time.time() trackdata["duration"] = "⌛ %dm%.2ds" % divmod( track.get_duration() / 1000, 60) trackdata["artist"], trackdata["title"] = (track.get_artist(), track.get_title()) trackname = "%(artist)s - %(title)s" % trackdata jobs = [ lambda: self.get_yt_data(trackname), lambda: self.get_listens(username, track.get_mbid()), lambda: self.get_album(track) ] if message.prefix in "!@": # Provide full template template = "04│ ♫ │ %(loved)s%(artist)s%(album)s · %(title)s\n"\ "04│ ♫ │ %(listens)s%(timeago)s%(duration)s %(link)s" else: template = "04│ %(loved)s%(artist)s · %(title)s (%(duration)s) %(tad)s%(dotlink)s" difftime["template"] = time.time() for i in util.parallelise(jobs): trackdata.update(i) final = time.time() for i in difftime: print("[Last.FM] %s: %f" % (i, final - difftime[i])) return template % trackdata