Ejemplo n.º 1
0
    def send_messages(self, user, context, immediate=False):
        popindices = []
        for i in self.reminders.get(self.server.lower(user), []):
            if time.time() >= i["after"] - 1:  # Fudge factor
                method = {
                    "pm": (user, "PRIVMSG"),
                    "private message": (user, "PRIVMSG"),
                    "message": (context, "PRIVMSG"),
                    "channel message": (context, "PRIVMSG"),
                    "notice": (user, "NOTICE")
                }[i["method"]]
                self.server.message(
                    "03│ ✉ │ %s: %s · from %s · ⌚ %s" %
                    (user, i["message"], i["sender"],
                     pretty_date(time.time() - i["time"])), *method)

                @command("reply", r"(.+)")
                def tellreply(server, message, text):
                    return self.reminder.funct(self, server, message,
                                               i["sender"], "", text, "",
                                               i["method"], "", "")

                self.server.reply_hook = tellreply
                popindices.append(i)
        for i in popindices[::-1]:
            self.reminders[self.server.lower(user)].remove(i)
        with open(self.server.get_config_dir(self.REMINDERF), "w") as f:
            json.dump(self.reminders, f)
Ejemplo n.º 2
0
        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
Ejemplo n.º 3
0
    def get_weatherdata(self, server, message, location):
        user = message.address.nick

        try:
            loc_id = self.guess_locid(user, 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│ ☀ │ Location not recognised."

        self.throttle.acquire()
        data = "http://api.wunderground.com/api/%s/conditions/q/%s" % (apikey,
                                                                       loc_id)
        data = requests.get(data).json()
        try:
            data = data["current_observation"]
        except:
            return "04│ ☀ │ Couldn't figure out the weather."
        station = data["station_id"]
        conditions = {
            "location": data["display_location"]["full"],
            "weather": data["weather"],
            "temperature": data["temperature_string"],
            "feels_like": data["feelslike_string"],
            "wind": data["wind_string"],
            "windchill": data["windchill_string"],
            "humidity": data["relative_humidity"],
            "visibility": data["visibility_km"],
            "precipitation": data["precip_today_metric"],
            "UV": data["UV"],
            "icon": icon_to_unicode(data["icon"])
        }
        t = data["temp_c"]
        temperature_color = [2, 12, 14, 7,
                             4][(t > 6) + (t > 16) + (t > 26) + (t > 36)]
        temperature = "%d °C \x0315%d °F\x03" % (data["temp_c"],
                                                 data["temp_f"])
        pieces = [
            "%s %s" % (conditions["icon"], conditions["weather"]),
            "\x03%d🌡 %s" % (temperature_color, temperature)
        ]
        pieces.append("%s humidity" % data["relative_humidity"])
        pieces.append("⌚ " + pretty_date(
            int(data["local_epoch"]) - int(data["observation_epoch"])))
        return "2│ %s 2│ %s" % (data["display_location"]["full"],
                                    " · ".join(pieces))
Ejemplo n.º 4
0
    def get_weatherdata(self, server, message, location):
        user = message.address.nick

        try:
            loc_id = self.guess_locid(user, 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│ ☀ │ Location not recognised."

        self.throttle.acquire()
        data = "http://api.wunderground.com/api/%s/conditions/q/%s" % (apikey, loc_id)
        data = requests.get(data).json()
        try:
            data = data["current_observation"]
        except:
            return "04│ ☀ │ Couldn't figure out the weather."
        station = data["station_id"]
        conditions = {
            "location": data["display_location"]["full"],
            "weather": data["weather"],
            "temperature": data["temperature_string"],
            "feels_like": data["feelslike_string"],
            "wind": data["wind_string"],
            "windchill": data["windchill_string"],
            "humidity": data["relative_humidity"],
            "visibility": data["visibility_km"],
            "precipitation": data["precip_today_metric"],
            "UV": data["UV"],
            "icon": icon_to_unicode(data["icon"]),
        }
        t = data["temp_c"]
        temperature_color = [2, 12, 14, 7, 4][(t > 6) + (t > 16) + (t > 26) + (t > 36)]
        temperature = "%d °C \x0315%d °F\x03" % (data["temp_c"], data["temp_f"])
        pieces = [
            "%s %s" % (conditions["icon"], conditions["weather"]),
            "\x03%d🌡 %s" % (temperature_color, temperature),
        ]
        pieces.append("%s humidity" % data["relative_humidity"])
        pieces.append("⌚ " + pretty_date(int(data["local_epoch"]) - int(data["observation_epoch"])))
        return "2│ %s 2│ %s" % (data["display_location"]["full"], " · ".join(pieces))
Ejemplo n.º 5
0
def push_format(push, sent, users):
    fields = []
    body = push_text(push)
    if body: fields.append(body)

    if push["iden"] in sent:
        sent.remove(push["iden"])
        tag, email = "to", push["receiver_email"]
    else:
        tag, email = "from", push["sender_email"]
    if email.lower() in users:
        user = users[email.lower()]
    else:
        user = "******" + email + "\x03"

    fields.append(tag + " " + user)
    timedelta = pretty_date(time.time() - push["modified"])
    if timedelta != "just now":
        fields.append("\u231a " + timedelta)
    
    return "03│ ⁍ │ " + " · ".join(fields)
Ejemplo n.º 6
0
    def search(self, server, message, anchor, frm, to, typefilter, users, context):
        if not context:
            context = message.context
        elif "#" not in context:
            target = [i for i in self.settings if self.settings[i]["username"].lower() == context.lower()]
            if not target:
                yield prefix + "\x0304No associated channel for that snapchat account."
                return
            context = target[0]
        context = server.lower(context)
        if context not in self.settings:
            yield prefix + "\x0304No associated snapchat for this channel."
            return

        new = []
        if not any((anchor, frm, to, typefilter, users)):
            new = list(self.newsnaps(context))
            for i in new:
                yield i + " [NEW]"
                if context != server.lower(message.context):
                    server.message(i, message.context)
            new = [i.rsplit("·", 1)[0] for i in new]

        if not anchor:
            frm, to, anchor = -1, -2 if message.prefix == "." else -5, -1
        elif anchor.lower() == "last":
            frm, to, anchor = -int(frm or 1), -int(to)-1 if to else None, -1
        elif anchor.lower() == "first":
            frm, to, anchor = int(frm or 1)-1, int(to) if to else None, 1
        types = {"gifs": {2},
                 "videos": {1},
                 "snaps": {0, 1, 2},
                 "pics": {0},
                 "clips": {1, 2}}
        filtr = set()
        if not typefilter: typefilter = "snaps"
        for i in re.split(r"\s+or\s+|\s+and\s+|\s*/\s*|\s*\+\s*", typefilter):
            filtr |= types[i.lower()]
        if users:
            users = {i.lower() for i in re.split(r"\s+or\s+|\s+and\s+|\s*/\s*|\s*\+\s*", users)}
        history = self.settings[context]["history"]
        history = [i for i in history if (i["media_type"] in filtr) and ((not users) or (i["sender"].lower() in users))]
        results = history[frm:to:anchor][:1 if message.prefix == "." else 5]
        for i in results:
            server.lasturl = self.settings[context]["snaps"][i["id"]]
            res = prefix + "\x0312\x1f%s\x1f\x0f · from %s · \u231a %s" % (self.settings[context]["snaps"][i["id"]], i["sender"], pretty_date(time.time() - i["sent"]/1000) if i["sent"] else "Unknown")
            if res.rsplit("·", 1)[0] not in new:
                yield res
Ejemplo n.º 7
0
    def newsnaps(self, channel):
        account = self.accounts[channel]

        if channel not in self.accounts or channel not in self.settings:
            return
        self.settings[channel]["last"] = time.time()
        snaps = account.get_snaps(self.settings[channel]["last"])
        for snap in snaps:
            try:
                if snap["id"] in self.settings[channel]["snaps"]:
                    continue
                blob = account.get_blob(snap["id"])
                if not blob:
                    self.settings[channel]["snaps"][snap["id"]] = None
                    continue
                self.unverified = {k:v for k, v in self.unverified.items() if v[0].lower() != snap["sender"].lower()}
                print(snap)
                print("*** Saving", snap["id"])
                url = self.snapsave(blob, snap["media_type"])
                print("*** URL:", url)
                self.settings[channel]["snaps"][snap["id"]] = url
                self.settings[channel].setdefault("history", []).append(snap)
                account.mark_viewed(snap["id"])
                self.server.lasturl = url
                username = [k for k, v in self.users.items() if v.lower() == snap["sender"].lower()] + [i for i in self.settings if self.settings[i]["username"].lower() == snap["sender"].lower()]
                yield prefix + "\x0312\x1f%s\x1f\x0f · from %s · \u231a %s" % (url, snap["sender"] + (" (%s)" % username[0] if username else ""), pretty_date(time.time() - snap["sent"]/1000) if snap["sent"] else "Unknown")
            except:
                traceback.print_exc()
        json.dump(self.settings, open(self.settingsf, "w"))
Ejemplo n.º 8
0
 def send_messages(self, user, context, immediate=False):
     for i in self.reminders[self.server.lower(user)]:
         if time.time() >= i["after"] - 1: # Fudge factor
             method = {"pm": (user, "PRIVMSG"),
                      "private message": (user, "PRIVMSG"),
                      "message": (context, "PRIVMSG"),
                      "channel message": (context, "PRIVMSG"),
                      "notice": (user, "NOTICE")}[i["method"]]
             self.server.message("03│ ✉ │ %s: %s · from %s · ⌚ %s" % (user, i["message"], i["sender"], pretty_date(time.time() - i["time"])), *method)
             self.reminders[self.server.lower(user)].remove(i)
     with open(self.server.get_config_dir(self.REMINDERF), "w") as f:
         json.dump(self.reminders, f)
Ejemplo n.º 9
0
    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
Ejemplo n.º 10
0
 def send_messages(self, user, context, immediate=False):
     popindices = []
     for i in self.reminders.get(self.server.lower(user), []):
         if time.time() >= i["after"] - 1: # Fudge factor
             method = {"pm": (user, "PRIVMSG"),
                      "private message": (user, "PRIVMSG"),
                      "message": (context, "PRIVMSG"),
                      "channel message": (context, "PRIVMSG"),
                      "notice": (user, "NOTICE")}[i["method"]]
             self.server.message("03│ ✉ │ %s: %s · from %s · ⌚ %s" % (user, i["message"], i["sender"], pretty_date(time.time() - i["time"])), *method)
             @command("reply", r"(.+)")
             def tellreply(server, message, text):
                 return self.reminder.funct(self, server, message, i["sender"], "", text, "", i["method"], "", "")
             self.server.reply_hook = tellreply
             popindices.append(i)
     for i in popindices[::-1]:
         self.reminders[self.server.lower(user)].remove(i)
     with open(self.server.get_config_dir(self.REMINDERF), "w") as f:
         json.dump(self.reminders, f)