Anon10W1z
Anon10W1z

Reputation: 167

Is there a better way to catch tweets using Twitter4J?

I tried using the StatusListener and TwitterStream way for a cleaner way to do this, but it seems not to catch all tweets from the users I want.

StatusListener statusListener = new StatusListener() {
    @Override
    public void onStatus(Status status) {
        //my code
    }
    //other requiredly-overriden methods
}
ConfigurationBuilder configurationBuilder = new ConfigurationBuilder();
configurationBuilder.setOAuthConsumerKey("XXXXX");
configurationBuilder.setOAuthConsumerSecret("XXXXXXX");
TwitterStream twitterStream = new TwitterStreamFactory(configurationBuilder.build()).getInstance(new AccessToken("XXXXX", "XXXXXXX"));
twitterStream.addListener(statusListener);
twitterStream.sample();

So I resorted to manually checking every 3 seconds whether a new tweet has been posted by the users I want to. This works perfectly, but seems unclean and hacky. Is there a better way?

Upvotes: 1

Views: 403

Answers (1)

FeanDoe
FeanDoe

Reputation: 1668

I don't fully understand. How are you trying to catch the tweets from the users that you are interested to?. If you were simply using the twitter stream and then checking if a tweet is from the user you want you could get tweets from different sources (and maybe losing some tweets if there are a lot).
If you want to follow some users you should use a filter, like this:

StatusListener statusListener = new StatusListener() {
    @Override
    public void onStatus(Status status) {
        //your code to manage the statuses
    }
    //other requiredly-overriden methods
}
ConfigurationBuilder configurationBuilder = new ConfigurationBuilder();
configurationBuilder.setOAuthConsumerKey("XXXXX");
configurationBuilder.setOAuthConsumerSecret("XXXXXXX");
TwitterStream twitterStream = new TwitterStreamFactory(configurationBuilder.build()).getInstance(new AccessToken("XXXXX", "XXXXXXX"));
twitterStream.addListener(statusListener);

//from here is different at your code

//you need to set up your user list, with their users id's!
long[] userslist = YOUR USER LIST;
//then you create a filter
FilterQuery filtre = new FilterQuery();
//and use that filter to follow the users that you want and to start the stream
filtre.follow(userslist);
twitterStream.filter(filtre);

With the filter you could follow up to 5000 different users and you will get what they tweet, when they are being retweeted and when they are being mentioned

Upvotes: 4

Related Questions