Friday, April 25, 2014

Getting Potential Reach for ReTweeted Tweets via Linq2Twitter

Linq2Twitter is a super awesome library to use the Twitter Api Thanks to the creator
I wanted to get all tweets and if retweeted , total count of followers of retweeters to see how many people each tweet reached.
And this is how you do it
public async static Task<List<Tuple<Statusint>>> GetTweetsWithReach(int schoolID, DateTime startDate, DateTime endDate)
{
    string twUrl;
    var auth = TWAuthenticate(schoolID, out twUrl);
    try
    {
        if (auth == nullreturn null;
        await auth.AuthorizeAsync();
        using (var twitterCtx = new TwitterContext(auth))
        {
            List<Status> tweets = await (from tweet in twitterCtx.Status
                                         where (tweet.Type == StatusType.User)
                                               && tweet.ScreenName == twUrl.GetTwitterUsername()
                                               //todo change 5
                                                && tweet.Count == 200
                                                // && tweet.RetweetCount > 0
                                                && tweet.CreatedAt < endDate && tweet.CreatedAt > startDate
                                                && tweet.IncludeRetweets == true
                                                && tweet.TrimUser == false
                                         select tweet).ToListAsync();
            var listTweets = new List<Tuple<Statusint>>();
 
            foreach (var tw in tweets)
            {
                int reach = 0;
                if ( tw.RetweetCount > 0)
                {
                    var reTweets = await (from tweet in twitterCtx.Status
                                          where tweet.Type == StatusType.Retweets && tweet.ID == tw.StatusID
                                          select tweet).ToListAsync();
                    if (reTweets != null)
                        reach = reTweets.Where(rt => rt != null && rt.User != null).Sum(rt => rt.User.FollowersCount);
                }
 
                listTweets.Add(new Tuple<Statusint>(tw, reach));
            }
            return listTweets;
        }
    }
    catch (Exception ex)
    {
        ex.LogException(twUrl.GetTwitterUsername() + "twitter error");
        return null;
    }
}

No comments:

Post a Comment