Skip to content

Instantly share code, notes, and snippets.

@davidaparicio
Created August 26, 2016 13:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save davidaparicio/5ecf75ffd786a755ba03922a87955eb9 to your computer and use it in GitHub Desktop.
Save davidaparicio/5ecf75ffd786a755ba03922a87955eb9 to your computer and use it in GitHub Desktop.
TwitterAPI search with Twitter4j
import twitter4j.*;
import twitter4j.conf.ConfigurationBuilder;
public class TwitterBot {
private final static int TWEETS_IN_PAGE = 100;
public static void main(String[] args) {
//Read the twitter4j.properties
ConfigurationBuilder cb = new ConfigurationBuilder();
try {
// The factory instance is re-useable and thread safe.
Twitter twitter = new TwitterFactory(cb.build()).getInstance();
// users represented by access tokens can make 180 requests/queries per 15 minutes.
// application-only auth, an app can make 450 queries/requests per 15 minutes.
// https://dev.twitter.com/rest/public/search
Query query = new Query("brexit" + " +exclude:retweets"); //" +exclude:retweets" / " -filter:retweets"
query.setResultType(Query.RECENT); //Query.MIXED/Query.POPULAR/Query.RECENT
query.setCount(TWEETS_IN_PAGE);
//Up to 1,500 (on page 15), so 15 times loop
for (int i = 1; i <= 15; i++) {
// Keep in mind that the search index has a 7-day limit. In other words, no tweets will be found for a date older than one week.
// https://dev.twitter.com/rest/reference/get/search/tweets#until
QueryResult result = twitter.search(query);
for (Status tweet : result.getTweets()) {
System.out.println(tweet.getText() + "(@" + tweet.getUser().getScreenName() + ")" + "[" + tweet.getCreatedAt() + "]");
}
// Check if there's a next page, else break the for loop
if (!result.hasNext()){
break;
}
// Keep search only every three seconds because the Twitter'll be angry if you request in continuous
Thread.sleep(3000);
query = result.nextQuery();
}
} catch (TwitterException te) {
// Check Twitter Status on : https://dev.twitter.com/overview/status
te.printStackTrace();
System.out.println("Failed to get the query: " + te.getMessage());
System.exit(-1);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment