I am using the Twitter4j library in Processing to retrieve tweets. I have added a timer to my application so that it collects tweets at appropriate intervals without hitting the Twitter API too many times. However, I am having trouble implementing the Since_Id parameter in order to step forward (instead of backwards as I am now) through the timeline of tweets. How do I keep track of the MAX_ID so that value is fed into the next interval when the timer tells my application to run again.
Timer timer;
import java.util.List;
void setup() {
timer = new Timer(30000);
timer.start();
goTwitter();
}
void draw(){
if (timer.isFinished()){
goTwitter();
timer.start();
}
}
void goTwitter(){
ConfigurationBuilder cb = new ConfigurationBuilder();
cb.setOAuthConsumerKey("");
cb.setOAuthConsumerSecret("");
cb.setOAuthAccessToken("");
cb.setOAuthAccessTokenSecret("");
Twitter twitter = new TwitterFactory(cb.build()).getInstance();
Query query = new Query("#processing");
int numberOfTweets = 300;
long lastID = Long.MAX_VALUE;
ArrayList<Status> tweets = new ArrayList<Status>();
while (tweets.size () < numberOfTweets) {
if (numberOfTweets - tweets.size() > 100)
query.setCount(100);
else
query.setCount(numberOfTweets - tweets.size());
try {
QueryResult result = twitter.search(query);
tweets.addAll(result.getTweets());
println("Gathered " + tweets.size() + " tweets");
for (Status t: tweets)
if(t.getId() < lastID) lastID = t.getId();
}
catch (TwitterException te) {
println("Couldn't connect: " + te);
};
query.setMaxId(lastID-1);
}
for (int i = 0; i < tweets.size(); i++) {
Status t = (Status) tweets.get(i);
GeoLocation loc = t.getGeoLocation();
String user = t.getUser().getScreenName();
String msg = t.getText();
String time = "";
if (loc!=null) {
Double lat = t.getGeoLocation().getLatitude();
Double lon = t.getGeoLocation().getLongitude();
println(i + " USER: " + user + " wrote: " + msg + " located at " + lat + ", " + lon);
}
}
println("lastID= " + lastID);
}
class Timer {
int savedTime;
int totalTime;
Timer (int tempTotalTime) {
totalTime = tempTotalTime;
}
void start(){
savedTime = millis();
}
boolean isFinished() {
int passedTime = millis() - savedTime;
if (passedTime > totalTime){
return true;
} else {
return false;
}
}
}
You can just take the line
long lastID = Long.MAX_VALUE;
and move it right above
void setup() {
like this:
long lastID = Long.MAX_VALUE;
void setup() {
essentially making it a variable that can be accessed by every method in your Processing sketch, a kind of "global variable". Also, if you want it to restart every time after it has reached the number of tweets you should to change the else clause in the while loop and make it like this
else {
query.setCount(numberOfTweets - tweets.size());
long lastID = Long.MAX_VALUE;
}