Java code to fetch the twitter followers of any user using twitter screen name

2.7k views Asked by At

I tried to get the twitter followers using the screen name. But i am able to get only my followers screen names where as i am expecting the followers of my followers. But i didn't found any supported method for this.

My code is as follows.

TwitterFactory factory = new TwitterFactory();
Twitter twitter = factory.getInstance();
twitter.setOAuthConsumer(consumerKey, consumerSecret);
AccessToken accessToken = new AccessToken(twitterToken, twitterSecret);
twitter.setOAuthAccessToken(accessToken);
String twitterScreenName = twitter.getScreenName();
IDs followerIDs = twitter.getFollowersIDs(twitterScreenName, -1);
long[] ids = followerIDs.getIDs();
for (long id : ids) {
   twitter4j.User user = twitter.showUser(id);
   //here i am trying to fetch the followers of each id
   System.out.println("Name: " + user.getScreenName());
   System.out.println("Location:" + user.getLocation());
}

Can anyone please help me in this.

1

There are 1 answers

0
Abhijeet Dhumal On BEST ANSWER

You will need to do the nesting over here. You are just getting the list of current users followers. But you need to get the list of followers of your followers.

Sample code is as below:

    TwitterFactory factory = new TwitterFactory();
    Twitter twitter = factory.getInstance();
    String twitterScreenName;
    try {
        twitterScreenName = twitter.getScreenName();

    IDs followerIDs = twitter.getFollowersIDs(twitterScreenName, -1);
    long[] ids = followerIDs.getIDs();
    for (long id : ids) {
       twitter4j.User user = twitter.showUser(id);
       //here i am trying to fetch the followers of each id
       String userScreenName = user.getScreenName();
       System.out.println("Name: " + user.getScreenName());
       System.out.println("Location:" + user.getLocation());

       IDs followerIDsOfFollowers = twitter.getFollowersIDs(user.getScreenName(), -1);
       long[]fofIDs = followerIDsOfFollowers.getIDs();
       for(long subId : fofIDs) {
           twitter4j.User user1 = twitter.showUser(subId);
           System.out.println("Follower Master:" + userScreenName +" Follower of Follower Name: " + user1.getScreenName());
           System.out.println("Location:" + user1.getLocation());

       }