2017-04-26 3 views
1

Bereits habe ich ein Skript, das die ersten 5000 Benutzer von Freunden/IDs sammelt. Ich möchte alle Freunde sammeln, also muss ich durch Cursor bewegen, um sie zu bekommen. Ich denke, ich verstehe, wie der Cursor funktioniert, aber ich kann es immer noch nicht funktionieren lassen. Ich versuche next_cursor zu erreichen, weiß aber nicht, was ich falsch mache.Twitter API Cursor PHP

Es scheint, dass der Cursor, den ich versuche zu bekommen, nicht richtig aufgerufen wird.

Möchte ein Feedback mit diesen, weil Twitter-API kein reales Beispiel gibt.

<?php 

header("Content-Type: text/html;charset=utf-8"); 
ini_set('display_errors', 1); 
require_once('TwitterAPIExchange.php'); 
session_start(); 
$user = $_POST['nombre']; 
$_SESSION['user']=$_POST['nombre']; 
$usuario = $user; 


$servername = "localhost"; 
$username = "root"; 
$password = ""; 
$dbname = "twitter"; 

// Create connection 
$conn = new mysqli($servername, $username, $password, $dbname); 
// Check connection 
if ($conn->connect_error) { 
    die("Connection failed: " . $conn->connect_error); 
} 


/** Set access tokens here - see: https://dev.twitter.com/apps/ **/ 
$settings = array(
'oauth_access_token' => "k1", 
'oauth_access_token_secret' => "k2", 
'consumer_key' => "k3", 
'consumer_secret' => "k4" 

); 

//https://api.twitter.com/1/followers/ids.json?cursor=-1&screen_name=microsoft 

$cursor = "cursor=".-1; 
$url = 'https://api.twitter.com/1.1/friends/ids.json'; 
$getfield = '?'.$cursor.'screen_name='.$usuario; 
$requestMethod = 'GET'; 


$twitter = new TwitterAPIExchange($settings); 
$json = $twitter->setGetfield($getfield) 
->buildOauth($url, $requestMethod) 
->performRequest(true, array(CURLOPT_CAINFO => dirname(__FILE__) . '/cacert.pem')); 

$arrayFriends = json_decode($json, true,512,JSON_BIGINT_AS_STRING); 

echo 'Usuario' .";". 'Nombre'.";".'Location'.";".'Numero Amigos'.";".'Numero  followers'.";".'Descripcion'."\n"; 

foreach($arrayFriends['next_cursor'] as $curs){ 
foreach($arrayFriends['ids'] as $obj){ 
while($cursor != 0){ 
    //$cursor->$arrayFriends['ids']->next_cursor; 
    $cursor = $curs; 
    //$cursor = "&cursor=" + $cursor; 
    $sql = "INSERT INTO friends (user, id) VALUES ('$usuario','$obj')"; 
    if ($conn->query($sql) === TRUE) { 
     //echo "New record created successfully"; 
     header("Location:logic.php"); 
    } else { 
     echo "Error: " . $sql . "<br>" . $conn->error; 
    } 
} 
    } 
} 
$conn->close(); 

?> 
+0

Hey Leute, kann mir jemand ein bisschen Feedback geben. Ich versuche das zu lösen, verliere aber viel Zeit darauf. – seyroku

+0

yo Leute, immer noch nicht funktioniert und brauche einen Rat oder etwas! – seyroku

+0

Ich teile den Code zum Abrufen aller Freunde mit dem Cursor. Dies ist jedoch eine gute Übung, um alle Freunde auf einmal zu holen. Sie werden weiterhin nur 3000 Freunde als Twitter crawlen, die 15 Anfragen/15 Minuten Fenster und maximal 200 Ergebnisse pro Anfrage erlauben. Bevor Sie next_cursor in der Datenbank speichern und eine neue Anfrage stellen, indem Sie den Cursorwert aus der Datenbank abrufen. Sie können cron-job dafür verwenden. – prograshid

Antwort

0

Versuchen Sie diesen Code. Es wird bis zu 3000 Freunde holen.

Laufzeit des Skripts ist ca. 3-5 Minuten

//function to fetch friends of the authenticating user 

function getAllFriends($auth_user_screen_name) 
{ 
    //---getting application tokens and connection to database 
    $arraySettings = defaultSettings(); 

    $con = $arraySettings['connection']; 

    //create api instance 
    \Codebird\Codebird::setConsumerKey('consumerKey', 'consumerSecret'); 
    $objTwitter = \Codebird\Codebird::getInstance(); 

    $oauth_token = "oauth_token"; 
    $oauth_token_secret = "oauth_token_secret"; 

    $objTwitter->setToken($oauth_token, $oauth_token_secret); 

    //initialize empty array to store friends data returned from API  
    $friendsData=array(); 

    if (strlen($oauth_token) > 0 && strlen($oauth_token_secret) > 0) { 

    $cursor = -1; 
    $j=0; 
    while ($cursor != 0) 
    { 
     $params = array(
      'screen_name' => $auth_user_screen_name, 
      'count' => 200, 
      'cursor' => $cursor 
     ); 

     $json = $objTwitter->friends_list($params); 
     $httpStatus = $json->httpstatus; 

     $jsonFriends=(array)$json; 

     //meta is user defined key 
     $friendsData['meta']['remaining']=$jsonFriends['rate']['remaining']; 
     $friendsData['meta']['seconds_to_reset']=($jsonFriends['rate']['reset'] - time()); 

     if ($httpStatus == 200) { 

      echo "remaining requests " . $jsonFriends['rate']['remaining'] . '<br>'; 
      echo "next reset after (sec) " . ($jsonFriends['rate']['reset'] - time()) . '<br>'; 

      $lenght = count($jsonFriends['users']); 

      $cursor = $jsonFriends['next_cursor']; 
      echo "next_cursor=>" . $cursor . "<br>"; 

      $i = 0; //loop counter 


      while ($i < $lenght) { 

       $friendsData[$j]['screen_name']=$profileScreenName = $jsonFriends['users'][$i]->screen_name; 
       $friendsData[$j]['name']=$profileFullName = $jsonFriends['users'][$i]->name; 
       $friendsData[$j]['location']=$profileLocation = $jsonFriends['users'][$i]->location; 
       $friendsData[$j]['description']=$profileDescription = $jsonFriends['users'][$i]->description; 
       $friendsData[$j]['followers_count']=$followersCount = $jsonFriends['users'][$i]->followers_count; 
       $friendsData[$j]['friends_count']=$friendsCount = $jsonFriends['users'][$i]->friends_count; 

       $friendsData['']=$language = $jsonFriends['users'][$i]->lang; 
       $friendsData['']=$profileTwitterId = $jsonFriends['users'][$i]->id; 
       $friendsData['']=$isVerified = $jsonFriends['users'][$i]->verified; 
       $friendsData['']=$joinDate = date('Y-m-d H:i:s', strtotime($jsonFriends['users'][$i]->created_at)); 
       $friendsData['']=$userWebsiteUrl = $jsonFriends['users'][$i]->url; 
       $friendsData['']=$tweetsCount = $jsonFriends['users'][$i]->statuses_count; 

       $friendsData['']=$defaultProfileImage = $jsonFriends['users'][$i]->default_profile_image; 

       $friendsData['']=$favouritesCount = $jsonFriends['users'][$i]->favourites_count; 
       $friendsData['']=$isGeoEnabled = $jsonFriends['users'][$i]->geo_enabled; 
       $friendsData['']=$utcOffset = $jsonFriends['users'][$i]->utc_offset; 
       $friendsData['']=$timeZone = $jsonFriends['users'][$i]->time_zone; 


       $i++; //counter for friends in particular cursor 
       $j++; //counter for friends for all friends including all cursor requests 

      } 

     } else { 
       //if httpStatus other than 200 
      $friendsData['meta']['error_code']=$errorCode = $jsonFriends['errors'][0]->code; 
      $friendsData['meta']['error_message']=$errorMessage = $jsonFriends['errors'][0]->message; 


      echo "<pre>"; 
      //print error and rate data 
      print_r($friendsData['meta']); 


     } 
     // check whether Api limit exceed 
     if ($friendsData['meta']['remaining']==0) 
     { 

      echo "<br>please wait=>".$friendsData['meta']['seconds_to_reset']." seconds"; 
      break; 
     } 

    } 
    echo "<pre>"; 
    print_r($friendsData); //print all friends data including errors if any 

    } 
} 


//call function to fetch all friends 
//only max 3000 friends will retrieved in single request 
getAllFriends('myUsername');