How To: Write a RTing Twitter bot in PHP

File this one under “stuff I’ve been meaning to look up for ages”: yesterday I finally sat down and wrote a Twitter-bot. You know the kind – a dedicated account that looks for updates containing a certain word or phrase, then retweets them – I often end up being tweeted by @redscarebot, for example.

Anyhow, here’s how to write your own, in just a few lines of PHP. You’ll need:

1) A server running PHP and MySQL (I set up an Appfog instance)

2) A Twitter account to post from, with a mobile phone number entered in settings

3) A computer somewhere to execute the script every X minutes via CRON

So, with all that in place: download and extra the TwitterOAuth library, then start a new PHP file. Require it:

require "twitteroauth/autoloader.php";
use Abraham\TwitterOAuth\TwitterOAuth;

Register an app at, then define the secrets required to access the API in your code:

define('CONSUMER_KEY', 'here');
define('CONSUMER_SECRET', 'here');
define('ACCESS_TOKEN', 'here');
define('ACCESS_TOKEN_SECRET', 'here');

Define your connection:


And then you’re ready to make a call to the Twitter API. You’ll probably want to search:

$sstring = '"sleepy cats" OR kittens';
$searchresult = $twitter->get("search/tweets", array("q" => urlencode($sstring), "since_id" => $since, "count" => 100, "result_type" => "recent"));

Note the variable $since – this is the ID of the last tweet processed by the bot on its last execution, used to prevent retweeting the same stuff over and over. Store and retrieve it from MySQL.

You know have $searchresult, and you’ll want to get the tweets out of it:

foreach($searchresult as $tweet) {
$tweettext = $tweet->text;
$tweetid = $tweet->id;

.. and you can do whatever you want with those. Want to post a message, probably created by trimming and formatting selected content from the search output? If you have your message in $somestatus

$postthis = $twitter->post("statuses/update", array("status" => $somestatus));

.. and that’s about it. Update your $since ID in MySQL, and close up the PHP file. Call it by CRON every X minutes to check for and retweet new messages.

This is only just barely scratching the surface, of course. Each tweet object contains loads of information that you can process to do more interesting things – see the API reference for details.