List of usage examples for twitter4j Query Query
public Query(String query)
From source file:twitterbot.TwitterActions.java
public void searchTweetandRetweet(String hashtag) { Query query = new Query(hashtag); query.count(40);// ww w.j a va 2s . co m int check = 0; int alreadyused = 0; int remove = 0; try { QueryResult queryresult = this.twitter.search(query); this.tweets = (ArrayList<Status>) queryresult.getTweets(); Collections.reverse(tweets); for (Status status : tweets) { if (!status.isRetweetedByMe() && status.getCreatedAt().getTime() > this.lastStatusTime) { try { this.retweetTweet(status); this.lastStatusTime = status.getCreatedAt().getTime(); this.writeTimeToFile(); Thread.sleep(10000); } catch (TwitterException tex) { System.out.println("Twitter Exception - Already Retweeted"); } } } } catch (TwitterException ex) { Logger.getLogger(TwitterActions.class.getName()).log(Level.SEVERE, null, ex); } catch (InterruptedException ex) { Logger.getLogger(TwitterActions.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:TwitterDownload.TwitterHandler.java
public List<Status> getSearchTweets(String searchPhrase, int pageSize) { if (pageSize > 18000) pageSize = 18000;// w w w . j a va2s.co m ArrayList<Status> tweets = new ArrayList<Status>(); //boolean last = false; try { Query query = new Query(searchPhrase); int limit = getRemainingSearchRateLimit(); while (tweets.size() < pageSize && query != null && limit > 0) { if (pageSize - tweets.size() > 100) query.setCount(100); else query.setCount(pageSize - tweets.size()); QueryResult result = twitter.search(query); tweets.addAll(result.getTweets()); query = result.nextQuery(); limit = getRemainingSearchRateLimit(); } return (List<Status>) tweets; } catch (TwitterException ex) { String s = ex.toString(); if (ex.exceededRateLimitation()) return null; } catch (IllegalStateException ex) { String s = ex.toString(); } return null; }
From source file:twitteremoji.FXMLDocumentController.java
private void startCrawling(String term) { crawling = true;//ww w. j a va2 s .c o m (new Thread() { public void run() { try { // crawler // just do once for debugging //while(crawling) { Query query = new Query(term); QueryResult result; result = twitter.search(query); List<Status> tweets = result.getTweets(); for (Status tweet : tweets) { //String emoji = cleanTweetLeaveEmoji(tweet.getText()); crawlerTableData.add( new StatusWrapper(DateFormat.getDateTimeInstance().format(tweet.getCreatedAt()), tweet.getUser().getName(), tweet.getText(), "")); } //} } catch (TwitterException ex) { statusLabel.setText(STATUS_PREFIX + STATUS_ERROR); } } }).start(); }
From source file:twittersentimentanalysis.TwitterSentimentAnalysis.java
private static ArrayList<Tweet> getAllTweets(Twitter twitter) { logger.info("getAllTweets"); List<Status> listTweets = null; ArrayList<Tweet> listOfTweets = new ArrayList<Tweet>(); try {//w ww. j av a2 s . co m Trends trends = twitter.getPlaceTrends(23424977); // System.out.println(trends.getLocation()); Trend trend[] = trends.getTrends(); logger.info("Number of Trends : " + trend.length); for (Trend trendTemp : trend) { //System.out.println("Name = " + trendTemp.getName()); //System.out.println("***************"); Query query = new Query(trendTemp.getQuery()); query.setCount(100); QueryResult queryResult = twitter.search(query); listTweets = queryResult.getTweets(); StanfordCoreNLPTool.init(); for (Status status : listTweets) { //System.out.println(status.getText()); Tweet tweet = getTweetObject(status); if (tweet != null) { tweet.setTrend(trendTemp.getName()); listOfTweets.add(tweet); } } } } catch (TwitterException ex) { Logger.getLogger(TwitterSentimentAnalysis.class.getName()).log(Level.SEVERE, null, ex); logger.info(ex.getMessage()); } return listOfTweets; }
From source file:TwitterStats.Facade.Twitter.java
public List<Status> getTuitsCuenta(String user, Date desde, Date hasta, int cantidad) throws TwitterException { SimpleDateFormat dt = new SimpleDateFormat("yyyy-MM-dd"); Query q = new Query("from:" + user + " since:" + dt.format(desde) + " until:" + dt.format(hasta)); q.setCount(100);/* w ww .jav a 2 s . c o m*/ List<Status> lista = new ArrayList<>(); List<Status> res = twitter.search(q).getTweets(); while (res.size() > 1 && lista.size() < 3000) { lista.addAll(res); q.setMaxId(res.get(res.size() - 1).getId()); res = twitter.search(q).getTweets(); } Collections.sort(lista, new Comparator<Status>() { public int compare(Status s1, Status s2) { return s1.getFavoriteCount() > s2.getFavoriteCount() ? -1 : (s1.getFavoriteCount() < s2.getFavoriteCount()) ? 1 : 0; } }); if (lista.size() > cantidad) { return lista.subList(0, cantidad); } else { return lista; } }
From source file:TwitterStats.Facade.Twitter.java
public Map<String, Integer> getTendencias(String user, Date desde, Date hasta) throws TwitterException { Map<String, Integer> tendencias = new HashMap<>(); SimpleDateFormat dt = new SimpleDateFormat("yyyy-MM-dd"); Query q = new Query("from:" + user + " since:" + dt.format(desde) + " until:" + dt.format(hasta)); q.setCount(100);//from w w w . j ava 2 s . co m List<Status> lista = new ArrayList<>(); List<Status> res = twitter.search(q).getTweets(); while (res.size() > 1 && lista.size() < 3000) { lista.addAll(res); q.setMaxId(res.get(res.size() - 1).getId()); res = twitter.search(q).getTweets(); } for (Status status : lista) { HashtagEntity[] ht = status.getHashtagEntities(); for (int i = 0; i < ht.length; i++) { String hash = ht[i].getText(); if (tendencias.containsKey(hash)) { tendencias.put(hash, tendencias.get(hash) + 1); } else { tendencias.put(hash, 1); } } } return sortByValue(tendencias); }
From source file:twittertestingagain.TwitterTesting.java
/** * @param args the command line arguments * @throws twitter4j.TwitterException//from w ww . j a v a 2s. c o m * @throws java.io.IOException */ public static void main(String[] args) throws TwitterException, IOException { /* ---------------------------Setting up twitter account authentication-------------------------------*/ ConfigurationBuilder cb = new ConfigurationBuilder(); cb.setDebugEnabled(true).setOAuthConsumerKey("YjICBJeNlnxAf3tFw7awLaCzS") .setOAuthConsumerSecret("8IfPzkr4opePnhCLLloKMP6X44IeNav0fLDrmtBrPbaHoxd1nO") .setOAuthAccessToken("4146680697-oOEPVezvvZ82vB7iP9HSbkoTG9ze9gH69XLrSCP") .setOAuthAccessTokenSecret("HZjsaabmVjeSkSX6vvVFdT3GWZek8xJ9RKfwaR57RDyEG"); /* ---------------------------------File Writing Variables------------------------------------------------*/ File outfile = new File("output.txt"); FileWriter fwriter = new FileWriter(outfile); try (PrintWriter pWriter = new PrintWriter(fwriter)) { /*----------------------------------Search Parameters-------------------------------------*/ String search = "chinese food"; String lang = "en"; /*------------------------End Search Parameters----------------------------------------*/ int numTweets = 0; long maxID = -1; TwitterFactory tf = new TwitterFactory(cb.build()); Twitter twitter = tf.getInstance(); try { Map<String, RateLimitStatus> rateLimitStatus = twitter.getRateLimitStatus("search"); //System.out.println(rateLimitStatus); RateLimitStatus searchTweetsRateLimit = rateLimitStatus.get("/search/tweets"); /*System.out.printf("You have %d calls remaining out of %d, Limit resets in %d seconds\n", searchTweetsRateLimit.getRemaining(), searchTweetsRateLimit.getLimit(), searchTweetsRateLimit.getSecondsUntilReset()); */ for (int queryNumber = 0; queryNumber < maxQueries; queryNumber++) { System.out.printf("\n\n!!! Starting loop %d\n\n", queryNumber); pWriter.println("\n\n!!! Starting iteration #" + queryNumber + "\n\n"); if (searchTweetsRateLimit.getRemaining() == 0) { System.out.printf("!!! Sleeping for %d seconds due to rate limits\n", searchTweetsRateLimit.getSecondsUntilReset()); Thread.sleep((searchTweetsRateLimit.getSecondsUntilReset() + 2) * 1000l); } //here is where we can send an object to the query Query query = new Query(search); query.setCount(tweetsPerQuery); query.resultType(Query.ResultType.recent); query.setLang(lang); if (maxID != -1) { query.setMaxId(maxID - 1); } QueryResult result = twitter.search(query); if (result.getTweets().size() == 0) { break; } for (Status s : result.getTweets()) { numTweets++; if (maxID == -1 || s.getId() < maxID) { maxID = s.getId(); } System.out.printf("On %s, @%-20s said: %s\n", s.getCreatedAt().toString(), s.getUser().getScreenName(), cleanText(s.getText())); pWriter.println("On " + s.getCreatedAt().toString() + " @" + s.getUser().getScreenName() + " " + cleanText(s.getText())); } searchTweetsRateLimit = result.getRateLimitStatus(); } } catch (Exception e) { System.out.println("Broken"); e.printStackTrace(); } System.out.printf("\n\nA total of %d tweets retrieved\n", numTweets); pWriter.println("\n\nA total of " + numTweets + " tweets retrieved\n\n"); pWriter.close(); /*while (result.hasNext()){ numTweets += result.getCount(); System.out.println(numTweets); for (Status status : result.getTweets()) { System.out.println("@" + status.getUser().getScreenName() + ":" + status.getText()); } result.nextQuery(); } /* QueryForm qf = new QueryForm(); qf.show(); */ } }
From source file:twittervis.TwitterVis.java
public void retrieveTweets(String keyword, boolean topic) { Twitter twitter = tf.getInstance();//ww w.j av a 2 s . c o m Query query = new Query(keyword); // The query parameter ("keyword") can be modified to make more // specific search queries based on language, users, time, etc. //Query query = new Query(keyword +" AND lang:en AND until:2016-12-01"); //number of tweets needed for each topic. query.count(240); // Assign the tweets to the corresponding Emotion Node if (topic == true) { JoyNode = "Joy1"; SadnessNode = "Sadness1"; AngerNode = "Anger1"; DisgustNode = "Disgust1"; FearNode = "xFear1"; } else { JoyNode = "Joy2"; SadnessNode = "Sadness2"; AngerNode = "Anger2"; DisgustNode = "Disgust2"; FearNode = "xFear2"; } //Try making the query request. try { QueryResult result = twitter.search(query); // Process the analysis results and create new edges and nodes accordingly result.getTweets().forEach((status) -> { status.getText(); //get the textual info from a tweet // String userName = status.getUser().getScreenName(); String TwtText = status.getText(); System.out.println("@" + status.getUser().getScreenName() + ":" + status.getText()); String twtEmotion = getTweetEmotion(TwtText); // A switch to assign the tweet to the correct node switch (twtEmotion) { case "Joy": System.out.println("Joy (*^__^*)"); graph.addEdge(TwtText, JoyNode, TwtText); break; case "Sadness": System.out.println("Sad (*T_T*)"); graph.addEdge(TwtText, SadnessNode, TwtText); break; case "Anger": System.out.println("Anger ()"); graph.addEdge(TwtText, AngerNode, TwtText); break; case "Fear": System.out.println("Fear ?|||"); graph.addEdge(TwtText, FearNode, TwtText); break; case "Disgust": System.out.println("Disgust (*~)"); graph.addEdge(TwtText, DisgustNode, TwtText); break; } }); } catch (TwitterException ex) { //fallback if exceptions occur System.out.println("Couldn't connect: " + ex); } }
From source file:twitter_contornos.Metodos.java
/** * Realizas una busqueda por hastag o palabras y te muestra twits relacionados * con la palabra que escribiste.//from w w w .jav a2s .c o m * @param busqueda */ public void buscarTrending(String busqueda) { try { Query query = new Query(busqueda); QueryResult result = twitter.search(query); for (Status status : result.getTweets()) { System.out.println("@" + status.getUser().getScreenName() + ":" + status.getText()); } } catch (TwitterException ex) { Logger.getLogger(Metodos.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:twittynumnum.BackwardGrinder.java
public void grind(String queryString) { try {/* w w w . j a v a2s. c o m*/ Query query = new Query(queryString); QueryResult result; do { result = twitter.search(query); List<Status> tweets = result.getTweets(); for (Status tweet : tweets) { System.out.println("@" + tweet.getUser().getScreenName() + " - " + tweet.getText() + " - " + tweet.getCreatedAt()); } } while ((query = result.nextQuery()) != null); System.exit(0); } catch (TwitterException te) { te.printStackTrace(); System.out.println("Failed to search tweets: " + te.getMessage()); System.exit(-1); } }