by Viper
26. May 2009 10:49
While working on new twitter marketing tool Marketweet, I ran into a situation. I need to get count
of people who a person is following. There is an API that gets you a user's profile. But if you notice the results
you will find that results are not current. Some time they are cached for hours. So I was tried few APIs. Finally
I found the one that does return current information. You can get IDs of friends from a user's Social Graph. There
are 2 main issues with this approach as well.
- You do not know how many total results will be returned.
- What is maximum number of results per page that can be returned by this API
So to work around this issue. Here is what I ended up doing. One I set an upper limit of 100000 on number
of users that an account may be following. Also grabbed user's cached profile as well and from there
got number of friends. And ended up using maximum of these two numbers. So when the API runs out of more
results, it returns response that translates to empty collection. And you can use that as sentinel
condition to break out of iterative loop.
static List<TwitterUser> GetFollowings()
{
IFluentTwitter ft = FluentTwitter.CreateRequest();
ft.AuthenticateAs(LOGIN_NAME, PASSWORD);
var profileReq = ft.Users().ShowProfileFor(LOGIN_NAME).AsJson();
var thisUser = profileReq.Request().AsUser();
var followersCount = thisUser.FriendsCount;
var upLimit = (followersCount < 100000) ? 100000 : followersCount;
var ceiling = Math.Ceiling(upLimit / 100m);
var results = new List<TwitterUser>();
for (var i = 1; i <= ceiling; i++)
{
var friendsResp = ft.Users().GetFriends().For(thisUser.Id)
.Skip(i).AsJson().Request();
if (null == friendsResp)
{
break;
}
IEnumerable<TwitterUser> friends = friendsResp.AsUsers();
if (friends == null ||
friends.Count() == 0)
{
break;
}
results.AddRange(friends);
}
return results;
}
Sale Coupons
Deals Of The Day