Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using the Twitter Streaming API

I need to notify my app of new tweets in real time from a selected few users. AFAIK, to do this I need to use the Twitter Streaming API. I have come across Twitter4J but i am not quite sure how to use this with the Streaming API. Does anyone know of any concrete up to date examples on using this?

Also, I came across this exerpt in the Streaming API documentation here:

Each account may create only one standing connection to the public endpoints, and connecting to a public stream more than once with the same account credentials will cause the oldest connection to be disconnected. Clients which make excessive connection attempts (both successful and unsuccessful) run the risk of having their IP automatically banned.

The app will need to update for all users when a new tweet is received. Would that break this rule? Do I need to create a backend instead to receive the stream and then push the new tweets down from there?

like image 503
Orbit Avatar asked Aug 25 '15 15:08

Orbit


2 Answers

You indeed need a backend, I suggest to create a PHP file (though any language that you like can serve), that connects to the streaming API, and on every new post sends a Google Cloud Message to all users of the app. In your android app you can then implement a broadcast receiver that handles the GCM message which should at least contain the link of the tweet, but can contain the complete tweet content.

Without a single connection point like a server, you would as you already suggested break the streaming API rules, and even worse, only one user at a time would have a reliable connection.

Hope that helps.

like image 138
Bas van Stein Avatar answered Sep 30 '22 17:09

Bas van Stein


No, you don't need any backend for this purpose. Each authenticated user can have its own stream in the app itself. Following is the code snippet which I am using in my own application.

I assume that the user is following those users. If they are not following then they are not going to get any tweets from them in their stream.

In case you want tweets from certain users to be delivered to everyone irrespective of the fact whether they are following those certain users or not, then you will have to open a public stream. This can't be done in the app itself and therefore you will need backend in that case. In that case only one instance of stream has to be opened and whenever a tweet arrives from those certain users, that tweet has to be notified to each user of your app.

I hope I am clear with my explanation.

In this code you just have to filter the tweets for those selected users.

    ConfigurationBuilder config = new ConfigurationBuilder();
    config.setJSONStoreEnabled(true);
    config.setOAuthConsumerKey(Keys.TWITTER_KEY);
    config.setOAuthConsumerSecret(Keys.TWITTER_SECRET);
    config.setOAuthAccessToken(HelperFunctions.currentSession.getAuthToken().token);
    config.setOAuthAccessTokenSecret(HelperFunctions.currentSession.getAuthToken().secret);

    Configuration cf = config.build();
    HelperFunctions.twitter = new TwitterFactory(cf).getInstance();

    HelperFunctions.twitterStream = new TwitterStreamFactory(cf).getInstance();
    HelperFunctions.twitterStream.addListener(listener);
    // user() method internally creates a thread which manipulates TwitterStream and calls these adequate listener methods continuously.
    HelperFunctions.twitterStream.user();







private static final UserStreamListener listener = new UserStreamListener() {
    @Override
    public void onStatus(Status status) {
        // Filter your selected users here
        System.out.println("onStatus @" + status.getUser().getScreenName() + " - " + status.getText());
    }

    @Override
    public void onFriendList(long[] friendIds) {
    }

    @Override
    public void onFavorite(User source, User target, Status favoritedStatus) {
    }

    @Override
    public void onUnfavorite(User source, User target, Status unfavoritedStatus) {

    }

    @Override
    public void onFollow(User source, User followedUser) {
    }

    @Override
    public void onUnfollow(User source, User unfollowedUser) {
    }

    @Override
    public void onDirectMessage(DirectMessage directMessage) {
    }

    @Override
    public void onUserListMemberAddition(User addedMember, User listOwner, UserList list) {
    }

    @Override
    public void onUserListMemberDeletion(User deletedMember, User listOwner, UserList list) {
    }

    @Override
    public void onUserListSubscription(User subscriber, User listOwner, UserList list) {
    }

    @Override
    public void onUserListUnsubscription(User subscriber, User listOwner, UserList list) {
    }

    @Override
    public void onUserListCreation(User listOwner, UserList list) {
    }

    @Override
    public void onUserListUpdate(User listOwner, UserList list) {
    }

    @Override
    public void onUserListDeletion(User listOwner, UserList list) {
    }

    @Override
    public void onUserProfileUpdate(User updatedUser) {
    }

    @Override
    public void onBlock(User source, User blockedUser) {
    }

    @Override
    public void onUnblock(User source, User unblockedUser) {
    }

    @Override
    public void onException(Exception ex) {
    }

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

    @Override
    public void onDeletionNotice(long directMessageId, long userId) {
        System.out.println("Got a direct message deletion notice id:" + directMessageId);
    }

    @Override
    public void onTrackLimitationNotice(int numberOfLimitedStatuses) {
        System.out.println("Got a 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);
    }
};
like image 34
Pranjal Sahu Avatar answered Sep 30 '22 16:09

Pranjal Sahu