kohloth
kohloth

Reputation: 924

Twitter API: Count number of Tweets since 0:00am this morning?

Is there an API to count the number of Tweets since 0:00am this morning for a particular user? I have tried the following Javascript but the closest I can get to it is the total number of tweets for all time for that user.

$.getJSON("http://api.twitter.com/1/statuses/user_timeline/BarackObama.json?count=1&include_rts=1&callback=?", function(data) {
     $("#twitter").html(data[0].user.statuses_count);
});

Upvotes: 0

Views: 1068

Answers (1)

air-dex
air-dex

Reputation: 4178

You can download the user timeline until you get tweets which were posted "yesterday" (i.e. before 0:00am). Once you get it, you just have to count tweets which were posted "today" (i.e. after 0:00am).

EDIT 1 : a pseudo JavaScript code for getting it

var howManyTweetsWerePostedToday = function () {
    var timeline = downloadTimeline()
    var lastTweet = timeline[timeline.length-1]
    var now = new Date()
    var today = new Date(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDay(), 0, 0, 0, 0) // Limit between today and yesterday
    var lastTweetDate = new Date(lastTweet["created_at"])

    while (lastTweetDate.getTime() >= today.getTime()) {
        var lastTweetID = lastTweet["id_str"]
        var earlierTweetsTimeline = downloadTimeline(max_id = lastTweetID)
        timeline = timeline.concat(earlierTweetsTimeline.shift())
        lastTweet = timeline[timeline.length-1]
        lastTweetDate = new Date(lastTweet["created_at"])
    }

    return getNumberOfTweetsThatWerePostedTodayInTheTimeline(timeline)
}();

With downloadTimeline() which is a function calling the GET statuses/user_timelineTwitter API endpoint to get the timeline. See https://dev.twitter.com/docs/api/1/get/statuses/user_timeline for details about the endpoint, especially max_id which is the highest tweet ID that will be in the results.

created_at is the date when a tweet was posted. id_str is the ID of a tweet under a String form. See https://dev.twitter.com/docs/platform-objects/tweets for more details about tweets.

Upvotes: 1

Related Questions