简体   繁体   中英

How to retrieve tweets of user and his/her followers under a certain hashtag using Twitter4j?

I am trying to build a twitter4j application that creates a small twitter network, actually. Here is my sample code snippet:

 //Monitoring hashtags Query query = new Query("#anger"); query.setCount(100); //get 100 tweets query.setSince("2010-01-01"); QueryResult result; try { result = twitter.search(query); for (Status status : result.getTweets()) { if (status.getText() != null) { // Getting followers list of a given user ArrayList<User> followers = getFollowers(status.getUser().getScreenName()); for (User user : followers) { if (status.getUser().getScreenName().contains(user.getScreenName())) { System.out.println(status.getUser().getScreenName()); } } } } } catch (TwitterException e) { // TODO Auto-generated catch block e.printStackTrace(); } 

I think that this code should print existence(names) of the followers of users under "#anger" hashtag. However, when I run this code, it violates the api 1.1 rate limits with an exception (message - Rate limit exceeded, code - 88). How can I overcome this issue?

Here is also my getFollowers() method:

 // Getting followers list of a given user public static ArrayList<User> getFollowers (String usname) { Twitter twitter = initTwitter(); String username = usname; ArrayList<User> followers = new ArrayList<User>(); long nextCursor = -1; do { PagableResponseList<User> usersResponse; try { usersResponse = twitter.getFollowersList(username, nextCursor); nextCursor = usersResponse.getNextCursor(); followers.addAll(usersResponse); } catch (TwitterException e) { e.printStackTrace(); } } while (nextCursor > 0); return followers; } 

Rate limit for calling getFollowers() is:

Requests / 15-min window (user auth): 15
Requests / 15-min window (app auth): 30

https://dev.twitter.com/rest/reference/get/followers/list

Since you are calling getFollowers() more than this from for (Status status : result.getTweets()) you are getting rate limit error.

Check rate limits here:

    for (Status status : result.getTweets()) 
     {
         if (status.getText() != null)
         {
             // Getting followers list of a given user
             ArrayList<User> followers = getFollowers(status.getUser().getScreenName());
             // Here, Check if you rate limit has been exceeded. 
             // If so, wait till limit is over and then continue
              .....
         }
     }

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