Twitter Monitor

From Unallocated Space
Jump to navigation Jump to search

This script sits in its own screen session and checks twitter to see if anyone has tweeted at Unallocated. If it finds any tweets, it posts it to the irc channel.

Code:

!/usr/bin/python
import tweepy
import sys
import settings
import time
import os

def debug_print(text):
    """Print text if debugging mode is on"""
    if settings.debug:
        print text


def save_id(statefile,id):
    """Save last status ID to a file"""
    last_id = get_last_id(statefile)

    if last_id < id:
        debug_print('Saving new ID %d to %s' % (id,statefile))
        f = open(statefile,'w')
        f.write(str(id)) # no trailing newline
        f.close()
    else:
        debug_print('Received smaller ID, not saving. Old: %d, New: %s' % (
            last_id, id))


def get_last_id(statefile):
    """Retrieve last status ID from a file"""

    debug_print('Getting last ID from %s' % (statefile,))
    try:
        f = open(statefile,'r')
        id = int(f.read())
        f.close()
    except IOError:
        debug_print('IOError raised, returning zero (0)')
        return 0
    debug_print('Got %d' % (id,))
    return id

def load_lists(force=False):
    """Load ignore and filtered word lists"""
    debug_print('Loading ignore list')
    global IGNORE_LIST
    IGNORE_LIST = [
        line.lower().strip() for line in open(settings.ignore_list) ]

    debug_print('Loading filtered word list')
    global FILTER_WORDS
    FILTER_WORDS = [
        line.lower().strip() for line in open(settings.filtered_word_list) ]

def main():
        #auth = tweepy.OAuthHandler(My_consumer_key, My_consumer_secret)
        #auth.set_access_token(My_access_token_key, My_access_token_secret)
        auth = tweepy.OAuthHandler(settings.consumer_key,settings.consumer_secret)
        auth.set_access_token(settings.access_token_key,settings.access_token_secret)
        api = tweepy.API(auth)
        while True:
                last_id = get_last_id(settings.last_id_file)
                try:
                        replies = api.mentions_timeline()
                except Exception, e:
                        print e
                        exit(1)
                replies.reverse()
                #print replies          
                for reply in replies:
#                       print reply.id
                        if reply.id > last_id:
                                print reply.text
                                try:
#                                       reply=reply.replace("'",'')
#                                       reply=reply.replace('"','')
#                                       reply=reply.replace('$','')
#                                       reply=reply.replace('`','')
                                
                                        # Don't post to irc if the tweet is from an ignored user
#                                       if reply.user.screen_name.lower() in IGNORE_LIST:
#                                               continue

                                        # Don't post to irc if the tweet contains a filtered word
#                                       for word in normalized_tweet.split():
#                                               if word.lower().strip() in FILTER_WORDS:
#                                                       continue
            
                                        #print reply
                                        #Out=open('/uas/irc/irc','a')
                                        #Out.write( 'New Twitter Alert: @'+reply.author.screen_name+ ' said: '+reply.text+'\n')
                                        os.system('echo "New Twitter Alert: @'+reply.author.screen_name+ ' said: '+reply.text+'" > /opt/uas/irc/irc')
                                except Exception, e:
                                        print 'e %s' % e
                                        print repr(e)
                                else:
                                        save_id(settings.last_id_file,reply.id)
                                        
                print('Exiting cleanly, going to sleep at '+time.asctime(time.localtime( time.time())))
                time.sleep(90)
                
if __name__ == '__main__':
    try:
        main()
    except KeyboardInterrupt:
        quit()