Implementing xkcd.com/1031 for Twitter live Stream

Posted By Hoyt Summers Pittman

If you don’t regularly read xkcd, please start now.

telnet www.sagaoftherealms.net 2211

The above command will log you into a server I am running. It is running a filter of Twitter looking for posts containing “keyboard” and replacing that word with “leopard”. (See www.xkcd.com/1031 if you don’t get the joke) This was surprisingly easy to write using the twitter4j library and Java 7’s new Asynchronous Socket Channels. It was also fast enough to handle at least 100 concurrent listeners when I was doing local testing.

For purposes of this post I will focus only on the Twitter4j integration.

Twitter4j uses StatusListener objects to consume StatusStreams. This is where I break up the message and replace my words.


StatusListener listener = new StatusListener() {

@Override
public void onStatus(Status status) {
String tweet = status.getText();
tweet = tweet.toLowerCase();
int index = tweet.indexOf("keyboard");
tweet = status.getText();
tweet = tweet.subSequence(0, index) + "leopard" + tweet.subSequence(index + 8, tweet.length());

queue.transfer("@" + status.getUser().getScreenName() + " - " + tweet);

}

public void onDeletionNotice(StatusDeletionNotice statusDeletionNotice) {
System.out.println("Got a status deletion notice id:" + statusDeletionNotice.getStatusId());
}

public void onTrackLimitationNotice(int numberOfLimitedStatuses) {
System.out.println("Got track limitation notice:" + numberOfLimitedStatuses);
}

public void onScrubGeo(long userId, long upToStatusId) {
System.out.println("Got scrub_geo event userId:" + userId + " upToStatusId:" + upToStatusId);
}

public void onException(Exception ex) {
ex.printStackTrace();
}
};

Now we configure Twitter4j to consume the stream.


ConfigurationBuilder cb = new ConfigurationBuilder();
cb.setDebugEnabled(true).setUser("username").setPassword("password");

long[] ids = {};
String[] tags = {"keyboard"};

FilterQuery query = new FilterQuery(0, ids, tags);

TwitterStream twitterStream = new TwitterStreamFactory(cb.build()).getInstance();

twitterStream.addListener(listener);
StatusStream stream = twitterStream.getFilterStream(query);

while (true) {
stream.next(listener);
}

The code should be rather self explanatory. FilterQuery creates a query which is submitted by Twitter4J to instruct Twitter to stream back tweets containing “keyboard”. I create a stream using my credentials and then loop to process each event. None of these are particularly exciting, and this code should be called in a main function or some background thread because it will block as written.

Mar 20th, 2012

One Comment to 'Implementing xkcd.com/1031 for Twitter live Stream'

Subscribe to comments with RSS or TrackBack to 'Implementing xkcd.com/1031 for Twitter live Stream'.

  1. Hoyt Summers Pittman said,

    Apparently, the stream will sometimes close for no reason.

:: Trackbacks/Pingbacks ::

No Trackbacks/Pingbacks

Leave a Reply