【问题标题】:Looping through User Timeline - Twitter API遍历用户时间线 - Twitter API
【发布时间】:2013-12-11 14:40:27
【问题描述】:

我目前正在编写一个通过 Twitter API 遍历用户时间线的 Web 应用程序。我在获取数据或操作数据方面没有任何问题。我遇到的问题是速度。 Twitter API 将您可以检索的推文数量限制为每页 200 条。分页是通过 ID 完成的,方法是在 (max_id) 中传递一个参数,这是您在上一页阅读的最后一条推文。有没有人能想到提高我收到这些推文的速度?我正在使用 abraham oauth lib。我的代码如下:

$twitteroauth = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, $oauth['oauth_token'],     $oauth['oauth_token_secret']);
            $tweets = $twitteroauth->get('statuses/user_timeline', array ( 'screen_name' => 'user_name', 'count' => 200));

            // get first batch of tweets from api
            foreach($tweets as $t)
            {
                $tweets_to_process[] = $t;
            }

            // get last id of tweet and set prev_id to 0
            $last_id = $tweets_to_process[count($tweets_to_process)-1]->id_str;
            $prev_id = 0;
            $loop_num = 0;

            // loop through pages whilst last page returned of api result does not equal last of last result
            while($last_id != $prev_id && $loop_num < 4)
            {
                // get tweets
                $tweets = $twitteroauth->get('statuses/user_timeline', array ( 'screen_name' => 'user_name', 'count' => 200, 'max_id' => $last_id));

                // loop through tweets and add to array
                foreach($tweets as $t)
                {
                    $tweets_to_process[] = $t;
                }

                // set prev and last id
                $prev_id = $last_id;
                $last_id = $tweets_to_process[count($tweets_to_process)-1]->id_str;
                $loop_num ++;
            }

正如你所看到的,我在 while 循环中放置了一个中断计数器,因为从用户体验的角度来看,循环最多 3200 条推文需要太长时间。

【问题讨论】:

    标签: php api twitter oauth


    【解决方案1】:

    Twitter API 的最新版本似乎专门用于减少每次从服务器中提取这些内容的持续压力。我建议您扩展您的代码以按时间提取 twitter 提要(通过 cron/计划任务)并在本地缓存时间线条目。这样您执行的操作可以更快地完成。

    【讨论】:

    • 嗨 - 该应用程序是实时的。由于用户“登录”,然后为该用户时间线提取数据,因此不幸的是,无法以预定义的时间间隔将其拉入,因为我不知道谁在使用它。
    【解决方案2】:

    为了扩展 BAwebimax 的建议。您可以定期下载并在本地缓存推文,然后在用户登录时调用以获取超出“since_id/max_id”的新推文。 旧推文不会改变,因此您可以提前对其进行预处理。当用户登录您的应用程序时,这将导致更少的调用和更少的新推文处理。

    ....

    刚刚注意到您的评论.. 如果场景涉及一次性使用并且没有重复用户,那么上述内容将无用。在这种情况下,您没有太多选择。

    【讨论】:

      【解决方案3】:

      在这种情况下,这似乎不是一个更简化的解决方案。结束

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2014-05-04
        • 2013-03-30
        • 1970-01-01
        • 1970-01-01
        • 2013-06-13
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多