Writing Twitter Bot, the “intellectual one”, in php

Hacks PHP Thoughts

What is Twitter? For many it is a place to brag about everyday life events and post pictures. Some use it to promote themselves, corporations and alikes try to provide “customer service” using Twitter and other folks are doing all sorts of things from selling knock-offs to completely illegal stuff.

This article is about how you can use Twitter to promote a site, service or anything you’d like to the tweeps.

It is apparent, that searching for a keyword or a key phrase and responding to all of those would take a lot of time, so we are going to use automated scrip (a twitter [ro]bot), which will do all the job for us.

To write it, first grab Twitter oAuth library for php by Abraham Williams. We will need two files from it –

  • OAuth.php
  • twitteroauth.php

to reside in the same folder as our script. Also, go ahead and create a file with the name ‘last_tweet_number.log’ and put 0 inside of it (a zero).

The twitter bot example used here is something I have used while promoting my www.findroomrent.com.

The idea behind robot script is simple : we will search for people sending tweets with the following “looking OR need for roomie OR roommate” and respond to them with the random string out of the array with possible answers. Some of our answers are funny and some promote website to the user.

Here is the code:


$query = 'looking OR need for roomie OR roommate';
$file_name = 'last_tweet_number.log';
// Create our twitter API object
require_once("twitteroauth.php");
// go to https://dev.twitter.com/apps and create new application
// and obtain [CONSUMER_KEY], [CONSUMER_SECRET], [oauth_token], [oauth_token_secret]
// then put them in place below
$oauth = new TwitterOAuth('[CONSUMER_KEY]', '[CONSUMER_SECRET]', '[oauth_token]', '[oauth_token_secret]');
// Send an API request to verify credentials
$credentials = $oauth->get("account/verify_credentials");
// Make up a useragent
$oauth->useragent = 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.9) Gecko/20071025 Firefox/3.6.0.9';
$remaining = $oauth->get('account/rate_limit_status');
// make sure we are banned by asking how many API hits we can make
echo "Current API hits remaining: {$remaining->remaining_hits}.\n";
// to prevent bot from responding to the same tweets over and over again
// we keep the since_id saved and pass it along when we search
$since_id = file_get_contents($file_name);
$tweets_found = $oauth->get('http://search.twitter.com/search.json',
array('q' => $query, 'since_id' => $since_id))->results;
// if a more recent tweet has appeared, store this tweet's id in the file
if (isset($tweets_found[0])) {
	file_put_contents($file_name, $tweets_found[0]->id_str);
}
foreach ($tweets_found as $tweet){
	$user = '@' . $tweet->from_user;
	echo $tweet->from_user . " says: ".$tweet->text."\r\n";
	$statuses = array (
	" we might be able to help - check out our website, lmk if your city is not listed",
	" awesomeeeeeeeeeeeeeeeeee",
	" what about putting an ad on findroomrent.com ?",
	" looking for a roomate? we can help" ,
	" we have some listings on our website, if you don't mind checking it out",
	" lmk, we can help, just put an ad in",
	);
	$status = "$user".$statuses[array_rand($statuses)];
	// do not respond to RT - retweets
	if (!startsWith($tweet->text,"RT")) {
echo "We responded: " . $status;
$oauth->post('statuses/update', array('status' => $status, 'in_reply_to_status_id' => $tweet->id_str));
	}
	// to simulate real person's behavoir make script pause for a while
	sleep(rand(120, 480));
}

// handy function for RT search
function startsWith($haystack, $needle)
{
    $length = strlen($needle);
    return (substr($haystack, 0, $length) === $needle);
}

That’s about it. Let me know, how it worked for you.

UPDATE: With a lot of commenters asking why the script seems to be working, but no tweets appear – make sure you change default application settings in the Twitter DEV site to allow read & writes as it puts into the read only mode by default!

A thought: With this bot being blocked by Twitter quite fast, I am looking to re-write it to mimic actual human behavior where it not only tweets responses but also says some random things.

6 Comments

Leave a Reply to Mr M Cancel reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.