3

I'm trying to make a sketch that gets the last 100 tweets from a specific user's twitter timeline. I'm using Twitter4j and the sketch works fine but I've learned that Twitter4J by default limits the timeline results to 20.

I've seen this page to learn about getting more than 100 when using Queries, but it seems to be working differently when trying to get a specific user's timeline. How to retrieve more than 100 results using Twitter4j

Thanks for looking!

Here is my sketch:

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.*;


ConfigurationBuilder cb = new ConfigurationBuilder();

cb.setOAuthConsumerKey("XXXXXX");
cb.setOAuthConsumerSecret("XXXXXX");
cb.setOAuthAccessToken("XXXXXX");
cb.setOAuthAccessTokenSecret("XXXXXX");

java.util.List statuses = null;

Twitter twitter = new TwitterFactory(cb.build()).getInstance();

String userName ="XXXXXX";
int numTweets = 100;
String[] twArray = new String[numTweets];



  try {
    statuses = twitter.getUserTimeline(userName);
  }
  catch(TwitterException e) {
  }

  for (int i=0; i<statuses.size(); i++) {
    Status status = (Status)statuses.get(i);

    //println(status.getUser().getName() + ": " + status.getText());
    twArray[i] = status.getUser().getName() + ": " + status.getText();

  }


println(twArray);
4

2 回答 2

6

我知道这个问题很老,但是公认的答案并不是最好的解决方案,下面是解决这个问题的更优雅的一段代码。

...

Paging p = new Paging();
p.setCount(100);
return twitter.getUserTimeline("screenName",p);
于 2015-10-29T13:04:29.643 回答
3

这样的事情怎么样?

Paging pg = new Paging();
String userName = "uzr";
void setup() {

  ConfigurationBuilder cb = new ConfigurationBuilder();
  cb.setOAuthConsumerKey("xxxx");
  cb.setOAuthConsumerSecret("xxxx");
  cb.setOAuthAccessToken("xxxx");
  cb.setOAuthAccessTokenSecret("xxxx");

  Twitter twitter = new TwitterFactory(cb.build()).getInstance();
  int numberOfTweets = 100;
  long lastID = Long.MAX_VALUE;
  ArrayList<Status> tweets = new ArrayList<Status>();
  while (tweets.size () < numberOfTweets) {
    try {
      tweets.addAll(twitter.getUserTimeline(userName,pg));
      println("Gathered " + tweets.size() + " tweets");
      for (Status t: tweets) 
        if(t.getId() < lastID) lastID = t.getId();
    }
    catch (TwitterException te) {
      println("Couldn't connect: " + te);
    }; 
    pg.setMaxId(lastID-1);
  }
}
于 2013-10-07T16:34:55.933 回答