Ammar Khan
Ammar Khan

Reputation: 356

Getting All followers with Linq To Twitter

I am trying to get all the followers list by using the below code snippet. Each call get 200 follwers so I wrap up in the loop to get all the followers. User has 23.1K followers, but I m getting "Rate Limit" Exceed error when it reaches to 2800 followers. I found out twitter allow 15 request per user, is there any way I can fix up the below code to get all followers?

private static async Task<List<User>> GetTwitterFollowersAsync(
         ulong twitterUserId, SingleUserAuthorizer auth, int? maxFollowers)
{
    var followerss = maxFollowers ?? 15000;
    long nextCursor = -1;
    var users = new List<User>();

    try
    {
        while (nextCursor != 0)
        {
            var twitterCtx = new TwitterContext(auth);              
            var friends = await twitterCtx.Friendship
                .Where(f => f.Type == FriendshipType.Show
                     && f.SourceScreenName == "John_Papa"
                     && f.Count == followerss && f.Cursor == nextCursor)
                .Select(f => new TwitterData()
                {
                     NewCursor = f.CursorMovement.Next,
                     Followers = f.Users.Where(t => !t.Protected)
                            .Take(followerss).Select(s => s).ToList()
                })
                .SingleOrDefaultAsync();

            nextCursor = friends.NewCursor;
            users.AddRange(friends.Followers);
        }
        return users;
    }
    catch (Exception ex)
    {
        return null;
    }
}

Upvotes: 2

Views: 1282

Answers (1)

Joe Mayo
Joe Mayo

Reputation: 7513

LINQ to Twitter has RateLimitXxx properties on TwitterContext that update after every query. They reflect the information described in this Rate Limiting documentation at Twitter:

https://dev.twitter.com/docs/rate-limiting/1

You have a 15 minute window for each number of queries in a rate limit per type of query. You can enclose your code in a loop with the following logic:

  1. Perform query
  2. Break loop if you have all the results you need.
  3. Check rate limit
  4. If rate limit exceeded, wait until 15 minute interval expires.
  5. If rate limit not exceeded, keep looping.

Upvotes: 3

Related Questions