Pages

Friday, August 15, 2008

My first Twitter hack - Traffic alerts

View Comments

2008-08-14_1437Last week, a fellow Twitterer, Jorge Bauermeister, created an account on Twitter called elTapon (the traffic jam, in Spanish). The idea is for local Puerto Ricans to send a message to that account and Jorge would re-post the message. That way locals have a way to have real-time traffic information.

Twitter Bot

There are already hundreds if not thousands of Twitter bots out there. And I knew that Twitter had an API I could use to tackle this. Thus, I figured it would be a good idea to put on my hacker hat and create a Twitter Bot that simply reposts the messages that it gets and adds everyone that follows it as a friend (so it can receive direct messages). I mean, how hard can this be, right ? Remember, I still have a day job!

Turns out that it wasn't hard at all. Total labor time: 3 hours! (thank goodness that the baby is sleeping more now ). Given Twitter's popularity, I figured that someone must've created a Java wrapper for this. 1-2 Google searches led me to JTwitter, a Java wrapper for the Twitter JSON API's. Unlike some Java libraries that I've downloaded in the past, this one was very well documented and easy to use.

Once I found the Java wrapper, I launched Eclipse on my Mac and got to work.

The Code

To show the simplicity of this, I thought I would share the code here with you. Hopefully, you can also take this code and create your own hacks/mashups...

First we initialize the Java wrapper:

twit = new Twitter(this.username, this.password);

Now, we get the replies (messages sent to the bot)

replies = twit.getReplies();

Finally, we iterate through the replies, check that we haven't already posted it (in a previous run), and then post the update to our timeline:

// Loop over replies first
int repliesLength = replies.size();
for (int i=repliesLength-1; i >= 0; i--)
{
Message replyMsg = replies.get(i);
if (replyMsg.getId() > lastReplyProcessed)
{
String toUpdate = replyMsg.getText();
// remove my username from the text
if ( toUpdate.startsWith("@" + username))
{
toUpdate = toUpdate.substring(replyUser.length());
toUpdate = toUpdate.trim();
}if ( canPostMessage(toUpdate) ) { System.out.println(" Re-posting reply: " + i); twit.updateStatus(toUpdate); lastReplyProcessed = replyMsg.getId(); } } }

Now, I, of course, have simplified the code a bit, but I just wanted to show you the core of the code. Some of the missing pieces are error handling, thread creation, etc. But check this out...if we count from the top, it's ~20 lines of code to get something going!!! Beautiful! Simple! Love it!

Hope this sample code helps you on your own Mashups/Hacks.

The Result

If you live in the island, you'll want to follow @eltapon for real-time information on traffic chaos here!

Note: The link to download JTwitter doesn't work for me at this time. Not sure if the site was taken down for some reason...

blog comments powered by Disqus