Tag Archives: Tutorial

Quick Tutorial: Twitter & Processing

Accessing information from the Twitter API with Processing is easy. A few people have sent me e-mails asking how it all works, so I thought I’d write a very quick tutorial to get everyone up on their feet.

We don’t need to know too much about how the Twitter API functions, because someone has put together a very useful Java library to do all of the dirty work for us. It’s called twitter4j, and you can download it here. Once you have it downloaded, we can get started.

1. Open up a new Processing sketch.
2. Import the twitter4j library – you do this by simply dragging the twitter4j-2.0.8.jar file onto your sketch window. If you want to check, you should now see this file in your sketch folder, inside of a new ‘code’ directory.
3. We’ll put the guts of this example into the setup enclosure, but you could wrap it into a function or build a simple Class around it if you’d like:

Twitter myTwitter;

void setup() {
  myTwitter = new Twitter("yourTwitterUserName", "yourTwitterPassword");
};

void draw() {
  
};

4. Now that we have a Twitter object, we want to build a query to search via the Twitter API for a specific term or phrase. This is code that will not always work – sometimes the Twitter API might be down, or our search might not return any results, or we might not be connected to the internet. The Twitter object in twitter4j handles those types of conditions by throwing back an exception to us; we need to have a try/catch structure ready to deal with that if it happens:

Twitter myTwitter;

void setup() {
  myTwitter = new Twitter("yourTwitterUserName", "yourTwitterPassword");
  try {
    
    Query query = new Query("sandwich");
    QueryResult result = myTwitter.search(query);    

  }
  catch (TwitterException te) {
    println("Couldn't connect: " + te);
  };
};
void draw() {
  
};

5. This code is working – but we haven’t done anything with the results. Here, we’ll set the results per page parameter for the query to 100 to get the last 100 results with the term ‘sandwich’ and spit those results into the output panel:

Twitter myTwitter;

void setup() {
  myTwitter = new Twitter("yourTwitterUserName", "yourTwitterPassword");
  try {
    
    Query query = new Query("sandwich");
    query.setRpp(100);
    QueryResult result = myTwitter.search(query);
    
    ArrayList tweets = (ArrayList) result.getTweets();
    
    for (int i = 0; i < tweets.size(); i++) {
      Tweet t = (Tweet) tweets.get(i);
      String user = t.getFromUser();
      String msg = t.getText();
      Date d = t.getCreatedAt();
      println("Tweet by " + user + " at " + d + ": " + msg);
    };
    
  }
  catch (TwitterException te) {
    println("Couldn't connect: " + te);
  };
};

void draw() {
  
};

That’s it! This example is very simple, but it’s the bare bones of what you need build a project which connects Twitter through Processing. Good luck!