Twitter and Java

From CompSciWiki
Jump to: navigation, search

Extra Lab: jTwitter

In this lab, we'll learn how to use a simple API wrapper for twitter to write Java programs to play with twitter.


Step 0: Register for Twitter

If you don't have a twitter account, you can sign up easily here. You can always delete this account later.

Step 1: Ensure you are running the latest version of JDK

Before running your lab, make sure you are running JDK 1.6.0 or later. Some of the libraries we will need use things only available in 1.6. Use the links on the main COMP 1010 website to get the latest JDK. If you are using a mac, then double check the version you are using. You will not be able to install JDK 1.6 on 32-bit macs(i.e., old intel macs).

Step 2: Download jar Files

For this code, we will need three jar files:

Save all three of these files on your hard drive.

Step 3: Make jTwitter accessible to your code

In eclipse, make the jar file accessible to your code:

  1. create a new Java project (File -> New -> Java Project).
  2. select the project, then click on Project-> Properties).
  3. click on "Java Build Path" in the left-hand pane, then click on the "Libraries" tab.
  4. click on "Add External JARs..." to add the jar file to the project.
  5. select the jtwitter.jar file you downloaded.

Repeat this process for all three jar files you downloaded. After this, the jtwitter.jar and all its contents should be accessible to your code.

In netbeans, use the following steps:

  1. Make your project as usual (File > New Project >Java Application >Next> Fill in Program name >Finish)
  2. Click File > Project Properties ("YourProgramName") If it doesn't say the right name, right-click on the coffee cup icon under the Projects from on the left-hand side and click "Set as Main Project"
  3. Go to Libraries (on the left)
  4. Click "Add JAR/Folder" and select the three .jar files (you can select them all at once) jtwitter.jar, signpost-core-1.2.1.1.jar commons-codec-1.3.jar
  5. Click OK and you now have access to the API

In other IDEs, a similar technique to add JAR files should be available

If you are using textpad, then you need to extract the jar file in the directory you want to work in. In Windows, do the following:

  1. go to the directory you want to write you program in, and move the jTwitter.jar file to that directory.
  2. open a command prompt and go to the same directory.
  3. at the command prompt extract the jar file with the command jar xf jtwitter.jar.
  4. if Windows complains about jar not being a recognized program, then you need to type the entire path of the jar command. Typically this is something like C:\Program Files\Java\jdk<some_number>\bin\jar.exe.

After this, the directory winterwell should have been created. In other operating systems (mac OS, linux), the same instructions work, and your OS should properly know where the jar command is.

Step 4: Start coding

In order to access the jTwitter methods, add the following import line with the rest of your imports:

import winterwell.jtwitter.*;

The hardest part of using jTwitter is the OAuth Key/Secret that you need to provide the application for authorization. We've registered a COMP 1010 app and have the key and secret. They will be provided for you at your lab (in a real application, you would register your own app

import winterwell.jtwitter.*;
import javax.swing.*;

public class tryjTwitter {
  
  public static void main (String[] args) {
     final String oaKey = "will be given at lab";
     final String oaSecret = "will be given at lab";
     String pin;
    
     // all the authorization material.
     OAuthSignpostClient client = new OAuthSignpostClient(oaKey,oaSecret,"oob");
     Twitter tw = new Twitter("yourTwitterUserName",client);
     client.authorizeDesktop();
     pin = JOptionPane.showInputDialog("Please enter the pin here:");
     client.setAuthorizationCode(pin);

     // the part that we actually care about:
     tw.setStatus("hello twitter world.");
  }
}

In this example, the string "yourTwitterUserName" is your actual user name that you use to log in to twitter (as a String, so put it in quotes). You don't have any place in the code to enter your password: this is all handled by twitter during the authorizeDesktop method call.

This method is a little clunky, but it should work: the authorizeDesktop method should launch your browser, and then it will provide you with a pin number, which you paste in your JOptionPane input dialog box. After this program finishes, "hello twitter world." should be your status.

Step 5: Add user interaction

To make your code more robust, you could ask the user to input (using JOptionPane, for instance):

  1. their username (to replace the hardcoded "yourTwitterUserName").
  2. their tweet.

So for instance, instead of the line:

     tw.setStatus("hello twitter world.");

You could write

String userTweet;
userTweet = JOptionPane.showInputDialog("Enter your tweet");

// if the user hit cancel, then the userInput will be null.
if (userTweet != null) {
  tw.setStatus(userTweet);
} else {
  System.out.println("You hit cancel.");
}

Step 6: Don't wreck it for everyone

The previous program (hopefully) works: it posts the string "hello twitter world" to your twitter account as a tweet. So please, please, don't abuse this. Do not write code like

for (int i = 0; i < 1000; i++) {
  myTwitter.setStatus("this is automated tweet number " + i);
}

That might well get you 1000 tweets on your account. But it might also get your account suspended. It might also get our application key (the long string provided to you) suspended, and wreck things for everyone. So please don't automate large volumes of tweets.


Step 7: Other routines in jTwitter

Setting your status is not the only thing you can accomplish with jTwitter. Other methods of the class Twitter that you may find useful are:

  • public Twitter.Status getStatus (String userName): Returns the current status of the twitter with user name userName. The method returns an object of type Twitter.Status, but this can be printed directly like it were a String:
 
System.out.println(myTwitter.getStatus("shitmydadsays"));

You don't need to be following the user to get the status. If no String parameter is passed, the status returned is your own.

  • public Twitter.User follow(String userName): follow the twitter account with user name userName. Returns an object of type Twitter.User which can be used to internally represent the user, but can also be

discarded.

  • public Twitter.User breakFriendship(String userName): stop following userName
  • public java.util.List<Twitter.User> getFriendsTimeline (): return the last 20 tweets from friends you follow. They are returned as a list. Example (uses Java 5 for loops):
ArrayList<Twitter.Status> tweets = (ArrayList<Twitter.Status>) myT.getFriendsTimeline();
for (Twitter.Status x : tweets) {
  System.out.println(x.getUser() + " says " + x);
}

Notice that this requires casting the result of the method call to an ArrayList if you want the result to be stored in a variable of that type.

  • Searching is similar. Use the method public java.util.List<Twitter.User> search (String searchTerm) which returns the latest tweets matching your search term. They are returned as a list. Example (uses Java 5 for loops):
ArrayList<Twitter.Status> tweets = (ArrayList<Twitter.Status>) myT.search("what you want to search for");
for (Twitter.Status x : tweets) {
  System.out.println(x.getUser() + " says " + x);
}

The full list of API calls is available here on the jTwitter website.