Beispiel #1
0
def weather(message_data, bot):
    db.execute("create table if not exists weather(nick primary key, loc)")
    loc = message_data["parsed"]
    if loc == "":
        row = db.execute("select loc from weather where nick=:nick", {"nick": message_data["nick"]}).fetchone()
        if not row:
            return 'Type in a location ¬_¬'
        loc = row[0]
    else:
        db.execute("insert or replace into weather(nick, loc) values (:nick, :loc)", {"nick": message_data["nick"], "loc": loc})
        db.commit()
    try:
        result = urllib2.urlopen('http://api.wunderground.com/api/91ef6bb1dc828118/conditions/q/' + loc + '.xml')
    except urllib2.URLError:
        return "Error getting weather data"
    try:
        weather = ElementTree.fromstring(result.read())
    except ElementTree.ParseError:
        return "Error getting weather data"
    current_observation = weather.find('current_observation')
    if current_observation is None:
        return "Error getting weather data"
    display_location = current_observation.find('display_location')
    string = display_location.find('full').text + ': '
    string = string + current_observation.find('weather').text + ', '
    string = string + current_observation.find('temperature_string').text + ', '
    string = string + current_observation.find('relative_humidity').text + ', Wind is blowing '
    string = string + current_observation.find('wind_string').text.replace('F','f', 1) + '.'
    return string
Beispiel #2
0
def get_tell(message_data, bot):
    db.execute("create table if not exists tells(nick_to, nick_from, message, time, channel)")
    row = db.execute("select nick_to, nick_from, message, time, channel from tells where nick_to=:nick_to", {"nick_to": message_data["nick"].lower()}).fetchone()
    if row:
        bot.irc.privmsg(message_data["nick"], row[1] + " said " + str(datetime.timedelta(seconds=(time.time() - row[3]))) + " ago in " + row[4] + " the following: " + row[2])
        db.execute("delete from tells where nick_to=:nick_to and nick_from=:nick_from and message=:message and time=:time and channel=:channel", {"nick_to": row[0], "nick_from": row[1], "message": row[2], "time": row[3], "channel": row[4]})
        db.commit()
Beispiel #3
0
def set_tell(message_data, bot):
    db.execute("create table if not exists tells(nick_to, nick_from, message, time, channel)")
    components = message_data["parsed"].split(" ", 1)
    if len(components) == 1:
        return 'You need to enter a message'
    db.execute("insert into tells (nick_to, nick_from, message, time, channel) values (:nick_to, :nick_from, :message, :time, :channel)", {"nick_to": components[0].lower(), "nick_from": message_data["nick"], "message": components[1], "time": time.time(), "channel": message_data["channel"]})
    db.commit()
    return "I'll pass that along."
Beispiel #4
0
def weather(message_data, bot):
    db.execute("create table if not exists weather(nick primary key, loc)")
    loc = message_data["parsed"]
    if loc == "":
        row = db.execute("select loc from weather where nick=:nick", {
            "nick": message_data["nick"]
        }).fetchone()
        if not row:
            return 'Type in a location ¬_¬'
        loc = row[0]
    else:
        db.execute(
            "insert or replace into weather(nick, loc) values (:nick, :loc)", {
                "nick": message_data["nick"],
                "loc": loc
            })
        db.commit()
    try:
        result = urllib2.urlopen(
            'http://api.wunderground.com/api/91ef6bb1dc828118/conditions/q/' +
            quote_plus(loc) + '.xml')
    except urllib2.URLError:
        return "Error getting weather data"
    try:
        weather = ElementTree.fromstring(result.read())
    except ElementTree.ParseError:
        return "Error getting weather data"
    current_observation = weather.find('current_observation')
    results = weather.find('results')
    if current_observation is not None:
        display_location = current_observation.find('display_location')
        string = display_location.find('full').text + ': '
        string += current_observation.find('weather').text + ', '
        string += current_observation.find('temperature_string').text + ', '
        string += current_observation.find(
            'relative_humidity').text + ', Wind is blowing '
        string += current_observation.find('wind_string').text.replace(
            'F', 'f', 1) + '.'
    elif results is not None:
        string = "Found the following cities/locations, please specify: "
        for r in results:
            string += "[ " + r.find('name').text + ', ' + r.find(
                'city').text + ', '
            state = r.find('state')
            if state.text is not None:
                string += state.text + ', '
            string += r.find('country_name').text + "(" + r.find(
                'country').text + ") ] "
    else:
        string = "City/location not found"
    return string
Beispiel #5
0
def seeninput(message_data, bot):
    # This could be improved but it doesn't matter:
    db.execute(
        "create table if not exists seen(name text, time integer, quote text, chan text, primary key(name, chan))"
    )
    db.execute(
        "replace into seen(name, time, quote, chan) values (:name, :time, :quote, :chan)",
        {
            "name": message_data["nick"],
            "time": int(time.time()),
            "quote": message_data["message"],
            "chan": message_data['channel']
        })
    db.commit()
    pass
Beispiel #6
0
def set_tell(message_data, bot):
    db.execute(
        "create table if not exists tells(nick_to, nick_from, message, time, channel)"
    )
    components = message_data["parsed"].split(" ", 1)
    if len(components) == 1:
        return 'You need to enter a message'
    db.execute(
        "insert into tells (nick_to, nick_from, message, time, channel) values (:nick_to, :nick_from, :message, :time, :channel)",
        {
            "nick_to": components[0].lower(),
            "nick_from": message_data["nick"],
            "message": components[1],
            "time": time.time(),
            "channel": message_data["channel"]
        })
    db.commit()
    return "I'll pass that along."
Beispiel #7
0
def quote(message_data, bot):
    db.execute("create table if not exists quote(sender text, quote text, time integer)")
    if message_data["parsed"][:4] == "add ":
        db.execute(
            "insert into quote(sender, quote, time) values (:sender, :quote, :time)",
            {"sender": message_data["nick"], "quote": message_data["parsed"][4:], "time": int(time.time())},
        )
        db.commit()
        return "Quote added."
    elif message_data["parsed"][:7] == "search ":
        quotes = db.execute(
            "select sender, quote, time from quote where quote like :quote order by random()",
            {"quote": "%" + message_data["parsed"][7:] + "%"},
        ).fetchall()
        if len(quotes) == 0:
            return "Nothing found."
        row = quotes[0]
        return "Found " + str(len(quotes)) + " quotes: (" + row[0] + ") " + row[1]
    else:
        return "Unknown command."
Beispiel #8
0
def weather(message_data, bot):
    db.execute("create table if not exists weather(nick primary key, loc)")
    loc = message_data["parsed"]
    if loc == "":
        row = db.execute("select loc from weather where nick=:nick", {"nick": message_data["nick"]}).fetchone()
        if not row:
            return 'Type in a location ¬_¬'
        loc = row[0]
    else:
        db.execute("insert or replace into weather(nick, loc) values (:nick, :loc)", {"nick": message_data["nick"], "loc": loc})
        db.commit()
    try:
        result = urllib2.urlopen('http://api.wunderground.com/api/91ef6bb1dc828118/conditions/q/' + quote_plus(loc) + '.xml')
    except urllib2.URLError:
        return "Error getting weather data"
    try:
        weather = ElementTree.fromstring(result.read())
    except ElementTree.ParseError:
        return "Error getting weather data"
    current_observation = weather.find('current_observation')
    results = weather.find('results')
    if current_observation is not None:
        display_location = current_observation.find('display_location')
        string = display_location.find('full').text + ': '
        string += current_observation.find('weather').text + ', '
        string += current_observation.find('temperature_string').text + ', '
        string += current_observation.find('relative_humidity').text + ', Wind is blowing '
        string += current_observation.find('wind_string').text.replace('F','f', 1) + '.'
    elif results is not None:
        string = "Found the following cities/locations, please specify: "
        for r in results:
            string += "[ " + r.find('name').text + ', ' + r.find('city').text + ', '
            state = r.find('state')
            if state.text is not None:
                string += state.text + ', '
            string += r.find('country_name').text + "(" + r.find('country').text + ") ] "
    else:
        string = "City/location not found"
    return string
Beispiel #9
0
def get_tell(message_data, bot):
    db.execute(
        "create table if not exists tells(nick_to, nick_from, message, time, channel)"
    )
    row = db.execute(
        "select nick_to, nick_from, message, time, channel from tells where nick_to=:nick_to",
        {
            "nick_to": message_data["nick"].lower()
        }).fetchone()
    if row:
        bot.irc.privmsg(
            message_data["nick"], row[1] + " said " +
            str(datetime.timedelta(seconds=(time.time() - row[3]))) +
            " ago in " + row[4] + " the following: " + row[2])
        db.execute(
            "delete from tells where nick_to=:nick_to and nick_from=:nick_from and message=:message and time=:time and channel=:channel",
            {
                "nick_to": row[0],
                "nick_from": row[1],
                "message": row[2],
                "time": row[3],
                "channel": row[4]
            })
        db.commit()
Beispiel #10
0
def seen(message_data, bot):
    searchname = message_data['parsed'].strip()
    chan = message_data['channel']

    if searchname.lower() == bot.nickname.lower(): # user is looking for us, being a smartass
        return "You need to get your eyes checked."

    if searchname.lower() == message_data['nick'].lower():
        return "Have you looked in a mirror lately?"

    last_seen = db.execute("select name, time, quote from seen where name like ? and chan = ?", (searchname, chan)).fetchone()
    
    if last_seen:
        reltime = getdelta(last_seen[1])
        if last_seen[0] != searchname.lower():  # for glob matching
            searchname = last_seen[0]
        return '%s was last seen %s saying: %s' % \
                    (searchname, reltime, last_seen[2])
    else:
        return "I've never seen %s" % searchname
Beispiel #11
0
def seen(message_data, bot):
    searchname = message_data['parsed'].strip()
    chan = message_data['channel']

    if searchname.lower() == bot.nickname.lower(
    ):  # user is looking for us, being a smartass
        return "You need to get your eyes checked."

    if searchname.lower() == message_data['nick'].lower():
        return "Have you looked in a mirror lately?"

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

    if last_seen:
        reltime = getdelta(last_seen[1])
        if last_seen[0] != searchname.lower():  # for glob matching
            searchname = last_seen[0]
        return '%s was last seen %s saying: %s' % \
                    (searchname, reltime, last_seen[2])
    else:
        return "I've never seen %s" % searchname
Beispiel #12
0
def db_init(db):
    db.execute("create table if not exists urlhistory"
               "(chan, url, nick, time)")
    db.commit()
Beispiel #13
0
def db_init(db):
    db.execute("create table if not exists urlhistory"
                 "(chan, url, nick, time)")
    db.commit()
Beispiel #14
0
def insert_history(db, chan, url, nick):
    now = time.time()
    db.execute(
        "insert into urlhistory(chan, url, nick, time) "
        "values(?,?,?,?)", (chan, url, nick, time.time()))
    db.commit()
Beispiel #15
0
def get_history(db, chan, url):
    db.execute("delete from urlhistory where time < ?",
               (time.time() - expiration_period, ))
    return db.execute(
        "select nick, time from urlhistory where "
        "chan=? and url=? order by time desc", (chan, url)).fetchall()
Beispiel #16
0
def seeninput(message_data, bot):
    # This could be improved but it doesn't matter:
    db.execute("create table if not exists seen(name text, time integer, quote text, chan text, primary key(name, chan))")
    db.execute("replace into seen(name, time, quote, chan) values (:name, :time, :quote, :chan)", {"name": message_data["nick"], "time": int(time.time()), "quote": message_data["message"], "chan": message_data['channel']})
    db.commit()
    pass
Beispiel #17
0
def get_history(db, chan, url):
    db.execute("delete from urlhistory where time < ?",
                 (time.time() - expiration_period,))
    return db.execute("select nick, time from urlhistory where "
            "chan=? and url=? order by time desc", (chan, url)).fetchall()
Beispiel #18
0
def insert_history(db, chan, url, nick):
    now = time.time()
    db.execute("insert into urlhistory(chan, url, nick, time) "
                 "values(?,?,?,?)", (chan, url, nick, time.time()))
    db.commit()
Beispiel #19
0
def quote(message_data, bot):
    global LastSearch, LastResults, LastNum

    db.execute(
        "create table if not exists quote(sender text, quote text, time integer)"
    )
    if message_data["parsed"][:4] == "add ":
        db.execute(
            "insert into quote(sender, quote, time) values (:sender, :quote, :time)",
            {
                "sender": message_data["nick"],
                "quote": message_data["parsed"][4:],
                "time": int(time.time())
            })
        db.commit()
        # Clear out all caches;
        LastSearch = {}
        LastResults = {}
        LastNum = {}
        return "Quote added."
    elif message_data["parsed"][:7] == "search ":

        # Seperate this data by channel;
        chan = message_data['channel']

        searchstring = message_data["parsed"]
        splitstring = searchstring.split()
        # If there are more than 3 parts, we are supplying a number we want to use perhaps, try to convert it to a number
        # If it succeeds, pop it from the search query
        num = 0
        if len(splitstring) >= 3:
            try:
                num = int(splitstring[-1])
                if num != 0:
                    # Valid number detected, remove this number:
                    splitstring.pop()
                    searchstring = " ".join(splitstring)
            except ValueError:
                num = 0
                pass

        # Check to see if this is the same as the last thing we searched so we can skip the DB pull:
        quotes = None
        IsReallyNext = False
        if chan in LastSearch:
            if searchstring == LastSearch[chan]:
                quotes = LastResults[chan]
                # Also sometimes this is really just someone doing the same search over and over to hear the next quote, so pretend to be next:
                IsReallyNext = True

        # If the list was not cached, do a DB pull:
        if quotes == None:
            quotes = db.execute(
                "select sender, quote, time from quote where quote like :quote order by time ASC",
                {
                    "quote": "%" + searchstring[7:] + "%"
                }).fetchall()

        # If results is now empty, don't update global dicts:
        total = len(quotes)
        if total == 0:
            return "Nothing found."

        # update cache dicts:
        LastSearch[chan] = searchstring
        LastResults[chan] = quotes

        # If num is out of range, select from the last value if we're really a 'next' command, or select randomly from range 0 - total
        if num <= 0 or num > total:
            if (IsReallyNext):
                num = ((LastNum[chan] + 1) % total)
            else:
                num = random.randrange(0, total)
        else:
            # Otherwise substract one from supplied digit due to 0 indexing etc
            num -= 1

        # Update the cached value for this:
        LastNum[chan] = num

        # Select that quote row, and provied to formatting function
        row = quotes[num]
        return retformat(num, total, row)

    elif message_data["parsed"][:4] == "next":
        chan = message_data['channel']

        splitstring = message_data["parsed"].split()
        # If there are more than 2 parts, we are supplying a number we want to use probably
        num = 0
        if len(splitstring) >= 2:
            try:
                num = int(splitstring[-1])
            except ValueError:
                num = 0
                pass

        if not (chan in LastResults):
            return "No stored query. Try search instead!"
        quotes = LastResults[chan]

        total = len(quotes)
        if total == 0:
            return "No stored query. Try search instead!"

        # If num is out of range, recover last request and add 1 mod total:
        if num <= 0 or num > total:
            num = (LastNum[chan] + 1) % total
        else:
            # Otherwise substract one from supplied digit due to 0 indexing etc
            num -= 1

        LastNum[chan] = num

        row = quotes[num]
        return retformat(num, total, row)
    else:
        return "Use quote followed by 'add', 'search ...', 'search  ... #', 'next' or 'next #'!"
Beispiel #20
0
def quote(message_data, bot):
    global LastSearch, LastResults, LastNum

    db.execute("create table if not exists quote(sender text, quote text, time integer)")
    if message_data["parsed"][:4] == "add ":
        db.execute("insert into quote(sender, quote, time) values (:sender, :quote, :time)", {"sender": message_data["nick"], "quote": message_data["parsed"][4:], "time": int(time.time())})
        db.commit()
        # Clear out all caches;
        LastSearch = {}
        LastResults = {}
        LastNum = {}
        return "Quote added."
    elif message_data["parsed"][:7] == "search ":

        # Seperate this data by channel;
        chan = message_data['channel']

        searchstring = message_data["parsed"]
        splitstring = searchstring.split()
        # If there are more than 3 parts, we are supplying a number we want to use perhaps, try to convert it to a number
        # If it succeeds, pop it from the search query
        num = 0
        if len(splitstring) >= 3:
            try:
                num = int(splitstring[-1])
                if num != 0:
                    # Valid number detected, remove this number:
                    splitstring.pop()
                    searchstring = " ".join(splitstring)
            except ValueError:
                num = 0
                pass

        # Check to see if this is the same as the last thing we searched so we can skip the DB pull:
        quotes = None
        IsReallyNext = False
        if chan in LastSearch:
            if searchstring == LastSearch[chan]:
                quotes = LastResults[chan]
                # Also sometimes this is really just someone doing the same search over and over to hear the next quote, so pretend to be next:
                IsReallyNext = True

        # If the list was not cached, do a DB pull:
        if quotes == None:
            quotes = db.execute("select sender, quote, time from quote where quote like :quote order by time ASC", {"quote": "%" + searchstring[7:] + "%"}).fetchall()

        # If results is now empty, don't update global dicts:
        total = len(quotes)
        if total == 0:
            return "Nothing found."

        # update cache dicts:
        LastSearch[chan] = searchstring
        LastResults[chan] = quotes
        
        # If num is out of range, select from the last value if we're really a 'next' command, or select randomly from range 0 - total
        if num <= 0 or num > total:
            if (IsReallyNext):
                num = ((LastNum[chan] + 1) % total)
            else: num = random.randrange(0,total) 
        else:
            # Otherwise substract one from supplied digit due to 0 indexing etc
            num -= 1

        # Update the cached value for this:
        LastNum[chan] = num
        
        # Select that quote row, and provied to formatting function
        row = quotes[num]
        return retformat(num,total,row)

    elif message_data["parsed"][:4] == "next":
        chan = message_data['channel']

        splitstring = message_data["parsed"].split()
        # If there are more than 2 parts, we are supplying a number we want to use probably
        num = 0
        if len(splitstring) >= 2:
            try:
                num = int(splitstring[-1])
            except ValueError:
                num = 0
                pass

        if not(chan in LastResults):
            return "No stored query. Try search instead!"
        quotes = LastResults[chan]

        total = len(quotes)
        if total == 0:
            return "No stored query. Try search instead!"

        # If num is out of range, recover last request and add 1 mod total:
        if num <= 0 or num > total:
            num = (LastNum[chan] + 1) % total
        else:
            # Otherwise substract one from supplied digit due to 0 indexing etc
            num -= 1

        LastNum[chan] = num

        row = quotes[num]
        return retformat(num,total,row)
    else:
        return "Use quote followed by 'add', 'search ...', 'search  ... #', 'next' or 'next #'!"