Example usage for twitter4j QueryResult getTweets

List of usage examples for twitter4j QueryResult getTweets

Introduction

In this page you can find the example usage for twitter4j QueryResult getTweets.

Prototype

List<Status> getTweets();

Source Link

Usage

From source file:twitterbot.TwitterActions.java

public void searchTweetandRetweet(String hashtag) {
    Query query = new Query(hashtag);
    query.count(40);//  w  w  w  .  jav a2  s.c  om
    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;/*from   ww w  .j a va 2  s  . c om*/

    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;/*from w  ww.  j a v  a 2 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:twitterrest.GeoSearch.java

License:Apache License

public static void main(String[] args) throws TwitterException {
    // ?/*from  www . j av  a 2 s. c o m*/
    Configuration configuration = new ConfigurationBuilder().setOAuthConsumerKey(CONSUMER_KEY)
            .setOAuthConsumerSecret(CONSUMER_SECRET).setOAuthAccessToken(ACCESS_TOKEN)
            .setOAuthAccessTokenSecret(ACCESS_TOKEN_SECRET).build();
    Twitter twitter = new TwitterFactory(configuration).getInstance();
    Query query = new Query();

    // ?????10kmIP??????      
    GeoLocation geo = new GeoLocation(35.69384, 139.703549);
    query.setGeoCode(geo, 10.0, Query.KILOMETERS);

    // 
    QueryResult result = twitter.search(query);

    // ???Tweet??placegeoLocation??????
    for (Status tweet : result.getTweets()) {
        System.out.println(tweet.getText());
        System.out.println(tweet.getPlace() + " : " + tweet.getGeoLocation());
    }
}

From source file:twitterrest.SearchTweet.java

License:Apache License

public static void main(String[] args) throws TwitterException {
    //?// w  w w . j a v a 2 s .co m
    Configuration configuration = new ConfigurationBuilder().setOAuthConsumerKey(CONSUMER_KEY)
            .setOAuthConsumerSecret(CONSUMER_SECRET).setOAuthAccessToken(ACCESS_TOKEN)
            .setOAuthAccessTokenSecret(ACCESS_TOKEN_SECRET).build();
    Twitter twitter = new TwitterFactory(configuration).getInstance();
    Query query = new Query();
    try {
        File file = new File("./file/tweets.txt");
        PrintWriter pw;
        //???
        pw = new PrintWriter(new BufferedWriter(new FileWriter(file, true)));

        // ???
        query.setQuery("?");
        query.setLang("ja");
        // 1????Tweet?100?
        query.setCount(100);
        //?????????
        //query.setSince("2013-06-13");
        //query.setUntil("2013-06-17");

        // 150015
        for (int i = 1; i <= 15; i++) {
            // 
            QueryResult result = twitter.search(query);
            System.out.println(": " + result.getTweets().size());
            System.out.println(" : " + new Integer(i).toString());

            // ???
            for (Status tweet : result.getTweets()) {
                // 
                String str = tweet.getText();
                System.out.println(str);
                //
                System.out.println(tweet.getUser());
                //
                System.out.println(tweet.getCreatedAt());
                // ??URL?   
                StringTokenizer sta = new StringTokenizer(str, " ");
                //?
                while (sta.hasMoreTokens()) {
                    String wk = sta.nextToken();
                    if (wk.indexOf("#") == -1 && wk.indexOf("http") == -1 && wk.indexOf("RT") == -1
                            && wk.indexOf("@") == -1) {
                        pw.println(wk);
                    }
                }
                String u = tweet.getUser().getName();
                pw.println(u);
            }
            if (result.hasNext()) {
                query = result.nextQuery();
            } else {
                break;
            }
        }
        pw.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:twitterrest.UserSearch.java

License:Apache License

public static void main(String[] args) throws TwitterException {
    //?/*from   w ww.  jav a 2 s .  c o m*/
    Configuration configuration = new ConfigurationBuilder().setOAuthConsumerKey(CONSUMER_KEY)
            .setOAuthConsumerSecret(CONSUMER_SECRET).setOAuthAccessToken(ACCESS_TOKEN)
            .setOAuthAccessTokenSecret(ACCESS_TOKEN_SECRET).build();
    Twitter twitter = new TwitterFactory(configuration).getInstance();
    Query query = new Query();

    // masason?Tweet
    //query.setQuery("from:anondroid3 OR to:anondroid3");
    query.setQuery("from:anondroid3");

    // ???
    QueryResult result = twitter.search(query);
    //
    System.out.println(":" + result.getTweets().size());
    // 1????Tweet?100?
    query.setCount(100);

    for (Status tweet : result.getTweets()) {
        System.out.println("tweet:" + tweet.getText());//
        System.out.println("UserID:" + tweet.getUser().getId());//ID
        System.out.println("Application:" + tweet.getSource());//
        System.out.println("Created Date:" + tweet.getCreatedAt());//?
        System.out.println("GeoLocation:" + tweet.getGeoLocation());//
    }
}

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  w w . j a  v  a2 s.c  om*/
        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:twittertestingagain.TwitterTesting.java

/**
 * @param args the command line arguments
 * @throws twitter4j.TwitterException/*from  ww  w. ja 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();/*from w  ww . j  a  v  a  2 s .co 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.//w ww. j a  v  a 2 s  .co  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);
    }
}