简体   繁体   中英

Listen tweets in real-time

I want to listen to a tweet in real-time, which means when someone tweets I want to see that tweet.

However I was able to get tweets from my news feed using twitter4j library. Here's the code.

 package twitteroperation;

import java.util.List;
import twitter4j.Status;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.conf.ConfigurationBuilder;

public class TwitterOperation {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) throws TwitterException {


          ConfigurationBuilder cb = new ConfigurationBuilder();

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

     TwitterFactory tf=new TwitterFactory(cb.build());  

     twitter4j.Twitter tw=tf.getInstance();

      List<Status> statuses=  tw.getHomeTimeline();

         for (Status status1 : statuses) {
            System.out.println(status1.getUser().getName() + ":" + status1.getText());

        }   
    }
}

I have found that I must use Streaming APIs to access tweets real-time. But I couldn't find any sample code in java to access teal-time tweets.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM