Search code examples
phptwitter

Twitter API - load X posts each time


I have three Twitter posts as follows:

-> Twitter with message 3 
-> Twitter with message 2 
-> Twitter with message 1

The Twitter with message 3 is the most recent in my timeline.

I'm trying to retrieve 1 post at a time ordered by descending (most recent to oldest). The Twitter API documentation I'm following is https://developer.twitter.com/en/docs/tweets/timelines/api-reference/get-statuses-user_timeline

According to the API, I'm trying to implement some code-logic and therefore I have a function like this one:

function getPosts($lastTwitterId = null)
{
    // I always retrieve 1 at a time (for testing purposes)
    $data = ['user_id' => 'my user id', 'count' => 1];

    // Get last twitter Id retrieved
    if ($lastTwitterId)
        $data['max_id'] = $lastTwitterId;

    return $twitter->get('statuses/user_timeline', $data);
}

With this code I'm getting the following behaviour:

-> grabs posts
    -> Twitter with message 3 -> OK 
-> grabs next posts 
    -> Twitter with message 3 -> NOT OK DUPLICATED (should get -> Twitter with message 2)
-> grabs next posts  
    -> Twitter with message 3 -> NOT OK DUPLICATED (should get -> Twitter with message 1)

I have checked and the $lastTwitterId variable gets the value correctly after the first call.


Solution

  • Solved.

    The solution is in this post using since_id and max_id in Twitter API. The only thing I needed to change was this:

    $data['max_id'] = $lastTwitterId;
    

    Into this:

    $data['max_id'] = $lastTwitterId - 1;