Skip to content

Get All Friends Code

linvi edited this page Jun 2, 2015 · 1 revision

What is this code for?

Instead of retrieving all the friends in a single operation that could take ages; the following code demonstrates how to retrieve up to 75000 friend ids in a single operation and continue with the next batch of friends.

This give you the ability to not have to store millions of ids in a single collection.

Please note that this code uses Custom Queries through the TwitterAccessor class. The reason is that this specific feature is not yet implemented in Tweetinvi. Thanks for your understanding.

The code

The first part of the code demonstrates how to get up to 75000 friend ids safely.

private static IEnumerable<IIdsCursorQueryResultDTO> GetFriendIds(string username, long cursor, out long nextCursor)
{
    var query = string.Format("https://api.twitter.com/1.1/friends/ids.json?screen_name={0}", username);

    // Ensure that we can get some information
    RateLimit.AwaitForQueryRateLimit(query);
    var results = TwitterAccessor.ExecuteCursorGETCursorQueryResult<IIdsCursorQueryResultDTO>(query, cursor : cursor).ToArray();

    if (!results.Any())
    {
        // Something went wrong. The RateLimits operation tokens got used before we performed our query
        RateLimit.ClearRateLimitCache();
        RateLimit.AwaitForQueryRateLimit(query);
        results = TwitterAccessor.ExecuteCursorGETCursorQueryResult<IIdsCursorQueryResultDTO>(query, cursor : cursor).ToArray();
    }

    if (results.Any())
    {
        nextCursor = results.Last().NextCursor;
    }
    else
    {
        nextCursor = -1;
    }

    return results;
}

The following code demonstrates how to use the previous method.

RateLimit.RateLimitTrackerOption = RateLimitTrackerOptions.TrackOnly;

long nextCursor = -1;

do
{
    var friendIds = GetFriendIds("<user_screen_name>", nextCursor, out nextCursor);
    // Your method to process the friend ids : ProcessFriendIds(friendIds);
} 
while (nextCursor != -1 && nextCursor != 0);
Clone this wiki locally