Listen tweets in real-time

北战南征 提交于 2019-12-01 01:10:23

Twitter4j provides examples, and one of them is exactly what you are looking for, however you need to change the line

TwitterStream twitterStream = new TwitterStreamFactory().getInstance();

with

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

      TwitterStream twitterStream = new TwitterStreamFactory(cb.build())
              .getInstance();

If you don't, you will have to configure the properties file. After that you will get this code

import twitter4j.*;
import twitter4j.conf.ConfigurationBuilder;

public final class PrintSampleStream {

    public static void main(String[] args) throws TwitterException {
         ConfigurationBuilder cb = new ConfigurationBuilder();
          cb.setDebugEnabled(true).setOAuthConsumerKey("")
                  .setOAuthConsumerSecret("")
                  .setOAuthAccessToken("")
                  .setOAuthAccessTokenSecret("");
          TwitterStream twitterStream = new TwitterStreamFactory(cb.build())
                  .getInstance();
        StatusListener listener = new StatusListener() {
            @Override
            public void onStatus(Status status) {
                System.out.println("@" + status.getUser().getScreenName() + " - " + status.getText());
            }

            @Override
            public void onDeletionNotice(StatusDeletionNotice statusDeletionNotice) {
                System.out.println("Got a status deletion notice id:" + statusDeletionNotice.getStatusId());
            }

            @Override
            public void onTrackLimitationNotice(int numberOfLimitedStatuses) {
                System.out.println("Got track limitation notice:" + numberOfLimitedStatuses);
            }

            @Override
            public void onScrubGeo(long userId, long upToStatusId) {
                System.out.println("Got scrub_geo event userId:" + userId + " upToStatusId:" + upToStatusId);
            }

            @Override
            public void onStallWarning(StallWarning warning) {
                System.out.println("Got stall warning:" + warning);
            }

            @Override
            public void onException(Exception ex) {
                ex.printStackTrace();
            }
        };
        twitterStream.addListener(listener);
        twitterStream.sample();
    }
}

With that you'll start to receive the sample public stream. If you want to get specific tweets you will need to use some filters. For example if you want the tweets for an specific query you need to change this line

twitterStream.sample();

with the word that you want

FilterQuery filtre = new FilterQuery();
String[] keywordsArray = { "obama" };
filtre.track(keywordsArray);
twitterStream.filter(filtre);

If you want to stream tweets from specifics profiles you will need to use the follow filter. The line twitterStream.sample(); you will need to change it for this

          long[] users = new long[]{someid,someotherid,otherid};
          twitterStream.addListener(listener);
          FilterQuery filtre = new FilterQuery();
          filtre.follow(users);
          twitterStream.filter(filtre);

The id's for the array are the id's that Twitter use for every user. If you don't know the id for a certain user you could get it with Twitter4j:

User user = tw.showUser("barackobama"); //tw is your Twitter variable from twitter4j.Twitter tw=tf.getInstance();
long id = user.getId();

There are more ways to retrieve tweets from the stream, you only need to read the documentation or search on this site. Good luck!

I would recommend you to try out the Twitter HBC project. It has some good examples on the front-page for how you can set up a BlockingQueue for consuming events.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!