Exemplo n.º 1
0
def seen(inp, nick='', chan='', db=None, input=None):
    ".seen <nick> -- Tell when a nickname was last in active in irc"

    if input.conn.nick.lower() == inp.lower():
        # user is looking for us, being a smartass
        return "You need to get your eyes checked."

    if inp.lower() == nick.lower():
        return "Have you looked in a mirror lately?"

    db_init(db)

    last_seen = db.execute("select name, time, quote from seen where name"
                           " like ? and chan = ?", (inp, chan)).fetchone()

    if last_seen:
        reltime = timesince.timesince(last_seen[1])
        if last_seen[0] != inp.lower():  # for glob matching
            inp = last_seen[0]
        return '%s was last seen %s ago saying: %s' % \
                    (inp, reltime, last_seen[2])
    else:
        from random import random
        seen_time = int(31557600 * random()) # 1 year ago
        reltime = timesince.timesince(int(time.time() - seen_time))
        return '%s was last seen %s ago saying: %s' % \
                    (inp, reltime, 'Volte is always wrong')
Exemplo n.º 2
0
def twitter_url(match, bot=None):
    # Find the tweet ID from the URL
    tweet_id = match.group(1)

    # Get the tweet using the tweepy API
    api = get_api(bot)
    if not api:
        return
    try:
        tweet = api.get_status(tweet_id)
        user = tweet.user
    except tweepy.error.TweepError:
        return

    # Format the return the text of the tweet
    text = " ".join(tweet.text.split())

    if user.verified:
        prefix = u"\u2713"
    else:
        prefix = ""

    time = timesince.timesince(tweet.created_at, datetime.utcnow())

    return u"{}@\x02{}\x02 ({}): {} ({} ago)".format(prefix, user.screen_name, user.name, text, time)
Exemplo n.º 3
0
def seen(text, nick, chan, db, input, conn):
    """seen <nick> <channel> -- Tell when a nickname was last in active in one of this bot's channels."""

    if input.conn.nick.lower() == text.lower():
        return "You need to get your eyes checked."

    if text.lower() == nick.lower():
        return "Have you looked in a mirror lately?"

    if not re.match("^[A-Za-z0-9_|.\-\]\[]*$", text.lower()):
        return "I can't look up that name, its impossible to use!"

    db_init(db, conn.name)

    last_seen = db.execute("select name, time, quote from seen_user where name"
                           " like :name and chan = :chan", {'name': text, 'chan': chan}).fetchone()

    if last_seen:
        reltime = timesince.timesince(last_seen[1])
        if last_seen[0] != text.lower():  # for glob matching
            text = last_seen[0]
        if last_seen[2][0:1] == "\x01":
            return '{} was last seen {} ago: * {} {}'.format(text, reltime, text,
                                                             last_seen[2][8:-1])
        else:
            return '{} was last seen {} ago saying: {}'.format(text, reltime, last_seen[2])
    else:
        return "I've never seen {} talking in this channel.".format(text)
Exemplo n.º 4
0
def seen(inp, nick='', chan='', db=None, input=None):
    "seen <nick> -- Tell when a nickname was last on active in irc"

    if input.conn.nick == inp:
        return "You need to get your eyes checked."
    inp = inp.split(" ")[0]
    db_init(db)
    last_seen = db.execute("select name, time, quote, chan, event from seen where name like (?) order by time desc", (inp.replace("*","%"),)).fetchone()

    if last_seen:
        reltime = timesince.timesince(last_seen[1])
        if last_seen[0] != inp.lower():  # for glob matching
            inp = last_seen[0]
        if last_seen[4] == "privmsg":
            if last_seen[2][0:1]=="\x01":
                return '%s was last seen %s ago in %s: *%s %s*' % (last_seen[0], reltime, last_seen[3], inp, last_seen[2][8:-1])
            else:
                return '%s was last seen %s ago in %s saying: %s' % (last_seen[0], reltime, last_seen[3], last_seen[2])
        if last_seen[4] == "join":
            return '%s was last seen %s ago joining %s' % (last_seen[0], reltime, last_seen[3])
        if last_seen[4] == "part":
            return '%s was last seen %s ago parting %s' % (last_seen[0], reltime, last_seen[3])
        if last_seen[4] == "quit":
            return '%s was last seen %s ago quitting (%s)' % (last_seen[0], reltime, last_seen[2])
        if last_seen[4] == "kick":
            return '%s was last seen %s ago getting kicked from %s' % (last_seen[0], reltime, last_seen[3])
    else:
        return "I've never seen %s" % inp
Exemplo n.º 5
0
def format_reply(history):
    if not history:
        return

    last_nick, recent_time = history[0]
    last_time = timesince.timesince(recent_time)

    if len(history) == 1:
        return "%s linked that %s ago." % (last_nick, last_time)

    hour_span = math.ceil(old_div((time.time() - history[-1][1]), 3600))
    hour_span = "%.0f hours" % hour_span if hour_span > 1 else "hour"

    hlen = len(history)
    ordinal = ["once", "twice", "%d times" % hlen][min(hlen, 3) - 1]

    if len(dict(history)) == 1:
        last = "last linked %s ago" % last_time
    else:
        last = "last linked by %s %s ago" % (last_nick, last_time)

    return "that url has been posted %s in the past %s by %s (%s)." % (
        ordinal,
        hour_span,
        nicklist([h[0] for h in history]),
        last,
    )
Exemplo n.º 6
0
def tellinput(paraml,
              input=None,
              notice=None,
              db=None,
              bot=None,
              nick=None,
              conn=None):
    if 'showtells' in input.msg.lower():
        return

    db_init(db)

    tells = get_tells(db, nick)

    if tells:
        user_from, message, time, chan = tells[0]
        reltime = timesince.timesince(time)

        reply = "%s sent you a message %s ago from %s: %s" % (
            user_from, reltime, chan, message)
        if len(tells) > 1:
            reply += " (+%d more, %sshowtells to view)" % (
                len(tells) - 1, conn.conf["command_prefix"])

        db.execute("delete from tell where user_to=lower(?) and message=?",
                   (nick, message))
        db.commit()
        notice(reply)
Exemplo n.º 7
0
def seen(inp, nick='', chan='', db=None, input=None):
    ".seen <nick> -- Tell when a nickname was last in active in irc"

    inp = inp.lower()

    if input.conn.nick.lower() == inp:
        # user is looking for us, being a smartass
        return "You need to get your eyes checked."

    if inp == nick.lower():
        return "Have you looked in a mirror lately?"

    db_init(db)

    last_seen = db.execute(
        "select name, time, quote from seen where"
        " name = ? and chan = ?", (inp, chan)).fetchone()

    if last_seen:
        reltime = timesince.timesince(last_seen[1])
        if last_seen[0] != inp.lower():  # for glob matching
            inp = last_seen[0]
        if last_seen[2][0:1] == "\x01":
            return '%s was last seen %s ago: *%s %s*' % \
                    (inp, reltime, inp, last_seen[2][8:-1])
        else:
            return '%s was last seen %s ago saying: %s' % \
                    (inp, reltime, last_seen[2])
    else:
        return "I've never seen %s" % inp
Exemplo n.º 8
0
def seen(inp, nick='', chan='', db=None, input=None, bot=None):
    "seen <nick> -- Tell when a nickname was last in active in one of this bot's channels."

    if input.conn.nick.lower() == inp.lower():
        return "You need to get your eyes checked."

    if inp.lower() == nick.lower():
        return "Have you looked in a mirror lately?"

    #if not re.match("^[A-Za-z0-9_|.\-\]\[]*$", inp.lower()):
    #    return "I can't look up that name, its impossible to use!"

    if not db_ready: db_init(db, bot)
    seens = db.execute(
        "select name, time, quote from seen where name like ? and chan = ?",
        (inp, chan)).fetchall()
    last_seen = None
    for i in seens:
        if str(i[0]) == inp.lower():
            last_seen = i
    if last_seen:
        reltime = timesince.timesince(last_seen[1])
        if last_seen[0] != inp.lower():  # for glob matching
            inp = last_seen[0]
        if last_seen[2][0:1] == "\x01":
            print 'notelse'
            return u'{} was last seen {} ago: * {} {}'.format(
                inp, reltime, inp, last_seen[2][8:-1]).encode('utf-8')
        else:
            return u'{} was last seen {} ago saying: {}'.format(
                inp, reltime, last_seen[2]).encode('utf-8')
    else:
        return "I've never seen {} talking in this channel.".format(inp)
Exemplo n.º 9
0
def showuptime(inp):
    "uptime -- shows how long I have been connected for"
    f = open("uptime","r")
    uptime = f.read()
    f.close()
    uptime = timesince.timesince(float(uptime))
    return "I have been online for %s"%uptime
Exemplo n.º 10
0
def seen(inp, nick="", chan="", db=None, input=None):
    ".seen <nick> -- Tell when a nickname was last in active in one of this bot's channels."

    if input.conn.nick.lower() == inp.lower():
        # user is looking for us, being a smartass
        return "You need to get your eyes checked."

    if inp.lower() == nick.lower():
        return "Have you looked in a mirror lately?"

    if not re.match("^[A-Za-z0-9_|.-\]\[]*$", inp.lower()):
        return "I cant look up that name, its impossible to use!"

    db_init(db)

    last_seen = db.execute(
        "select name, time, quote from seen where name" " like ? and chan = ?", (inp, chan)
    ).fetchone()

    if last_seen:
        reltime = timesince.timesince(last_seen[1])
        if last_seen[0] != inp.lower():  # for glob matching
            inp = last_seen[0]
        return "%s was last seen %s ago saying: %s" % (inp, reltime, last_seen[2])
    else:
        return "I've never seen %s" % inp
Exemplo n.º 11
0
Arquivo: seen.py Projeto: Cameri/Gary
def seen(inp, say='', nick='', db=None, input=None):
    """.seen <nick> - Tell when a nickname was last in active in IRC."""
    if input.conn.nick.lower() == inp.lower():
        return "You need to get your eyes checked."
    if inp.lower() == nick.lower():
        return "Have you looked in a mirror lately?"

    rows = db.execute("select chan, nick, action, msg, uts from seen where server = lower(?) and chan in (lower(?), 'quit', 'nick') and (nick = lower(?) or (action = 'KICK' and msg = ?)) order by uts desc limit 1",
        (input.server, input.chan, inp, inp.lower() + "%")).fetchone()

    if rows:
        row = dict(zip(['chan', 'nick', 'action', 'msg', 'uts'], rows))
        reltime = timesince.timesince(row['uts'])
        if row['action'] == 'KICK':
            row['who'] = row['msg'].split(' ')[:1][0]
            row['msg'] = ' '.join(row['msg'].split(' ')[1:]).strip('[]')
            if inp.lower() != row['who'].lower():
                row['action'] = 'KICKEE'

        format = formats.get(row['action'])

        out = '{} was last seen {} ago '.format(inp, reltime)
        say(out + format % row)
    else:
        return "I've never seen %s" % inp
Exemplo n.º 12
0
def first(inp, chan='', bot=None, db=None, say=None):
    """f[irst] [-G] <phrase> - Finds the first occurence of a phrase. Flag -G to search all channels."""
    inp, _global = is_global(inp)

    if not inp:
        return "Check your input and try again."

    if _global:
        match_clause = tokenize.build_query(inp)
    else:
        match_clause = '{} AND chan:"{}"'.format(tokenize.build_query(inp), chan.strip('#'))

    try:
        row = db.execute("select uts, time, chan, nick, action, msg from logfts where logfts match ? and (msg not like '!%' and msg not like ';%' and msg not like '.%') and action = 'PRIVMSG' limit 1",
            (match_clause, )).fetchone()
    except OperationalError:
        return "Error: must contain one inclusive match clause (+/=)."

    if row:
        row = dict(zip(['uts', 'time', 'chan', 'nick', 'action', 'msg'], row))

        row['date'] = row['time'].split(' ')[0]
        row['timesince'] = timesince.timesince(float(row['uts']))
        if bot.config.get("logviewer_url"):
            row['log_url'] = web.try_googl(bot.config["logviewer_url"].format(row['chan'].strip('#'), *row['time'].split()))
        else:
            row['log_url'] = ''

        say(formats[row['action']].format(context='first said that', **row).strip())
    else:
        say("Never!")
Exemplo n.º 13
0
def seen(inp, nick='', chan='', db=None, input=None):
    "seen <nick> -- Tell when a nickname was last in active in one of this bot's channels."

    if input.conn.nick.lower() == inp.lower():
        return "You need to get your eyes checked."

    if inp.lower() == nick.lower():
        return "Have you looked in a mirror lately?"

    if not re.match("^[A-Za-z0-9_|.-\]\[]*$", inp.lower()):
        return "I can't look up that name, its impossible to use!"

    if not db_ready:
        db_init(db)

    last_seen = db.execute(
        "select name, time, quote from seen_user where name"
        " like ? and chan = ?", (inp, chan)).fetchone()

    if last_seen:
        reltime = timesince.timesince(last_seen[1])
        if last_seen[0] != inp.lower():  # for glob matching
            inp = last_seen[0]
        return '%s was last seen %s ago saying: %s' % \
                    (inp, reltime, last_seen[2])
    else:
        return "I've never seen %s talking in this channel." % inp
Exemplo n.º 14
0
def reminder_thread(nick, chan, reminder, wait_time, creation_time, conn, bot):
    if float(wait_time) >= 1:
        # Handle the case where a reminder didn't spawn a thread before expiring
        time.sleep(float(wait_time))

    elapsed_time = int(time.time() - creation_time)
    remainder_seconds = elapsed_time % 60
    if elapsed_time < 60:
        creation_time_output = str(elapsed_time) + ' seconds'
    else:
        creation_time_output = timesince.timesince(creation_time)
        if remainder_seconds:
            # Prevent '1 minute & 0 seconds'
            creation_time_output += ' & ' + str(remainder_seconds) + ' seconds'

    conn.msg(
        chan, nick + ': ' + 'You set a reminder ' + str(creation_time_output) +
        ' ago: ' + reminder)

    # Cheat real bad and just reimplement core/db.get_db_connection
    filename = os.path.join(bot.persist_dir,
                            '%s.%s.db' % (conn.nick, conn.server_host))
    db = sqlite3.connect(filename, timeout=10)
    db.execute(
        'delete from reminders where nick=? and chan=? and creation_time=?',
        (nick, chan, creation_time))
    db.commit()
Exemplo n.º 15
0
def pre(inp):
    """pre <query> -- searches scene releases using orlydb.com"""

    try:
        h = http.get_html("http://orlydb.com/", q=inp)
    except http.HTTPError as e:
        return 'Unable to fetch results: {}'.format(e)

    results = h.xpath("//div[@id='releases']/div/span[@class='release']/..")

    if not results:
        return "No results found."

    result = results[0]

    date = result.xpath("span[@class='timestamp']/text()")[0]
    section = result.xpath("span[@class='section']//text()")[0]
    name = result.xpath("span[@class='release']/text()")[0]

    # parse date/time
    date = datetime.datetime.strptime(date, "%Y-%m-%d %H:%M:%S")
    date_string = date.strftime("%d %b %Y")
    since = timesince.timesince(date)

    size = result.xpath("span[@class='inforight']//text()")
    if size:
        size = ' - ' + size[0].split()[0]
    else:
        size = ''

    return '{} - {}{} - {} ({} ago)'.format(section, name, size, date_string, since)
Exemplo n.º 16
0
def showuptime(inp):
    "uptime -- shows how long I have been connected for"
    f = open("uptime", "r")
    uptime = f.read()
    f.close()
    uptime = timesince.timesince(float(uptime))
    return "I have been online for %s" % uptime
Exemplo n.º 17
0
def pre(inp):
    """pre <query> -- searches scene releases using orlydb.com"""

    try:
        h = http.get_html("http://orlydb.com/", q=inp)
    except http.HTTPError as e:
        return 'Unable to fetch results: {}'.format(e)

    results = h.xpath("//div[@id='releases']/div/span[@class='release']/..")

    if not results:
        return "No results found."

    result = results[0]

    date = result.xpath("span[@class='timestamp']/text()")[0]
    section = result.xpath("span[@class='section']//text()")[0]
    name = result.xpath("span[@class='release']/text()")[0]

    # parse date/time
    date = datetime.datetime.strptime(date, "%Y-%m-%d %H:%M:%S")
    date_string = date.strftime("%d %b %Y")
    since = timesince.timesince(date)

    size = result.xpath("span[@class='inforight']//text()")
    if size:
        size = ' - ' + size[0].split()[0]
    else:
        size = ''

    return '{} - {}{} - {} ({} ago)'.format(section, name, size, date_string, since)
Exemplo n.º 18
0
def seen(inp, nick='', chan='', db=None, input=None):
    ".seen <nick> -- Tell when a nickname was last in active in irc"

    inp = inp.lower()

    if input.conn.nick.lower() == inp:
        # user is looking for us, being a smartass
        return "You need to get your eyes checked."

    if inp == nick.lower():
        return "Have you looked in a mirror lately?"

    db_init(db)

    last_seen = db.execute("select name, time, quote from seen where"
                           " name = ? and chan = ?", (inp, chan)).fetchone()

    if last_seen:
        reltime = timesince.timesince(last_seen[1])
        if last_seen[0] != inp.lower():  # for glob matching
            inp = last_seen[0]
        if last_seen[2][0:1] == "\x01":
            return '%s was last seen %s ago: *%s %s*' % \
                (inp, reltime, inp, last_seen[2][8:-1])
        else:
            return '%s was last seen %s ago saying: %s' % \
                (inp, reltime, last_seen[2])
    else:
        return "I've never seen %s" % inp
Exemplo n.º 19
0
def seen(inp, nick='', chan='', db=None, input=None, conn=None, notice=None):
    "seen <nick> -- Tell when a nickname was last in active in one of this bot's channels."

    if input.conn.nick.lower() == inp.lower():
        phrase = datafiles.get_phrase(nick,insults,nick,conn,notice,chan)
        return phrase

    if inp.lower() == nick.lower():
        return phrase

    #if not re.match("^[A-Za-z0-9_|.\-\]\[]*$", inp.lower()):
    #    return "I can't look up that name, its impossible to use!"

    if not db_ready: db_init(db)

    last_seen = db.execute("select name, time, quote from seen where name like ? and chan = ?", (inp, chan)).fetchone()

    if last_seen:
        reltime = timesince.timesince(last_seen[1])
        if last_seen[0] != inp.lower():  # for glob matching
            inp = last_seen[0]
        if last_seen[2][0:1] == "\x01":
            return '{} was last seen {} ago: * {} {}'.format(inp, reltime, inp,
                                                             last_seen[2][8:-1])
        else:
            return '{} was last seen {} ago saying: {}'.format(inp, reltime, last_seen[2])
    else:
        return "I've never seen {} talking in this channel.".format(inp)
Exemplo n.º 20
0
def twitter_url(match, bot=None):
    # Find the tweet ID from the URL
    tweet_id = match.group(1)

    # Get the tweet using the tweepy API
    api = get_api(bot)
    if not api:
        return
    try:
        tweet = api.get_status(tweet_id)
        user = tweet.user
    except tweepy.error.TweepError:
        return

    # Format the return the text of the tweet
    text = " ".join(tweet.text.split())

    if user.verified:
        prefix = "\u2713"
    else:
        prefix = ""

    time = timesince.timesince(tweet.created_at, datetime.utcnow())

    return "{}@\x02{}\x02 ({}): {} ({} ago)".format(prefix, user.screen_name,
                                                    user.name, text, time)
Exemplo n.º 21
0
def requestinput(paraml,
                 input=None,
                 notice=None,
                 db=None,
                 bot=None,
                 nick=None,
                 conn=None):
    if 'showrequests' in input.msg.lower():
        return

    if not db_ready: db_init(db)

    requests = get_requests(db)

    if requests:
        user_from, message, time, chan = requests[0]
        reltime = timesince.timesince(time)

        reply = "{} sent a request {} ago from {}: {}".format(
            user_from, reltime, chan, message)
        if len(requests) > 1:
            reply += " (+%d more, %sshowtells to view)" % (
                len(requests) - 1, conn.conf["command_prefix"])

        if 'del' in inp:
            db.execute("delete from requests where user_from=? and message=?",
                       (user_from, message))
            db.commit()
        notice(reply)
Exemplo n.º 22
0
def format_reply(history):
    if not history:
        return

    last_nick, recent_time = history[0]
    last_time = timesince.timesince(recent_time)
    current_time = time.time()

    if (current_time - recent_time < minimum_time_lag):
        return

    if len(history) == 1:
        return "%s linked that %s ago. Pay attention, dumbass." % (last_nick, last_time)

    hour_span = math.ceil((time.time() - history[-1][1]) / 3600)
    hour_span = '%.0f hours' % hour_span if hour_span > 1 else 'hour'

    hlen = len(history)
    ordinal = ["once", "twice", "%d times" % hlen][min(hlen, 3) - 1]

    if len(dict(history)) == 1:
        last = "last linked %s ago" % last_time
    else:
        last = "last linked by %s %s ago" % (last_nick, last_time)

    return "that url has been posted %s in the past %s by %s (%s)." % (ordinal,
            hour_span, nicklist(history), last)
Exemplo n.º 23
0
def seen(inp, nick='', chan='', db=None, input=None, bot=None):
    "seen <nick> -- Tell when a nickname was last in active in one of this bot's channels."

    if input.conn.nick.lower() == inp.lower():
        return "You need to get your eyes checked."

    if inp.lower() == nick.lower():
        return "Have you looked in a mirror lately?"

    #if not re.match("^[A-Za-z0-9_|.\-\]\[]*$", inp.lower()):
    #    return "I can't look up that name, its impossible to use!"

    if not db_ready: db_init(db, bot)

    last_seen = db.execute("select name, time, quote from seen where name like ? and chan = ?", (inp, chan)).fetchone()

    if last_seen:
        reltime = timesince.timesince(last_seen[1])
        if last_seen[0] != inp.lower():  # for glob matching
            inp = last_seen[0]
        if last_seen[2][0:1] == "\x01":
            print 'notelse'
            return u'{} was last seen {} ago: * {} {}'.format(inp, reltime, inp,
                                                             last_seen[2][8:-1]).encode('utf-8')
        else:
            return u'{} was last seen {} ago saying: {}'.format(inp, reltime, last_seen[2]).encode('utf-8')
    else:
        return "I've never seen {} talking in this channel.".format(inp)
Exemplo n.º 24
0
def seen(inp, nick='', chan='', db=None, input=None, conn=None):
    """seen <nick> <channel> -- Tell when a nickname was last in active in one of this bot's channels."""

    if input.conn.nick.lower() == inp.lower():
        return "You need to get your eyes checked."

    if inp.lower() == nick.lower():
        return "Have you looked in a mirror lately?"

    if not re.match("^[A-Za-z0-9_|.\-\]\[]*$", inp.lower()):
        return "I can't look up that name, its impossible to use!"

    db_init(db, conn.name)

    last_seen = db.execute(
        "select name, time, quote from seen_user where name"
        " like ? and chan = ?", (inp, chan)).fetchone()

    if last_seen:
        reltime = timesince.timesince(last_seen[1])
        if last_seen[0] != inp.lower():  # for glob matching
            inp = last_seen[0]
        if last_seen[2][0:1] == "\x01":
            return '{} was last seen {} ago: * {} {}'.format(
                inp, reltime, inp, last_seen[2][8:-1])
        else:
            return '{} was last seen {} ago saying: {}'.format(
                inp, reltime, last_seen[2])
    else:
        return "I've never seen {} talking in this channel.".format(inp)
Exemplo n.º 25
0
def showtells(paraml, say='', nick='', chan='', conn=None, db=None):
    db_init(db)
    tells = get_tells(db, nick, chan)

    if tells:
        for tell in tells:
            if '#' in tell[2]:
                say("{nick}: Message from {}, {time} ago: {}".format(
                    nick=nick, time=timesince.timesince(tell[-1]), *tell))
            else:
                out = "PM from {}, {time} ago: {}".format(
                    time=timesince.timesince(tell[-1]), *tell)
                conn.send("PRIVMSG {} :{}".format(nick, out))
        db.execute(
            "delete from tell where user_to=lower(?) and (chan=lower(?)"
            " or chan not like '#%')", (nick, chan))
        db.commit()
Exemplo n.º 26
0
def getdelta(t):
    delta = timesince.timesince(t) + " ago"
    # Check if it's been over a month since we saw them:
    days = datetime.timedelta(seconds=(time.time() - t)).days
    # Consider hiding this is it's been fewer than some number of days?
    if days >= 0:
        t = int(t)
        dt = datetime.datetime.fromtimestamp(t)
        delta = delta + " (" + dt.__str__() + ")"
    
    return delta
Exemplo n.º 27
0
def last(inp, nick='', chan='', input=None, db=None, say=None):
    """.last <phrase> - Finds the last occurence of a phrase."""
    row = db.execute("select time, nick, msg, uts from log where msg like ? "
        "and uts < ? and chan = ? order by uts desc limit 1",
        (('%' + inp.strip() + '%'), (time.time() - 1), chan)).fetchone()
    if row:
        xtime, xnick, xmsg, xuts = row
        say("%s last said \"%s\" on %s (%s ago)" %
            (xnick, xmsg, xtime[:-7], timesince.timesince(xuts)))
    else:
        say("Never!")
Exemplo n.º 28
0
def getdelta(t):
    delta = timesince.timesince(t) + " ago"
    # Check if it's been over a month since we saw them:
    days = datetime.timedelta(seconds=(time.time() - t)).days
    # Consider hiding this is it's been fewer than some number of days?
    if days >= 0:
        t = int(t)
        dt = datetime.datetime.fromtimestamp(t)
        delta = delta + " (" + dt.__str__() + ")"

    return delta
Exemplo n.º 29
0
def reddit(inp):
    """reddit <subreddit> [n] -- Gets a random post from <subreddit>, or gets the [n]th post in the subreddit."""
    id_num = None

    if inp:
        # clean and split the input
        parts = inp.lower().strip().split()

        # find the requested post number (if any)
        if len(parts) > 1:
            url = base_url.format(parts[0].strip())
            try:
                id_num = int(parts[1]) - 1
            except ValueError:
                return "Invalid post number."
        else:
            url = base_url.format(parts[0].strip())
    else:
        url = "http://reddit.com/.json"

    try:
        data = http.get_json(url, user_agent=http.ua_chrome)
    except Exception as e:
        return "Error: " + str(e)
    data = data["data"]["children"]

    # get the requested/random post
    if id_num is not None:
        try:
            item = data[id_num]["data"]
        except IndexError:
            length = len(data)
            return "Invalid post number. Number must be between 1 and {}.".format(length)
    else:
        item = random.choice(data)["data"]

    item["title"] = formatting.truncate_str(item["title"], 50)
    item["link"] = short_url.format(item["id"])

    raw_time = datetime.fromtimestamp(int(item["created_utc"]))
    item["timesince"] = timesince.timesince(raw_time)

    if item["over_18"]:
        item["warning"] = " \x02NSFW\x02"
    else:
        item["warning"] = ""

    return (
        "\x02{title} : {subreddit}\x02 - posted by \x02{author}\x02"
        " {timesince} ago - {ups} upvotes, {downs} downvotes -"
        " {link}{warning}".format(**item)
    )
Exemplo n.º 30
0
def reddit(inp):
    """reddit <subreddit> [n] -- Gets a random post from <subreddit>, or gets the [n]th post in the subreddit."""
    id_num = None

    if inp:
        # clean and split the input
        parts = inp.lower().strip().split()

        # find the requested post number (if any)
        if len(parts) > 1:
            url = base_url.format(parts[0].strip())
            try:
                id_num = int(parts[1]) - 1
            except ValueError:
                return "Invalid post number."
        else:
            url = base_url.format(parts[0].strip())
    else:
        url = "http://reddit.com/.json"

    try:
        data = http.get_json(url, user_agent=http.ua_chrome)
    except Exception as e:
        return "Error: " + str(e)
    data = data["data"]["children"]

    # get the requested/random post
    if id_num:
        try:
            item = data[id_num]["data"]
        except IndexError:
            length = len(data)
            return "Invalid post number. Number must be between 1 and {}.".format(
                length)
    else:
        item = random.choice(data)["data"]

    item["title"] = text.truncate_str(item["title"], 50)
    item["link"] = short_url.format(item["id"])

    rawtime = datetime.fromtimestamp(int(item["created_utc"]))
    item["timesince"] = timesince.timesince(rawtime)

    if item["over_18"]:
        item["warning"] = " \x02NSFW\x02"
    else:
        item["warning"] = ""

    return u'\x02{title} : {subreddit}\x02 - posted by \x02{author}\x02' \
    ' {timesince} ago - {ups} upvotes, {downs} downvotes -' \
    ' {link}{warning}'.format(**item)
Exemplo n.º 31
0
def lastfm(script):
    if not api_key:
        script.character.send_chat("[lastfm] error: no api key set")

    user = script.character.name

    response = http.get_json(api_url, method="user.getrecenttracks",
                             api_key=api_key, user=user, limit=1)

    if 'error' in response:
        script.character.send_chat("[lastfm] Error: %s." % response["message"])

    if not "track" in response["recenttracks"] or len(response["recenttracks"]["track"]) == 0:
        script.character.send_chat('[lastfm] No recent tracks for user "%s" found.' % user)

    tracks = response["recenttracks"]["track"]

    if type(tracks) == list:
        # if the user is listening to something, the tracks entry is a list
        # the first item is the current track
        track = tracks[0]
        status = 'is listening to'
        ending = '.'
    elif type(tracks) == dict:
        # otherwise, they aren't listening to anything right now, and
        # the tracks entry is a dict representing the most recent track
        track = tracks
        status = 'last listened to'
        # lets see how long ago they listened to it
        time_listened = datetime.fromtimestamp(int(track["date"]["uts"]))
        time_since = timesince.timesince(time_listened)
        ending = ' (%s ago)' % time_since

    else:
        script.character.send_chat("[lastfm] error: could not parse track listing")

    title = track["name"]
    album = track["album"]["#text"]
    artist = track["artist"]["#text"]

    out = '%s %s "%s"' % (user, status, title)
    if artist:
        out += " by \x02%s\x0f" % artist
    if album:
        out += " from the album \x02%s\x0f" % album

    # append ending based on what type it was
    out += ending

    script.character.send_chat("[lastfm] " + out)
Exemplo n.º 32
0
def reddit(inp):
    """reddit <subreddit> [n] - Gets a random post from <subreddit>, or gets the [n]th post in the subreddit."""

    # clean and split the input
    parts = inp.lower().strip().split()
    id_num = None

    # find the requested post number (if any)
    if len(parts) > 1:
        inp = parts[0]
        try:
            id_num = int(parts[1]) - 1
        except ValueError:
            return "Invalid post number."

    try:
        data = http.get_json(base_url.format(inp.strip()))
    except Exception as e:
        return "Error: " + str(e)
    data = data["data"]["children"]

    try:
        # geit the requested/random post
        if id_num is not None:
            try:
                item = data[id_num]["data"]
            except IndexError:
                length = len(data)
                return ("Invalid post number. Number must " \
                    "be between 1 and {}.".format(length))
        else:
            item = random.choice(data)["data"]
    except:
        return "I couldn't find any data for \x02{}\x0F.".format(inp)

    item["title"] = text.truncate_str(item["title"], 100)
    item["link"] = short_url.format(item["id"])

    rawtime = datetime.fromtimestamp(int(item["created_utc"]))
    item["timesince"] = timesince.timesince(rawtime)

    if item["over_18"]:
        item["warning"] = " \x02NSFW\x02"
    else:
        item["warning"] = ""

    return u'{link}{warning} - \x02{title}\x02 - posted by' \
        ' \x02{author}\x02 {timesince} ago - {ups} upvotes,' \
        ' {downs} downvotes'.format(**item)
Exemplo n.º 33
0
def showtells(inp, say='', nick='', chan='', db=None):
    db_init(db)
    tells = get_tells(db, nick)

    if not tells:
        return
    for tell in tells:
        user_from, message, time, chan = tell
        past = timesince.timesince(time)
        say("%s: Message from %s, %s ago in %s: %s" %
            (nick, user_from, past, chan, message))  # notice(

    db.execute("delete from tell where user_to=lower(?)",
               (nick,))
    db.commit()
Exemplo n.º 34
0
def showtells(nick, notice, db, conn):
    """showtells -- View all pending tell messages (sent in a notice)."""

    tells = get_unread(db, conn.server, nick)

    if not tells:
        notice("You have no pending messages.")
        return

    for tell in tells:
        sender, message, time_sent = tell
        past = timesince.timesince(time_sent)
        notice("{} sent you a message {} ago: {}".format(sender, past, message))

    read_all_tells(db, conn.server, nick)
Exemplo n.º 35
0
Arquivo: msg.py Projeto: gbyers/skybot
def onJoinMsg(inp, input=None, db=None, pm=None, conn=None):
    db_init(db)
    m = getMsgs(db,input.nick)
    #if c > 0:
    #    notice("You have %s new messages. Type /msg %s |read to read them"%(str(c),conn.nick))
    if len(m) > 0:
        #if len(m) == 1: notice("You have %s new message."%len(m))
        #elif len(m) > 1: notice("You have %s new messages."%len(m))
        if len(m) > 0:
            for m in m:
                string = "Sent %s ago; From %s;"%(timesince.timesince(m[4]),m[2])
                pm(string+" "+m[3])
                #notice(m[3])
                db.execute("delete from msg where touser like (?)",(input.nick,))
                db.commit()
Exemplo n.º 36
0
def seen(inp, nick='', chan='', db=None, input=None):
    ",seen <nick> -- Tell when a nickname was last in active in irc"
    if input.conn.nick.lower() == inp.lower():
        return("I'm right here, need something?")
    if inp.lower() == nick.lower():
        return("Yes, that's your nick ...")
    db_init(db)
    last_seen = db.execute("select name, said, time, chan from seen where name=lower(?)", (inp,)).fetchone()
    if last_seen:
        reltime = timesince.timesince(last_seen[2])
        if last_seen[0] != inp.lower():  # for glob matching
            inp = last_seen[0]
        return('%s was last seen %s ago in %s saying: %s' % (inp, reltime, last_seen[3], last_seen[1].replace("\x01ACTION",'"'+inp+': ').replace("\x01",'"')))
    else:
        return("User not in database")
Exemplo n.º 37
0
def showtells(nick, notice, db, conn):
    """showtells -- View all pending tell messages (sent in a notice)."""

    tells = get_unread(db, conn.server, nick)

    if not tells:
        notice("You have no pending messages.")
        return

    for tell in tells:
        sender, message, time_sent = tell
        past = timesince.timesince(time_sent)
        notice("{} sent you a message {} ago: {}".format(
            sender, past, message))

    read_all_tells(db, conn.server, nick)
Exemplo n.º 38
0
def tellinput(input, notice, db, nick, conn):
    if 'showtells' in input.msg.lower():
        return

    tells = get_unread(db, conn.server, nick)

    if tells:
        user_from, message, time_sent = tells[0]
        reltime = timesince.timesince(time_sent)

        reply = "{} sent you a message {} ago: {}".format(user_from, reltime, message)
        if len(tells) > 1:
            reply += " (+{} more, {}showtells to view)".format(len(tells) - 1, conn.config["command_prefix"])

        read_tell(db, conn.server, nick, message)
        notice(reply)
Exemplo n.º 39
0
def showtells(inp, nick="", chan="", notice=None, db=None):
    "showtells -- View all pending tell messages (sent in a notice)."

    db_init(db)

    tells = get_tells(db, nick)

    if not tells:
        notice("You have no pending tells.")
        return

    for tell in tells:
        user_from, message, time, chan = tell
        past = timesince.timesince(time)
        notice("%s sent you a message %s ago from %s: %s" % (user_from, past, chan, message))

    db.execute("delete from tell where user_to=lower(?)", (nick,))
    db.commit()
Exemplo n.º 40
0
def showtells(inp, nick='', chan='', pm=None, db=None):
    ".showtells -- view all pending tell messages (sent in PM)."

    db_init(db)

    tells = get_tells(db, nick)

    if not tells:
        pm("You have no pending tells.")
        return

    for tell in tells:
        user_from, message, time, chan = tell
        past = timesince.timesince(time)
        pm("%s said %s ago in %s: %s" % (user_from, past, chan, message))

    db.execute("delete from tell where user_to=lower(?)", (nick, ))
    db.commit()
Exemplo n.º 41
0
def tellinput(input, notice, db, nick, conn):
    if 'showtells' in input.msg.lower():
        return

    tells = get_unread(db, conn.server, nick)

    if tells:
        user_from, message, time_sent = tells[0]
        reltime = timesince.timesince(time_sent)

        reply = "{} sent you a message {} ago: {}".format(
            user_from, reltime, message)
        if len(tells) > 1:
            reply += " (+{} more, {}showtells to view)".format(
                len(tells) - 1, conn.config["command_prefix"])

        read_tell(db, conn.server, nick, message)
        notice(reply)
Exemplo n.º 42
0
def showtells(inp, nick='', chan='', pm=None, db=None):
    ".showtells -- view all pending tell messages (sent in PM)."

    db_init(db)

    tells = get_tells(db, nick)

    if not tells:
        pm("You have no pending tells.")
        return

    for tell in tells:
        user_from, message, time, chan = tell
        past = timesince.timesince(time)
        pm("%s said %s ago in %s: %s" % (user_from, past, chan, message))

    db.execute("delete from tell where user_to=lower(?)",
               (nick,))
    db.commit()
Exemplo n.º 43
0
def seen(inp, nick='', chan='', db=None):
    ".seen <nick> -- Tell when a nickname was last in active in irc"

    if inp.lower() == nick.lower():
        return "Have you looked in a mirror lately?"

    db_init(db)

    last_seen = db.execute("select name, time, quote from seen where name"
                           " like ? and chan = ?", (inp, chan)).fetchone()

    if last_seen:
        reltime = timesince.timesince(last_seen[1])
        if last_seen[0] != inp.lower():  # for glob matching
            inp = last_seen[0]
        return '%s was last seen %s ago saying: %s' % \
                    (inp, reltime, last_seen[2])
    else:
        return "I've never seen %s" % inp
Exemplo n.º 44
0
def tellinput(paraml, input=None, notice=None, db=None, bot=None, nick=None, conn=None):
    if "showtells" in input.msg.lower():
        return

    db_init(db)

    tells = get_tells(db, nick)

    if tells:
        user_from, message, time, chan = tells[0]
        reltime = timesince.timesince(time)

        reply = "%s sent you a message %s ago from %s: %s" % (user_from, reltime, chan, message)
        if len(tells) > 1:
            reply += " (+%d more, %sshowtells to view)" % (len(tells) - 1, conn.conf["command_prefix"])

        db.execute("delete from tell where user_to=lower(?) and message=?", (nick, message))
        db.commit()
        notice(reply)
Exemplo n.º 45
0
def seen(inp, chan='', nick='', bot=None, db=None, say=None, input=None):
    """seen [-G] <nick> - Tell when a nickname was last in active in IRC. Flag -G to search all channels."""
    try:
        inp = inp.group(1)
    except:
        pass

    inp, _global = is_global(inp)

    if input.conn.nick.lower() == inp.lower():
        return "You need to get your eyes checked."
    if inp.lower() == nick.lower():
        return "Have you looked in a mirror lately?"

    if _global:
        row = db.execute("select uts, time, chan, nick, action, msg from logfts where logfts match ? order by cast(uts as decimal) desc limit 1",
            ('nick:^"{}" OR (action:"kick" AND msg:^"{}") OR (chan:"nick" AND msg:^"{}")'.format(inp, inp, inp),)).fetchone()
    else:
        row = db.execute("select uts, time, chan, nick, action, msg from logfts where logfts match ? order by cast(uts as decimal) desc limit 1",
            ('((chan:"{}" OR chan:"nick" OR chan:"quit") AND nick:^"{}") OR (chan:"{}" AND action:"kick" AND msg:^"{}") OR (chan:"nick" AND msg:^"{}")'.format(chan.strip('#'), inp, chan.strip('#'), inp, inp),)).fetchone()

    if row:
        row = dict(zip(['uts', 'time', 'chan', 'nick', 'action', 'msg'], row))

        row['date'] = row['time'].split(' ')[0]
        row['timesince'] = timesince.timesince(float(row['uts']))
        if bot.config.get("logviewer_url"):
            row['log_url'] = web.try_googl(bot.config["logviewer_url"].format(row['chan'].strip('#'), *row['time'].split()))
        else:
            row['log_url'] = ''

        if row['action'] == 'KICK':
            row['who'], row['msg'] = row['msg'].split(' ', 1)
            if inp.lower() != row['nick'].lower():
                row['action'] = 'KICKEE'

        if row['action'] == 'NICK':
            if inp.lower() != row['nick'].lower():
                row['action'] = 'NICKEE'

        say(formats[row['action']].format(context='was last seen', **row).strip())
    else:
        return "I've never seen {}".format(inp)
Exemplo n.º 46
0
def showtells(inp, nick='', chan='', notice=None, db=None):
    "showtells -- View all pending tell messages (sent in a notice)."

    db_init(db)

    tells = get_tells(db, nick)

    if not tells:
        notice("You have no pending tells.")
        return

    for tell in tells:
        user_from, message, time, chan = tell
        past = timesince.timesince(time)
        notice("%s sent you a message %s ago from %s: %s" %
               (user_from, past, chan, message))

    db.execute("delete from tell where user_to=lower(?)", (nick, ))
    db.commit()
Exemplo n.º 47
0
def tellinput(paraml, input=None, db=None, bot=None):
    if 'showtells' in input.msg.lower():
        return

    db_init(db)

    tells = get_tells(db, input.nick)

    if tells:
        user_from, message, time, chan = tells[0]
        reltime = timesince.timesince(time)

        reply = "%s said %s ago: %s" % (user_from, reltime, message)
        if len(tells) > 1:
            reply += " (+%d more, .showtells to view)" % (len(tells) - 1)

        db.execute("delete from tell where user_to=lower(?) and message=?",
                   (input.nick, message))
        db.commit()
        input.notice(reply)
Exemplo n.º 48
0
def requestinput(paraml, input=None, notice=None, db=None, bot=None, nick=None, conn=None):
    if 'showrequests' in input.msg.lower():
        return

    if not db_ready: db_init(db)

    requests = get_requests(db)

    if requests:
        user_from, message, time, chan = requests[0]
        reltime = timesince.timesince(time)

        reply = "{} sent a request {} ago from {}: {}".format(user_from, reltime, chan, message)
        if len(requests) > 1:
            reply += " (+%d more, %sshowtells to view)" % (len(requests) - 1, conn.conf["command_prefix"])

        if 'del' in inp:
            db.execute("delete from requests where user_from=? and message=?", (user_from, message))
            db.commit()
        notice(reply)
Exemplo n.º 49
0
def tellinput(paraml, input=None, db=None, bot=None):
    if 'showtells' in input.msg.lower():
        return

    db_init(db)

    tells = get_tells(db, input.nick)

    if tells:
        user_from, message, time, chan = tells[0]
        reltime = timesince.timesince(time)

        reply = "%s said %s ago: %s" % (user_from, reltime,
                                              message)
        if len(tells) > 1:
            reply += " (+%d more, .showtells to view)" % (len(tells) - 1)

        db.execute("delete from tell where user_to=lower(?) and message=?",
                     (input.nick, message))
        db.commit()
        input.notice(reply)
Exemplo n.º 50
0
def seen(inp, nick='', chan='', db=None, input=None, conn=None):
    """seen <nick> [channel] -- Tell when a nickname was last in active in one of this bot's channels."""

    args = inp.split()
    lookup_nick = args[0]
    if len(args) > 1:
        lookup_chan = args[1]
    else:
        lookup_chan = chan

    if input.conn.nick.lower() == lookup_nick.lower():
        return "You need to get your eyes checked."

    if lookup_nick.lower() == nick.lower():
        return "Have you looked in a mirror lately?"

    if any(c not in (string.ascii_letters + string.digits + "_-\[]{}^`|")
           for c in lookup_nick):
        return "I can't look up that name, its impossible to use!"

    db_init(db, conn.name)

    last_seen = db.execute(
        "SELECT name, time, quote FROM seen_user WHERE name"
        " like ? and chan = ?", (lookup_nick, lookup_chan)).fetchone()

    if last_seen:
        reltime = timesince.timesince(last_seen[1])
        if last_seen[0] != lookup_nick.lower():  # for glob matching
            lookup_nick = last_seen[0]
        if last_seen[2][0:1] == "\x01":
            return '{} was last seen {} ago: * {} {}'.format(
                lookup_nick, reltime, lookup_nick, last_seen[2][8:-1])
        else:
            return '{} was last seen {} ago saying: {}'.format(
                lookup_nick, reltime, last_seen[2])
    else:
        return "I've never seen {} talking in this channel.".format(
            lookup_nick)
Exemplo n.º 51
0
def format_reply(history):
    if not history:
        return

    last_nick, recent_time = history[0]
    last_time = timesince.timesince(recent_time)

    if len(history) == 1:
        return  #"%s linked that %s ago." % (last_nick, last_time)

    hour_span = math.ceil((time.time() - history[-1][1]) / 3600)
    hour_span = '%.0f hours' % hour_span if hour_span > 1 else 'hour'

    hlen = len(history)
    ordinal = ["once", "twice", "%d times" % hlen][min(hlen, 3) - 1]

    if len(dict(history)) == 1:
        last = "last linked %s ago" % last_time
    else:
        last = "last linked by %s %s ago" % (last_nick, last_time)

    return  #"that url has been posted %s in the past %s by %s (%s)." % (ordinal,
Exemplo n.º 52
0
def tellinput(inp, input=None, notice=None, db=None, nick=None, conn=None):
    if 'showtells' in input.msg.lower():
        return

    db_init(db, conn)

    tells = get_tells(db, nick)

    if tells:
        user_from, message, time, chan = tells[0]
        reltime = timesince.timesince(time)

        reply = "{} sent you a message {} ago from {}: {}".format(
            user_from, reltime, chan, message)
        if len(tells) > 1:
            reply += " (+{} more, {}showtells to view)".format(
                len(tells) - 1, conn.conf["command_prefix"])

        db.execute("delete from tell where user_to=lower(?) and message=?",
                   (nick, message))
        db.commit()
        notice(reply)
Exemplo n.º 53
0
def showrequests(inp, nick='', chan='', notice=None, db=None, bot=None):
    "showrequests [del nick/all] -- View all pending requests (sent in a notice)."
    gadmins = bot.config['admins']
    admins = []

    for admin in gadmins:
        admin = admin.split('@')
        admins.append(admin[0])
    admins = " ".join(admins)

    if nick not in admins:
        return
    else:
        if not db_ready: db_init(db)

        requests = get_requests(db)
        print requests

        if not requests:
            notice("You have no pending tells.")
            return

        for request in requests:
            user_from, message, time, chan = request
            past = timesince.timesince(time)
            notice("%s sent you a message %s ago from %s: %s" %
                   (user_from, past, chan, message))

        if 'del' in inp:
            inp = inp.split(" ")
            if inp[1] == 'all':
                db.execute("delete from requests where user_from=?",
                           (user_from, ))
                db.commit()
            else:
                db.execute("delete from requests where user_from=?",
                           (inp[1], ))
                db.commit()
Exemplo n.º 54
0
def seen(inp, nick='', chan='', db=None, input=None):
    ".seen <nick> -- Tell when a nickname was last in active in irc"

    if input.conn.nick.lower() == inp.lower():
        # user is looking for us, being a smartass
        input.notice("I'm right here, need something?")

    if inp.lower() == nick.lower():
        input.notice("Yes, that's your nick ...")

    db_init(db)

    last_seen = db.execute("select name, time, quote from seen where name"
                           " like ? and chan = ?", (inp, chan)).fetchone()

    if last_seen:
        reltime = timesince.timesince(last_seen[1])
        if last_seen[0] != inp.lower():  # for glob matching
            inp = last_seen[0]
        input.notice('%s was last seen %s ago saying: %s' % \
                    (inp, reltime, last_seen[2]))
    else:
        input.notice("User not in database")
Exemplo n.º 55
0
def reminder_thread(nick, chan, reminder, wait_time, creation_time, conn, bot):
    if float(wait_time) >= 1:
        # Handle the case where a reminder didn't spawn a thread before expiring
        time.sleep(float(wait_time))

    elapsed_time = int(time.time() - creation_time)
    remainder_seconds = elapsed_time % 60
    if elapsed_time < 60:
        creation_time_output = str(elapsed_time) + ' seconds'
    else:
        creation_time_output = timesince.timesince(creation_time)
        if remainder_seconds:
            # Prevent '1 minute & 0 seconds'
            creation_time_output += ' & ' + str(remainder_seconds) + ' seconds'

    conn.msg(chan, nick + ': ' + 'You set a reminder ' + str(creation_time_output) + ' ago: ' + reminder)

    # Cheat real bad and just reimplement core/db.get_db_connection
    filename = os.path.join(bot.persist_dir, '%s.%s.db' % (conn.nick, conn.server))
    db = sqlite3.connect(filename, timeout=10)
    db.execute('delete from reminders where nick=? and chan=? and creation_time=?',
               (nick, chan, creation_time))
    db.commit()
Exemplo n.º 56
0
def format_reply(history):
    if not history:
        return

    last_nick, recent_time = history[0]
    last_time = timesince.timesince(recent_time)

    if len(history) == 1:
       # return "%s linked that %s ago." % (last_nick, last_time)
	return "Pfff like I haven't seen that before!"

    hour_span = math.ceil((time.time() - history[-1][1]) / 3600)
    hour_span = '%.0f hours' % hour_span if hour_span > 1 else 'hour'

    hlen = len(history)
    ordinal = ["once", "twice", "%d times" % hlen][min(hlen, 3) - 1]

    if len(dict(history)) == 1:
        last = "last linked %s ago" % last_time
    else:
        last = "last linked by %s %s ago" % (last_nick, last_time)

    return "Jesus how many times are you guys gonna link that?!"
Exemplo n.º 57
0
def seen(inp, nick='', chan='', db=None, input=None):
    "seen <nick> -- Tell when a nickname was last on active in irc"

    if input.conn.nick == inp:
        return "You need to get your eyes checked."
    inp = inp.split(" ")[0]
    db_init(db)
    last_seen = db.execute(
        "select name, time, quote, chan, event from seen where name like (?) order by time desc",
        (inp.replace("*", "%"), )).fetchone()

    if last_seen:
        reltime = timesince.timesince(last_seen[1])
        if last_seen[0] != inp.lower():  # for glob matching
            inp = last_seen[0]
        if last_seen[4] == "privmsg":
            if last_seen[2][0:1] == "\x01":
                return '%s was last seen %s ago in %s: *%s %s*' % (
                    last_seen[0], reltime, last_seen[3], inp,
                    last_seen[2][8:-1])
            else:
                return '%s was last seen %s ago in %s saying: %s' % (
                    last_seen[0], reltime, last_seen[3], last_seen[2])
        if last_seen[4] == "join":
            return '%s was last seen %s ago joining %s' % (
                last_seen[0], reltime, last_seen[3])
        if last_seen[4] == "part":
            return '%s was last seen %s ago parting %s' % (
                last_seen[0], reltime, last_seen[3])
        if last_seen[4] == "quit":
            return '%s was last seen %s ago quitting (%s)' % (
                last_seen[0], reltime, last_seen[2])
        if last_seen[4] == "kick":
            return '%s was last seen %s ago getting kicked from %s' % (
                last_seen[0], reltime, last_seen[3])
    else:
        return "I've never seen %s" % inp
Exemplo n.º 58
0
def seen(inp, nick='', chan='', db=None, input=None):
    ".seen <nick> -- Tell when a nickname was last in active in irc"

    if input.conn.nick.lower() == inp.lower():
        # user is looking for us, being a smartass
        input.notice("I'm right here, need something?")

    if inp.lower() == nick.lower():
        input.notice("Yes, that's your nick ...")

    db_init(db)

    last_seen = db.execute(
        "select name, time, quote from seen where name"
        " like ? and chan = ?", (inp, chan)).fetchone()

    if last_seen:
        reltime = timesince.timesince(last_seen[1])
        if last_seen[0] != inp.lower():  # for glob matching
            inp = last_seen[0]
        input.notice('%s was last seen %s ago saying: %s' % \
                    (inp, reltime, last_seen[2]))
    else:
        input.notice("User not in database")
Exemplo n.º 59
0
def twitter(inp):
    "twitter <user>/<user> <n>/<id>/#<hashtag>/@<user> -- Gets last/<n>th " \
    "tweet from <user>/gets tweet <id>/Gets random tweet with #<hashtag>/" \
    "gets replied tweet from @<user>."

    def add_reply(reply_name, reply_id):
        if len(history) == history_max_size:
            history.pop()
        history.insert(0, (reply_name, reply_id))

    def find_reply(reply_name):
        for name, id in history:
            if name == reply_name:
                return id if id != -1 else name

    if inp[0] == '@':
        reply_inp = find_reply(inp[1:])
        if reply_inp == None:
            return 'No replies to %s found.' % inp
        inp = reply_inp

    url = 'http://api.twitter.com'
    getting_nth = False
    getting_id = False
    searching_hashtag = False

    time = 'status/created_at'
    text = 'status/text'
    retweeted_text = 'status/retweeted_status/text'
    retweeted_screen_name = 'status/retweeted_status/user/screen_name'
    reply_name = 'status/in_reply_to_screen_name'
    reply_id = 'status/in_reply_to_status_id'
    reply_user = '******'

    if re.match(r'^\d+$', inp):
        getting_id = True
        url += '/statuses/show/%s.xml' % inp
        screen_name = 'user/screen_name'
        time = 'created_at'
        text = 'text'
        reply_name = 'in_reply_to_screen_name'
        reply_id = 'in_reply_to_status_id'
        reply_user = '******'
    elif re.match(r'^\w{1,15}$', inp) or re.match(r'^\w{1,15}\s+\d+$', inp):
        getting_nth = True
        if inp.find(' ') == -1:
            name = inp
            num = 1
        else:
            name, num = inp.split()
        if int(num) > 3200:
            return 'error: only supports up to the 3200th tweet'
        url += ('/1/statuses/user_timeline.xml?include_rts=true&'
                'screen_name=%s&count=1&page=%s' % (name, num))
        screen_name = 'status/user/screen_name'
    elif re.match(r'^#\w+$', inp):
        url = 'http://search.twitter.com/search.atom?q=%23' + inp[1:]
        searching_hashtag = True
    else:
        return 'Error: Invalid request.'

    try:
        tweet = http.get_xml(url)
    except http.HTTPError as e:
        errors = {
            400: 'Bad request (ratelimited?)',
            401: 'Tweet is private',
            403: 'Tweet is private',
            404: 'Invalid user/id',
            500: 'Twitter is broken',
            502: 'Twitter is down ("getting upgraded")',
            503: 'Twitter is overloaded'
        }
        if e.code == 404:
            return 'error: invalid ' + ['username', 'tweet id'][getting_id]
        if e.code in errors:
            return 'Error: %s.' % errors[e.code]
        return 'Unknown Error: %s' % e.code
    except http.URLError as e:
        return 'Error: Request timed out.'

    if searching_hashtag:
        ns = '{http://www.w3.org/2005/Atom}'
        tweets = tweet.findall(ns + 'entry/' + ns + 'id')
        if not tweets:
            return 'Hashtag not found!'
        id = random.choice(tweets).text
        id = id[id.rfind(':') + 1:]
        return twitter(id)

    if getting_nth:
        if tweet.find('status') is None:
            return "User doesn't have that many tweets!"

    time = tweet.find(time)
    if time is None:
        return "User has no tweets!"

    reply_name = tweet.find(reply_name).text
    reply_id = tweet.find(reply_id).text
    reply_user = tweet.find(reply_user).text
    if reply_name is not None and (reply_id is not None
                                   or reply_user is not None):
        add_reply(reply_name, reply_id or -1)

    time_raw = strftime('%Y-%m-%d %H:%M:%S',
                        strptime(time.text, '%a %b %d %H:%M:%S +0000 %Y'))

    time_nice = timesince(parseDateTime(time_raw), datetime.utcnow())

    if tweet.find(retweeted_text) is not None:
        text = 'RT @%s:' % tweet.find(retweeted_screen_name).text
        text += unescape_xml(tweet.find(retweeted_text).text.replace('\n', ''))
    else:
        text = unescape_xml(tweet.find(text).text.replace('\n', ''))

    screen_name = tweet.find(screen_name).text

    return "\x02@%s\x02: %s (%s ago)" % (screen_name, text, time_nice)