【问题标题】:Twitter API - Count number of tweets of a specific stringTwitter API - 计算特定字符串的推文数量
【发布时间】:2018-11-15 07:54:41
【问题描述】:

我正在使用 twitter api 来尝试获取一个整数,该整数告诉我我给出的某个字符串有多少条推文。

例如我搜索“mercedes”,然后想从 twitter 上得到一个整数,上面写着:“1249”。 1249 意味着过去 2 周内有很多推文。据我所知,Twitter 只返回过去两周的数据。因为我,如果我取回所有记录并通过 php 或类似的方式提取它们也可以。我已经发送了一些测试请求,但总是只返回最多 20 个条目的数组。

谁有解决办法?

我已经看过类似的问题,但找不到对我有帮助的东西。随着 twitter 及其 api 的变化和发展,我看到的许多问题的答案都不再有效

【问题讨论】:

    标签: php api twitter twitter-oauth


    【解决方案1】:

    使用公共搜索 API,您将仅获得过去 7 天的推文,而不是所有推文。所以你的结果不会是准确的。

    如果您仍想测试,则必须使用标准搜索 API: https://developer.twitter.com/en/docs/tweets/search/api-reference/get-search-tweets.html

    将“cout”参数设置为 100,并检查结果中的“next_results”值以循环其他 100 条推文,依此类推,直到没有结果。

    【讨论】:

    • 感谢您的洞察力!我编码了你的想法,并分享它;)
    【解决方案2】:

    我也找不到解决方案,所以我使用之前@JeffProd one 的代码和想法对其进行编码,并避免使用库。希望对你有帮助。

    PS:您必须 apply for a Twitter Developer Account 并创建一个应用程序来获取您的 TOKEN 和 KEY。

    <?php
    //Access token & access token secret
    define("TOKEN", 'XXXXXXXXXXXXXXXX'); //Access token
    define("TOKEN_SECRET", 'XXXXXXXXXXXXXXXX'); //Access token secret
    //Consumer API keys
    define("CONSUMER_KEY", 'XXXXXXXXXXXXXXXX'); //API key
    define("CONSUMER_SECRET", 'XXXXXXXXXXXXXXXX'); //API secret key
    
    $method='GET';
    $host='api.twitter.com';
    $path='/1.1/search/tweets.json'; //API call path
    $url="https://$host$path";
    //Query parameters
    $query = array(
        'q' => 'wordtosearch',          /* Word to search */
        'count' => '100',               /* Specifies a maximum number of tweets you want to get back, up to 100. As you have 100 API calls per hour only, you want to max it */
        'result_type' => 'recent',      /* Return only the most recent results in the response */
        'include_entities' => 'false'   /* Saving unnecessary data */
    );
    //time window in hours
    define("WINDOW", 1); 
    
    //Authentication
    $oauth = array(
        'oauth_consumer_key' => CONSUMER_KEY,
        'oauth_token' => TOKEN,
        'oauth_nonce' => (string)mt_rand(), //A stronger nonce is recommended
        'oauth_timestamp' => time(),
        'oauth_signature_method' => 'HMAC-SHA1',
        'oauth_version' => '1.0'
    );
    //Used in Twitter's demo
    function add_quotes($str) { return '"'.$str.'"'; }
    
    //Searchs Twitter for a word and get a couple of results
    function twitter_search($query, $oauth, $url){  
        global $method; 
    
        $arr=array_merge($oauth, $query); //Combine the values THEN sort
        asort($arr); //Secondary sort (value)
        ksort($arr); //Primary sort (key)
        $querystring=http_build_query($arr,'','&');
        //Mash everything together for the text to hash
        $base_string=$method."&".rawurlencode($url)."&".rawurlencode($querystring);
        //Same with the key
        $key=rawurlencode(CONSUMER_SECRET)."&".rawurlencode(TOKEN_SECRET);
        //Generate the hash
        $signature=rawurlencode(base64_encode(hash_hmac('sha1', $base_string, $key, true)));
        //This time we're using a normal GET query, and we're only encoding the query params (without the oauth params)
        $url=str_replace("&amp;","&",$url."?".http_build_query($query));
        $oauth['oauth_signature'] = $signature; //Don't want to abandon all that work!
        ksort($oauth); //Probably not necessary, but twitter's demo does it
        $oauth=array_map("add_quotes", $oauth); //Also not necessary, but twitter's demo does this too  
        //This is the full value of the Authorization line
        $auth="OAuth ".urldecode(http_build_query($oauth, '', ', '));
        //If you're doing post, you need to skip the GET building above and instead supply query parameters to CURLOPT_POSTFIELDS
        $options=array( CURLOPT_HTTPHEADER => array("Authorization: $auth"),
                          //CURLOPT_POSTFIELDS => $postfields,
                          CURLOPT_HEADER => false,
                          CURLOPT_URL => $url,
                          CURLOPT_RETURNTRANSFER => true,
                          CURLOPT_SSL_VERIFYPEER => false);
        //Query Twitter API
        $feed=curl_init();
        curl_setopt_array($feed, $options);
        $json=curl_exec($feed);
        curl_close($feed);
        //Return decoded response
        return json_decode($json);
    };
    
    //Initializing
    $done = false;      //Loop flag
    $countTweets=0;     //Tweets fetched
    $twitter_data = new stdClass();
    $now=new DateTime(date('D M j H:i:s O Y')); //Current search time
    
    //Fetching starts
    do{
        $twitter_data = twitter_search($query,$oauth,$url);
        //Partial results, updating the total amount of tweets fetched
        $countTweets += count($twitter_data->statuses); 
        //If not all the tweets have been fetched, then redo... 
        if(isset($twitter_data->search_metadata->next_results)){        
            //Parsing information for max_id in tweets fetched
            $string="?max_id="; 
            $parse=explode("&",$twitter_data->search_metadata->next_results);       
            $maxID=substr($parse[0],strpos($parse[0],$string)+strlen($string));     
            $query['max_id'] = -1+$maxID; //Returns results with an ID less than (that is, older than) or equal to the specified ID, to avoid getting the same last tweet
            //Twitter will be queried again, this time with the addition of 'max_id'        
        }else{      
            $done = true;
        }   
    }while(!$done);
    
    //If all the tweets have been fetched, then we are done
    echo "<p>query: ".urldecode($query['q'])."</p>";
    echo "<p>tweets fetched: ".$countTweets."</p>";
    ?>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-07-24
      • 2018-07-23
      • 1970-01-01
      • 2017-12-03
      • 2011-02-11
      • 2014-01-30
      • 2012-11-05
      • 1970-01-01
      相关资源
      最近更新 更多