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

eqpaisley

Junior Member
Joined
Oct 16, 2012
Messages
178
Reaction score
50
Hi all. I've been teaching myself PHP in order to make a personal (not selling) retweet cron job.

I am using Abrahams twitteroauth library and keys/tokens I generated.

I am having no problem retrieving a list of recent tweets from the donor account and no problem going through that list, ignoring retweets and replies.

What I'm stuck on is this:

How do I cycle through a list of several accounts (store in a CSV file) and retweet a given tweetID?

Does each account need its own keys/codes or can I use one twitter app for this?

Why is there so little good documentation on the twitter api and php for posting retweets?

Thanks - current code below
EQP

PHP:
<?php

date_default_timezone_set('America/New_York');
session_start();
require_once("twitteroauth.php"); //Path to twitteroauth library
 
$twitteruser = "CPlusPainter";
$notweets = 10;
$consumerkey = "xxxxxxxxxxxxxxxxxx";
$consumersecret = "xxxxxxxxxxxxxxxxxxx";
$accesstoken = "xxxxxxxxxxxxxxxxxxxxxxxxxx";
$accesstokensecret = "xxxxxxxxxxxxxxxxxxxxxxxx";
 
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;
}
 
$connection = getConnectionWithAccessToken($consumerkey, $consumersecret, $accesstoken, $accesstokensecret);
 
$tweets = $connection->get("https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=".$twitteruser."&count=".$notweets);
 
$tweetData = json_decode(json_encode($tweets), true);


foreach ($tweetData as $tweet) {
  echo '<br/>ID: ' . $tweet['id_str'];
  echo '<br/>Tweet: ' . $tweet['text'];

   $retweet = $tweet['retweeted_status'] != NULL ? TRUE : false;
   $reply = $tweet['in_reply_to_status_id'] != NULL ? TRUE : false;
 
   echo "<br/>reply " . $reply;
   echo "<br/>retweet " . $retweet;


echo "</p>";
}
?>
 
To cycle through a list of accounts from a CSV you'd have get the account data from the CSV into an array. You'd then loop through that array as many times as needed.

You don't need individual API keys for each account. Your API keys are for an app and that app can have several hundred users

I believe the APIs have good documentation. They're just hard to understand because you're new to PHP and APIs in general. If you need help there are tons of 3rd party resources online, a quick search should have answers.

I'm on my phone so I don't have time to look at your code so if you still need help I can take a look at it when I get back home to get an idea of what part you might need some help on.
 
Thanks so much for your reply. I suspect you're right, it's not the documentation, it's my experience that makes it all look tough.

Here's the process, as I see it:
a) Check a twitter account for newest non-retweet, non-reply tweet. -- DONE
b) Load a CSV into an array -- DONE
c) Do a FOR LOOP for each CSV account that will retweet to post the retweet to their own twitter account --- NOT DONE

for this step, I need to examine some parts of the CSV, determine which accounts are valid for retweeting and then retweet from them after a short delay (to mimic human behavior).

I assume for this I will need to pass a tweet ID to this part of the PHP file. What I don't understand is how to authenticate each user and then send the tweet. The code I have for getting the tweets from the original/donor account doesn't seem to need an actual login.

c) Set up cron job to run this php every hour and send a log file of the results once a day --- DONE
 
Okay, it seems like you have the logic done, you just need some direction. PM me so when I get back home I won't forget to look over your code and help you out.
 
new code sample -- returns the most recent tweet that is not a reply or a retweet-- both the text of the tweet and the ID.

What I need to do now is a FOR loop that cycles through a CSV and retweets this tweet ID (based on a couple of simple criteria).

Thanks for the help.

PHP:
<?php

date_default_timezone_set('America/New_York');
session_start();
require_once("twitteroauth.php"); //Path to twitteroauth library
 
$twitteruser = "tmeyertweets";
$notweets = 1;
$ignore_replies = true; // Ignore replies from the timeline. (Default : false)
$include_rts = false; // Include retweets. (Default : false)
$consumerkey = "-------------------------";
$consumersecret = "--------------------------";
$accesstoken = "----------------------------------------";
$accesstokensecret = "------------------------------------";
 
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;
}
 
$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);


foreach ($tweetData as $tweet) {
  echo '<br/>ID: ' . $tweet['id_str'];
  echo '<br/>Tweet: ' . $tweet['text'];

echo "</p>";
}
?>
 
I was just taking a look at your code and adding some things and I ran into something that could possibly render your bot impractical.

In order to gain the permissions to post to an account the user must MANUALLY log in on the actual twitter website. This is not something you can easily do with PHP.

If you're up for the challenge you could basically code an app. Then code a script that'll automate the app.

PHP just makes it harder, but it's possible. With a different programming language it might be easier.
 
Hmmm. I encounter websites all the time that will POST for you if you give them permission. What you're saying is they don't use PHP but some other programming language? I guess I could teach myself something simple like visual basic and work it that way but - honestly - i was hoping for a solution that was cron-able and not reliant on me having my CPU powered on.

Something I could set to go, get a log file once a day letting me know it was working.
 
Hey there, not to second guess you because I am a total novice here but I found this:
PHP:
$response = $tmhOAuth->request('POST', $tmhOAuth->url('1.1/statuses/update'), array(

  'status' => 'Test message. Lorem ipsum.'

));

This uses a different library than I use but it appears to be possible to tweet from PHP using this POST method. Wouldn't that also mean retweeting is possible?

I found this snippet on twitters api web site, thought it's all a bit confusing to me.

PHP:
 https://api.twitter.com/1.1/statuses/retweet/241259202004267009.json

http://www.webmaster-source.com/2013/01/09/post-to-twitter-from-a-php-script-2013-edition/
 
You need to set up an application on twitter and every account has to grant this app the right to tweet on their behalf. This is the very first step that has to happen (yeah, you could get credentials for every account and do the login via curl, but that's way more difficult and error prone).

You already have the code to get the desired tweets, so the last part to get your idea working is to cycle through a list of accounts that granted you the rights (either your cvs file or some other data source where your app saved the accounts) and post the retweet.

So read about creating a twitter application, oauth/authorization and granting rights to twitter apps. It's not that difficult, there should be enough examples to copy and paste what you need.
 
I've created the app already, I'm using the consumer / access codes and tokens which are required to GET the status in the first place.

What I'm not clear on is how I use those code to make a POST request. I have the GET request coded and working (as you see in the code above). I put 'xxxxxxx' in as my keys to hide them from public view but in my actual file they are correct and working.

What I'm struggling with is making the POST using the twitteroauth and oauth library I've already loaded.
 
To post the tweet you need to connect to twitter using the credentials of the account you want to use, just like you did to get the tweet in first place.
PHP:
//line from your code:
$connection = getConnectionWithAccessToken($consumerkey, $consumersecret, $accesstoken, $accesstokensecret);

//line to retweet:
$var = $connection->post('statuses/retweet/'.$tweet['id_str']);
 
Okay, makes sense. A couple of followups:

1) if I $somevariable = $connection-> blah blah. do I then need to reference that variable in some way or will the act of assigning it actually execute the retweet?

2) what if I want to do a FOR loop and retweet for 5 accounts, how do I use these same keys for different users?

thanks!
 
1) This variable just stores what ever the connection returns, usually an array with some informations. Might contain some error code if the post fails, but is not necessary for posting.

2) You can't use the same keys for different users. Assign the keys inside the loop.
PHP:
for(...) {
      $accesstoken=getTheAccessTokenFromYourDataSource();
      $accesstokensecret=getThatAccessTokenSecretToo();
      $connection = getConnectionWithAccessToken($consumerkey, $consumersecret, $accesstoken, $accesstokensecret);
      $connection->post('statuses/retweet/'.$tweet['id_str']);
     /* or if you want to get the returned informations
     $var = $connection->post...
     print_r($var);
     */
}
 
hello

info has stored in accounts.txt

PHP:
<?php
require_once('twitteroauth/twitteroauth.php');


$__CONSUMER_KEY="consumer key here ";
$__CONSUMER_SECRET="consumer secret here ";

// load oauth_token,oauth_token_secret,twitter username from file accounts.txt ( possible load from any database ) 
$__f=file("accounts.txt");
foreach($__f as $v){
$__ct=explode(",",trim($v));
$connection = new TwitterOAuth($__CONSUMER_KEY, $__CONSUMER_SECRET, $__ct['0'], $__ct['1']);
  
  
$twitteruser = $__ct['2'];
$notweets = 1;
$ignore_replies = true; // Ignore replies from the timeline. (Default : false)
$include_rts = false; // Include retweets. (Default : false)
$tweets = $connection->get("----------------/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);
foreach ($tweetData as $tweet) {
  echo '<br/>ID: ' . $tweet['id_str'];
  echo '<br/>Tweet: ' . $tweet['text'];
$var = $connection->post('statuses/retweet/'.$tweet['id_str']);
}
}

 ?>
now all time you run a cron job the script loop and update all accounts in file


best
 
hello

the loop is 1 only , this allow modification if need change tweets number , loop stop in this number

Best
 
I meant the outer loop, where you loop through the user accounts.
If you have five accounts inside accounts.txt you will call $connection->get five times - but you only need it once to get the tweet id.
The same applies to the vars $notweets, $ignore_replies and $include_rts, you're assigning them new for every loop.
It's always better to do as few tasks as possible inside of a loop.

PHP:
<?php
require_once 'twitteroauth/twitteroauth.php';
$twitteruser = 'CPlusPainter';
$notweets = 1;
$consumerkey = 'xxxxxxxxxxxxxxxxxx';
$consumersecret = 'xxxxxxxxxxxxxxxxxxx';
$accesstoken = 'xxxxxxxxxxxxxxxxxxxxxxxxxx';
$accesstokensecret = 'xxxxxxxxxxxxxxxxxxxxxxxx';

$connection = new TwitterOAuth($consumerkey , $consumersecret , $accesstoken,$accesstokensecret);
$tweets = $connection->get('https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name='.$twitteruser.'&count='.$notweets);
$tweetData = json_decode($tweets, true);
$retweetId=$tweetData[0]['id_str'];

 // load oauth_token,oauth_token_secret,twitter username from file accounts.txt ( possible load from any database ) 
$lines=file('accounts.txt');
foreach($lines as $line) {
     $data=explode(',',trim($line));
     $connection = new TwitterOAuth($consumerkey , $consumersecret , $data[0],$data[1]);
     $var = $connection->post('statuses/retweet/'.$retweetId);
}

 ?>
 
he get $twitteruser from csv , in your example you get only last tweet from 1 id only !
 
That's what he wanted, as far as I understand. He wants to retweet a single post to the accounts from his csv.

In your example he connects as account1, gets the latest tweets that account1 posted and retweets them as account1. That's not very effective.

Don't get me wrong, I like that you're trying to help and I don't want to make you look bad. :) But I think your example doesn't work the way the OP wants it.
 
Thanks for the code, this is moving me in the right direction. TripperJohn is right, the code you posted (while excellent and useful) has me getting a userID from the text file, findind that users most recent tweet and then THAT SAME user tries to retweet his own most recent tweet.

It's an easy adjustment though. $twitteruser for retrieving the most recent tweet will be a static value declared up top and $retweetinguser can be stored in the file and read in.

I see that I can reuse Consumer Keys but not the access keys? How do I get access keys for each individual user?
 
Back
Top