Automatically tweeting shared items in your Google Reader
Alright there are easier ways to do this using friendfeed etc but I wanted to write a Java program that reads my Google Reader shared items and post them to a twitter account. So here it is I wrote one using Rome to read google shared items atom feed and JTwitter (the Java library for the Twitter API) to write to Twitter.
Get Feeds:
public static java.util.List getFeedEntries() throws Exception
{
URL url = new URL("http://www.google.com/reader/public/atom/user%2F04396927642867243125%2Fstate%2Fcom.google%2Fbroadcast?"+Math.random());
XmlReader reader = null;
try {
reader = new XmlReader(url);
SyndFeed feed = new SyndFeedInput().build(reader);
return feed.getEntries();
} finally {
if (reader != null)
reader.close();
}
}
Get Tiny URL:
public static String getTinyUrl(String fullUrl) throws HttpException, IOException {
HttpClient httpclient = new HttpClient();
// Prepare a request object
HttpMethod method = new GetMethod("http://tinyurl.com/api-create.php");
method.setQueryString(new NameValuePair[]{new NameValuePair("url",fullUrl)});
httpclient.executeMethod(method);
String tinyUrl = method.getResponseBodyAsString();
method.releaseConnection();
return tinyUrl;
}
Update Status:
public static void UpdateStatus(String title, String link) throws Exception{
Twitter twitter;
try {
twitter = new Twitter(userName, password);
} catch (Exception e) {
System.out.println(e.getMessage());
return;
}
String tinylink = Reader.getTinyUrl(link);
java.util.List searchList1 = twitter.search(tinylink);
if(searchList1.size() ==0)
{
String StatusMessage = title +" "+tinylink;
List<String> messageList = twitter.splitMessage(StatusMessage);
for (int i = 0; i < messageList.size(); ++i) {
try {
twitter.updateStatus(messageList.get(i));
} catch (TwitterException e) {
System.out.println(e.getMessage());
return;
}
System.out.println("Message sent "+StatusMessage);
}
}
else
{
System.out.println("Skipping item already published "+title);
}
}
I tested tipping to techmeme using the above approach, i created a test account for this, you can checkout these test tweets at kiranpatch
Few things to note:
- Wanted to use Bitly URL shortner. Found bitlyj but it still seems to be work in progress
- If I maintained a database of my own, I could have eliminated the ugly message search before posting.
- Without the Math.random in the URL, the feed contents would not get refreshed.
- Tried to use Jakarta FeedParser but could not get it to read atom feeds.
One obvious thing here is the lack of real-timeness. There is lot of lag from the time the feed apears in google reader and the lag in my program to pickup the shared item and push it to twitter. Obviously this would be way cooler with pubsubhubbub or rsscloud
You can catch a better explanation of why this will be good at Anil Dash's blog where he defines this as PushButton Web


