[HELP] Using PHP to Get list of tweets and retweet most recent

tripper,
Sorry, I'm really really new to this so I apologize for all the questions. I'm not coding an app, this is a PHP script with no user interface -- it's not an app that asks me to verify that I want to allow twitter access, yada yada.

Is there a scripting way to generate this authorization?
 
No need to apologize. Just keep all the help in mind and share your knowledge in the future like we did. :)

Read Post #9, I explained it there.
An app is nothing more than a script. To use the twitter api you need to register an app and every account you want to retweet to has to grant this app the rights to post to their timeline. During this authorization you will get the desired keys, save them and use them like kboing and I did in our examples.
Just google for oauth/authorize and look out for some example scripts, you should get everything done with copy and paste.
 
Thanks again. I'm making progress (and once I have this working, I will post the entire code for the community.

I have the entire code working, to a point, right now -- here's the core of what I have:


Code:
//CHECK THE TWEET ID OF THE MOST RECENTLY SENT TWEET
$logfile = 'last_send_tweetID.txt';
$f = fopen($logfile, 'r');
$lasttweetID = fgets($f);
fclose($f);

//GET MOST RECENT TWEET FROM DONOR ACCOUNT, EXCLUDE RETWEETS AND REPLIES  
$notweets = 1;
$ignore_replies = true; // Ignore replies from the timeline. (Default : false)
$include_rts = false; // Include retweets. (Default : false)
$twitteruser = "DONOR ACCOUNT HERE";

//SET USER KEYS (based on tmeyertweets twitter account)
$consumerkey = "xxxxxxxxxxxxxxx";
$consumersecret = "xxxxxxxxxxxxxxxxxxxx";
$accesstoken = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
$accesstokensecret = "xxxxxxxxxxxxxxxxxxxxxxxxxxx";

// DECLARE FUNCTION
function getConnectionWithAccessToken($cons_key, $cons_secret, $oauth_token, $oauth_token_secret) {
  $connection = new TwitterOAuth($cons_key, $cons_secret, $oauth_token, $oauth_token_secret);
  return $connection;
}

// MAKE CONNECTION, GET MOST RECENT TWEET
$connection = getConnectionWithAccessToken($consumerkey, $consumersecret, $accesstoken, $accesstokensecret);
 
$tweets = $connection->get("https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=".$twitteruser."&count=".$notweets."&include_rts=".$include_rts."&exclude_replies=".$ignore_replies);
 
$tweetData = json_decode(json_encode($tweets), true);



//CHECK TO SEE IF MOST RECENT TWEET IS NEWER THAN MOST RECENTLY SENT RETWEET

if ($lasttweetID<$tweetData[0]["id_str"])
    {
    //SEND THE RETWEET
    // Create object
    $tweet = new TwitterOAuth($consumerKey, $consumerSecret, $accessToken, $accessTokenSecret);
  
    // POST REWEET

    $retweetResult = $tweet->post('statuses/retweet/'.$tweetData[0]["id_str"]);


    // UPDATE THE LASTTWEETEDID file
    $f = fopen($logfile, 'w');
    fwrite($f, $tweetData[0]["id_str"]);;
    fclose($f);
    }
    else
    {
    // LOG THAT NO TWEET WAS DONE
    $logoutput = "There is NO new tweet available.\r\n";
    $file2 = 'retweet_log.txt';
    file_put_contents($file2, $logoutput, FILE_APPEND | LOCK_EX);
    }

Two things still perplex me (going to work on them today and tonight):

a) How would I ALSO favorite this tweetID? I've gone to the twitter api 1.1 page and copied exactly the syntax, replacing 'statuses/retweet/' with 'favorites/create/' but that doesn't seem to work.

b) Assuming I do a FOR loop, how do I get access keys for additional users. To get my original set of access keys I needed to create an APP on dev.twitter.com. That I understand. What I'm not sure about is how to proceed with having multiple users use this app. I think ALL users can use the same consumer keys but each user needs unique access tokens? Is this correct? If so how do I generate those tokens? (obviously once generated I can store them in a CSV and load them when needed).
 
@a: Print out the your variable (e.g. $retweetResult) to get some status informations. There should be an error message

@b: You're right about the consumer keys. To get access tokens for each user you need to grant the app the rights to post on the account's behalf. Read about oauth/authorize and do it for every account you want to use.
 
Okay, I've got my homework for tonight, I'll get reading about and tinkering with oAuth/Authentication.

In terms of the 'retweet and favorite' thing. Here's the code:

Code:
// Create object
$tweet = new TwitterOAuth($consumerKey, $consumerSecret, $accessToken, $accessTokenSecret);
  
$postID = "382904915707691008";
 
// Post the retweet

$retweetResult = $tweet->post('statuses/retweet/'.$postID);

$favoriteResult = $tweet->post('favorites/create/'.$postID);

var_dump($retweetResult);
echo "</p>";
var_dump($favoriteResult);

The retweet executes properly and returns the big array of information you'd expect from a sucessfull POST action.

The favorite fails and returns this:
Code:
object(stdClass)#18 (1) {   ["errors"]=>   array(1) {     [0]=>     object(stdClass)#19 (2) {       ["message"]=>       string(31) "Sorry, that page does not exist"       ["code"]=>       int(34)     }   } }

Looking at the API 1.1 pages on twitter this should work, the call is indentical to the retweet call in syntax and format, except with favorites/create inplace of statuses/retweet. But I guess there's some nuance I'm missing?
 
It's not the same format.
The retweet uses statuses/retweet/id while the favorites use favorites/create and you have to send the ID as POST data.
PHP:
<?php
$tweet->post('favorites/create',array('id'=>$postID));
?>
 
Well, you don't need me to tell you this, but that worked. :)

I'm knee deep in OAuth and completely baffled but I'm going to work on it a bit and try to come here with intelligent questions rather than 'Can you explain this to me?!' -- I could have hired someone to write this code, the whole point for me was actually learning something and you're really helping with that so thanks!
 
Okay, from what I am understanding, I need to do two separate things.

Part 1 - get access tokens for each user who will use the program and store them in a file. Not sure how to do this as yet so moving on to part 2.

Part 2 - within my retweet script, cycle through a CSV and create a new connection using the Consumer Key / Consumer Secret of the APP that I made at dev.twitter.com and the Access Tokens previously generated in part #1.

Assuming I have stored the access tokens in a CSV in the 3rd and 4th field, would something like this work?

Code:
$row = 1;
if (($handle = fopen("retweets.csv", "r")) !== FALSE) {
    while (($userdata = fgetcsv($handle, 1000, ",")) !== FALSE) {
        $num = count($userdata);
        $row++;
    // Create object for each user where $userdata[3] and [4] are access keys specific to each user
    $tweet = new TwitterOAuth($consumerKey, $consumerSecret, $userdata[3], $userdata[4]);
    $postID = "382485048274202624";
    // Post the retweet
    $retweetResult = $tweet->post('statuses/retweet/'.$postID);
    }
    }
 
Sadly, if you gonna post to several accounts from the same IP adress that can be easily detected as spam.
There are two solutions around this. You can use private proxies to hide your original IP. Or, you can install as many instances of your script to different domains as many user accounts you want to use. Both solutions raises the price of the experiment.
 
Back
Top