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!

Bookmark the permalink. Follow any comments here with the RSS feed for this post. Post a comment or leave a trackback: Trackback URL.

35 Comments

  1. Posted July 22, 2009 at 9:40 pm | Permalink

    A big THANK YOU.

  2. Posted July 22, 2009 at 10:02 pm | Permalink

    Awesome! twitter4j is fantastic! And I didn’t even know about how one can import a file just by dragging a jar to the window!

  3. Posted August 31, 2009 at 11:47 am | Permalink

    One of these days I'll be able to figure this stuff out. I got lost at 'open up a new processing sketch'!

    That gets me every time; like html, I don't know how to start there either. Funny thing though I seem to understand most everything else I read here. Must be a stupid thingy with me.

    Excellent blog though, the stuff you've created looks really good.

  4. edu
    Posted September 22, 2009 at 9:52 am | Permalink

    I'm having problems with the constructor :S

    i put this on processing and this have to work but it hasn't >.<

    Twitter miTwitter;
    String user = "user";
    String pass = "pass";
    miTwitter = new Twitter(user, pass);

    I do the steps 1 & 2 whitout problems … but when i get to the step 3 in the fourth line it say that the constructor Twitter(string,string) is undefined

    Any suggestion please ??

    Thanks for the blog it's really great and it helps me a lot.

  5. undefined
    Posted September 24, 2009 at 5:03 am | Permalink

    Very good tutorial, but i'm having problems with the constructor :

    String user = "user";
    String pass = "pass";
    Twitter miTwitter = new Twitter(user, pass);

    This generates an error : "The constructor Twitter(String,String) is undefined"

    Any suggestion ??

    Thanks.

  6. alessandro
    Posted September 25, 2009 at 2:58 am | Permalink

    thank you so much!

  7. Cheddar
    Posted October 4, 2009 at 11:36 am | Permalink

    To let the error-message disappear, you have to open a new Processing pde-file. Then, just copy the code in it without doing anything. Before, you have to create a "twitter4j" directory in the "libraries" folder. In your new created twitter4j folder, you create another folder called "library". There, you put in the twitter4j.jar file (You have to rename it to "twitter4j.jar" first!). Then, click "Import library -> twitter4j" in your new processing file.

  8. JArryd
    Posted October 30, 2009 at 9:06 pm | Permalink

    I'm also having problems with the error: "The constructor Twitter(String,String) is undefined"

    I tried adding the twitter4j library as Cheddar suggested but it still gives the same problems.

    Anyone else have an idea whats going wrong?

    Thanx!

  9. Jonas
    Posted November 4, 2009 at 7:19 am | Permalink

    I'm having a peoblem when exporting it from processing. It keeps giving me an error java.lang.NoClassDefFoundError: twitter4j/TwitterException I'm not sure why since all of my code is in the right folders, or I hope it is. I've asked around and no ne can seem to find an a reason why. i was hoping you crossed by it and can help me find it.

  10. russell
    Posted November 9, 2009 at 5:55 am | Permalink

    i think you need to sign the applet. There is an easy step by step instruction at processing.org :

    http://processing.org/hacks/hacks:signapplet

    make sure you sign it for all of the jar files. however, once I got that error message out of the way, I am getting an Animation Thread exception in the twitter4j class for all of the functions it calls…so now im stuck again.

  11. russell
    Posted November 9, 2009 at 5:56 am | Permalink

    also, you're going to have to go into the index file generated and where it says "Archive" = 'yourfile.jar' you need to add the twitter jar

  12. davypaperboy
    Posted December 17, 2009 at 3:06 pm | Permalink

    I have tried putting in the code and installing twitter4j into processing. I'm getting no error messages, but always get a Couldn't connect: twitter4j.TwitterException: connect timed out
    Is this message an internet connection problem with processing (login on browser works fine) or a problem with connecting to twitter?

    Can someone help please?

  13. Posted January 14, 2010 at 3:14 am | Permalink

    Sorry for the late response. This is strange – have yo had any luck finding a fix?

  14. Faz
    Posted February 25, 2010 at 6:22 am | Permalink

    Hi @davypaperboy. I am facing the same problem. Have you found a solution?

    My Twitter-Java application is on 1.4.2_05, and the Exception thrown is as below:
    java.lang.NoClassDefFoundError: java/net/Proxy
    at twitter4j.http.HttpClient.getConnection(HttpClient.java:409)
    at twitter4j.http.HttpClient.request(HttpClient.java:243)
    at twitter4j.http.HttpClientWrapper.request(HttpClientWrapper.java:66)
    at twitter4j.http.HttpClientWrapper.post(HttpClientWrapper.java:97)
    at twitter4j.Twitter.updateStatus(Twitter.java:428)

  15. skwinte
    Posted May 1, 2010 at 1:43 pm | Permalink

    Dear Jer, when i run the sketch i get static page with number of tweets, how would you implement self-updating tweets?

    i used ur code. Thank you!

    Twitter myTwitter;

    PFont fontA;

    void setup() {

    size(800,600);

    background(0);

    smooth();

    fontA = loadFont(“Baskerville-48.vlw”);

    textFont(fontA, 20);

    textAlign(LEFT, CENTER);

    noLoop();

    noStroke();

    };

    void draw() {

    myTwitter = new Twitter(“yourTwitterUserName”, “yourTwitterPassword”);

    try {

    Query query = new Query(“jer”);

    query.setRpp(40);

    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);

    // println(msg);

    fill((127), (0), (0));

    colorMode(RGB,100,500,10, 255);

    text(msg, random(500), random(500),width/2, height/2);

    textAlign(CENTER);//posX = 100;

    //posY = 10;

    //text(msg,100*2 ,10+50 );

    };

    }

    catch (TwitterException te) {

    println("Couldn't connect: " + te);

    };

    };

  16. topy
    Posted June 30, 2010 at 1:57 pm | Permalink

    hey nice work man, though i need ur help in posting to twitter using javascript and xml, im a novice in this and will really appreciate if u can help me out, cheers

  17. Posted July 25, 2010 at 4:40 pm | Permalink

    I must admit I am one of the few people that do not have a face book account. I have a twitter account, but have only really started to understand how powerful it can be by reading articles like this – cheers

  18. Bheem
    Posted August 2, 2010 at 4:17 am | Permalink

    Thank you, this code is very helpful

  19. Posted August 4, 2010 at 4:22 pm | Permalink

    Any idea how to implement the new twitter streaming api ? It use json – and I would guess it wouldn't work like this script right ?

  20. Posted August 8, 2010 at 3:29 pm | Permalink

    if you check out Processing.org, that will explain everything you need to get going. You probably didn't realize that processing is an application to write and compile code, written in the Processing language. Once you have the application downloaded, opening the application automatically starts a new window which is called a Sketch. Sounds like you can handle the tougher parts :)

  21. meelo
    Posted August 14, 2010 at 10:45 pm | Permalink

    hello.. someone can u help me please????i got two questions which are:
    1) how to add our website link into the status in twitter using java programming???
    2) how to upload image into the status in twitter using java programming???

  22. Posted September 15, 2010 at 10:47 am | Permalink

    Great work! I did not expect this to be so easy. :)

  23. Posted October 18, 2010 at 6:33 am | Permalink

    hi skwinte,
    I have been looking at Jer's sketch and your own and was wondering if you ever worked out how to implement self-updating tweets?
    many thanks

  24. daniel
    Posted November 14, 2010 at 1:37 am | Permalink

    Thanks for this example! Please, could you give a brief example of limiting queries by date (using the "since" and "until" methods in twitter4j)? That would be a huge help, because I am struggling in this area.

    Thanks,
    Dan

  25. jobe
    Posted November 30, 2010 at 11:18 pm | Permalink

    Hi, I'm getting the same Animation thread exception:

    Exception in thread "Animation Thread" java.lang.NullPointerException
    at twitter4j.TwitterResponse.<init>(TwitterResponse.java:68)
    at twitter4j.QueryResult.<init>(QueryResult.java:57)
    at twitter4j.Twitter.search(Twitter.java:343)

    Any idea on how to fix it?

    thanks!

  26. Posted December 6, 2010 at 2:23 pm | Permalink

    lovely, thanks!

  27. januz
    Posted February 15, 2011 at 9:21 am | Permalink

    Nice! I'm definitively trying this out!

  28. Posted February 19, 2011 at 4:09 pm | Permalink

    I guess the current site is now: https://github.com/yusuke/twitter4j

  29. Zeb
    Posted March 18, 2011 at 9:00 am | Permalink

    Okay this might sound a little dumb but my first problem is that I don't which .jar file I need to use when downloading the new 2.2.0 version. Should I use the old version or is there a way to use this tutorial with this new version.

  30. danielpaluska
    Posted September 5, 2011 at 2:23 am | Permalink

    i cant get this to work either…

  31. moose
    Posted October 19, 2011 at 2:50 pm | Permalink

    I have the exact same problem. Is there a solution?

  32. qas
    Posted December 15, 2011 at 11:07 am | Permalink

    how can i display message on to a different box in processing…

  33. Kevin O'Connor
    Posted February 28, 2012 at 12:50 pm | Permalink

    How does this work now that the Twitter API requires Oauth?

    Thanks,

    Kevin

  34. blprnt
    Posted February 28, 2012 at 12:53 pm | Permalink

    http://blog.blprnt.com/blog/blprnt/updated-quick-

  35. Rebecca
    Posted November 23, 2012 at 4:59 pm | Permalink

    Thank you!!!
    I had problems with the twitter4j library before, I didn't know that I can add a jar just by dragging it into the sketch..
    Thank you, you mafe my evening! :)

10 Trackbacks

  1. [...] Quick Tutorial: Twitter & Processing | blprnt.blg Accessing information from the Twitter API with Processing is easy. 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. (tags: api java twitter library processing blprnt) [...]

  2. [...] Quick Tutorial: Twitter & Processing | blprnt.blg [...]

  3. By GoodMorning! | blprnt.blg on August 23, 2009 at 9:42 pm

    [...] 24 hours worth of good morning tweets. Querying the Twitter API is easy enough – I posted a simple tutorial about doing this with Processing and Twitter4J a couple of weeks ago. The issue with gathering this [...]

  4. By Pick Data to Analyze for Final « Mindy at ITP on November 18, 2009 at 9:22 pm

    [...] I found a tutorial that shows you how to work with the Twitter API and Processing. [...]

  5. [...] excellent and has some tutorials on how to achieve this kind of work – I have had a go at the basic Twitter setup so [...]

  6. [...] Or maybe some comparison between ITP students who tweet and the vending machine stock. I found a tutorial that shows you how to work with the Twitter API and Processing. For next week’s assignment, we’re supposed to plot locational data on a sphere. Since [...]

  7. By Agent-based Generative Patterns | christianmeinke.com on December 14, 2009 at 11:42 pm

    [...] various interfaces and input formats (i.e. sound, image-analysys and various data formats & sources) to create interactive structures not only producing decorative drawings, but creating generative [...]

  8. [...]  There's a tutorial on using twitter4j to access the regular REST API here http://blog.blprnt.com/blog/blpr…, although it hasn't been updated to use OAuth instead of basic auth.Given those two libraries [...]

  9. [...] mobility, I have to source the tweets in real time, it can be done easily with major help from this tutorial . So while I haven’t yet fully let go of the idea of curating the tweets since I still feel [...]

  10. [...] blink or reaction in a Processing sketch, and my conclusions are not 100% certain. However, I have found multiple blog posts/forum discussions that would lead me to believe that this is a possibility. I [...]

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*