Wednesday, July 25, 2012

Twitter Updating

Revised version of the code I originally wrote about here. The main difference is that I've included a counter so it doesn't post more than two tweets every time it is run (and since it only runs once an hour, this shouldn't make it too antisocial even when it hasn't run for a while and there are a lot of items in the RSS feed).
#!/usr/bin/python

import tweepy
import feedparser
import urllib
import urllib2

url = "http://www2.le.ac.uk/departments/engineering/news-and-events/blog/RSS"

oauth_file = open("access_token.txt", "r")
oauth_token = oauth_file.readline().rstrip()
oauth_token_secret = oauth_file.readline().rstrip()

consumer_file = open("consumer_keys.txt", "r")
consumer_key = consumer_file.readline().rstrip()
consumer_secret = consumer_file.readline().rstrip()

bitly_file = open("bitly.txt", "r")
bitly_username = bitly_file.readline().rstrip()
bitly_apikey = bitly_file.readline().rstrip()

bitly_base = "http://api.bit.ly/v3/shorten?"
bitly_data = {
    "login" : bitly_username,
    "apiKey" : bitly_apikey,
    "format" : "txt",
    "longUrl" : ""
    }

already_done = []
done_file = open("done.txt", "r")
for line in done_file:
    already_done.append(line.rstrip())
done_file.close()

auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(oauth_token, oauth_token_secret)

api = tweepy.API(auth)
feed = feedparser.parse(url)

count = 0
for item in feed["items"]:
    url   = item["link"]
    title = item["title"]
    if url not in already_done and count < 2:
        bitly_data["longUrl"] = url
        to_shorten = bitly_base + urllib.urlencode(bitly_data)
        result = urllib2.urlopen(to_shorten).read()
        api.update_status(title + " : " + result)
        already_done.append(url)
        count = count + 1

done_file = open("done.txt", "w")
for url in already_done:
    done_file.write(url + "\n")
done_file.close()

No comments:

Post a Comment