Blog

26Jul/1212

Processing + Twitter by using Twitter4j

Processing Icon

***RESOLVED*** EDIT: I am updating the info of this post with this edit, since it got a bit outdated. First thanks to Codasign people for their awesome tutorial, you can take a look at it here. The current version of Twitter4j is 4.0.1 by the time I am writing this post. Below you can find the working tutorial for using Twitter4j within Processing.

Okay, I know that there are many, many tutorials on this subject and I know that it's fairly easy to actually get some output within 2 hours of googling and copy pasta - however, this is a long road for impatient users like me. Also, I have a project on my mind and I want to share my experience before I get it done.

First of all, please do check this tutorial before getting your hands dirty, because it is simply awesome. I just modified it slightly and I believe it's a wonderful starting point.

One issue about the tutorial for me was the authentication part of the twitter API. Below is my (slightly different yet more practical) version of the steps:

1. Visit https://dev.twitter.com/ and login with your twitter username and password
2. Click on the ‘Create an app’ button at the bottom right
3. Fill out the form that follows.
4. Once you’ve agreed to the developer terms, you’ll arrive at a page which shows the first two of the four things that we need: the Consumer key and the Consumer secret. Copy and paste these somewhere so you have them ready to access.

 4,5. Click on settings button. Scroll down to Application Type and select Read and Write. This is important because otherwise for posting a tweet, you'll need the rights to be able to Write. The code provided on the tutorial will NOT post a tweet to your account.

5. To get the other two values that we need, click on the button that says ‘Create my access token’. Copy and paste those two values (Access token and Access token secret) so that we have all four in the same place. These are pretty important so keep them handy, but don't share them with third parties.

So this was what you had to do with twitter authentication. Now we come to Twitter4j and Processing part. If you haven't done yet, please download Twitter4j and install it from here.

For installing, do the following:
1) Unzip the twitter4j-4.0.1.zip
2) Move the unzipped folder to Processing > libraries (This is by default inside Documents on Windows)
3) Rename the folder "twitter4j-4.0.1 " to "twitter4j401"
4) Place all contents of the "twitter4j401" folder into a folder called "library", which is inside the "twitter4j401" folder
5) Rename "twitter4j-core-4.0.1.jar" in the "library" folder to "twitter4j401.jar".  This was our final step and now shut down processing if it's still running and relaunch it. Voila!
Now you should have Twitter4j library ready to use in Processing. Open up a Processing sketch, and select Sketch-> Import Library... -> twitter4j401. If you got it all right, you'll see a bunch of import twitter4j... codes in your sketch. Excellent!

For a quick example (provided %99 by Jer from blog.blprnt.com), copy and paste the code below to your Processing sketch and hit Play button. I'm sure that'll help you get started. By the way, do not forget to replace the asterisks with your own tokens you got from https://dev.twitter.com.
 

import twitter4j.conf.*;
import twitter4j.internal.async.*;
import twitter4j.internal.org.json.*;
import twitter4j.internal.logging.*;
import twitter4j.json.*;
import twitter4j.internal.util.*;
import twitter4j.management.*;
import twitter4j.auth.*;
import twitter4j.api.*;
import twitter4j.util.*;
import twitter4j.internal.http.*;
import twitter4j.*;
import twitter4j.internal.json.*;
//Build an ArrayList to hold all of the words that we get from the imported tweets
ArrayList<String> words = new ArrayList();

void setup() {
//Set the size of the stage, and the background to black.
size(550,550);
background(0);
smooth();

//Credentials
ConfigurationBuilder cb = new ConfigurationBuilder();
cb.setOAuthConsumerKey("*****");
cb.setOAuthConsumerSecret("*****");
cb.setOAuthAccessToken("***-******");
cb.setOAuthAccessTokenSecret("*****");

//Now we’ll make the main Twitter object that we can use to do pretty much anything you can do on the twitter website
//– get status updates, run search queries, find follower information, etc. This Twitter object gets built by something
//called the TwitterFactory, which needs our configuration information that we set above:
Twitter twitter = new TwitterFactory(cb.build()).getInstance();
//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:
Query query = new Query("#audio");
query.setRpp(100);
//Try making the query request.
try {
QueryResult result = twitter.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);

//Break the tweet into words
String[] input = msg.split(" ");
for (int j = 0; j < input.length; j++) {
//Put each word into the words ArrayList
words.add(input[j]);
}
};
}
catch (TwitterException te) {
println("Couldn't connect: " + te);
};
}

void draw() {
//Draw a faint black rectangle over what is currently on the stage so it fades over time.
fill(0,1);
rect(0,0,width,height);

//Draw a word from the list of words that we've built
int i = (frameCount % words.size());
String word = words.get(i);

//Put it somewhere random on the stage, with a random size and colour
fill(255,random(50,150));
textSize(random(10,30));
text(word, random(width), random(height));
}

 

//End of code.

 

Please feel free to share any problems you confront with.

Share
Comments (12) Trackbacks (1)
  1. You’re the mother fucking man dude! You made my school project work. Props to you for a great tutorial.

  2. Hi,

    I have followed your steps. But I get this when I go to Run the sketch:

    “The function setRpp(int) does not exist.”

    Could you help me out at all please?

    • Hello Nathan,
      I have read your comment but I didn’t have time to check about this error yet. I checked for this problem online and my best guess is that you are experiencing version problems. This is rather an old code and probably uses older libraries than the current version. Again I am guessing that the libraries that are used in this code are either changed or moved. I would suggest you to check for the particular libraries’ recent versions. I will do that myself, too, as soon as I have some time.
      I wish I could be more helpful.
      Best,
      Deniz

    • I had to change ‘setRpp(int);’ to ‘count(int);’ to get it working.
      Nice tutorial Deniz. Do you know how to reply to a tweet? As it is I can send a tweet with someone’s handle, but I can’t reply to a tweet….any ideas?

  3. I have used this same code in a project which I found elsewhere online and then adapted slightly for my needs. I want to use this code for another project however I don’t want to split the tweets into word to display, I want to display say the last 50 tweets in their entirety either randomly or scrolling the screen.

  4. I’m getting an error message that reads, “Cannot find a class or type named ‘Tweet’.” Any thoughts?

    • Hey Lee,
      Now that the versions have changed, I get the same error, too. Also as Martin mentioned, the ‘setRpp(int);’ is also faulty.
      The best idea would be to visit the reference page (http://twitter4j.org/en/code-examples.html) and spend some experimenting time with that information.
      I’ll do the same soon.
      Best,
      Deniz

      • Thanks for responding so promptly! I’ll look through the resource you pointed me towards. Let me know if you figure out a solution.

        • Hello! Have you found a solution for the Tweet class?
          Thanks!!

          Bárbara

          • Hello Bárbara,

            I know it has been quite a while since this problem first showed up, but I am working on two different projects at the moment and I cannot spend any time to find my way around this in near future – mainly because I have limited experience with Java. I believe someone who has experience with Java can enlighten us regarding this matter.
            Also, I downloaded Processing v1.5.1 to see how it works, but then I figured I also have to download the older version of Twitter4j and do the configurations accordingly, and then I gave up.
            If you find anything, do tell us!

  5. I finally figured out that you would need to use:
    Status t=(Status)tweets.get(i);
    instead of:
    Tweet t = (Tweet) tweets.get(i);
    Pheww….


Leave a comment