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

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.



Tags: ,

Friday, January 27th, 2012 Hacks, PHP, Thoughts

You might also like

Twitter Bots is the future of Twitter monetization A question of Twitter monetization has been around for a while, but nobody seems to have an idea of how...
Why you don’t need to have a website today unless you are a corporation When I see people looking to create their website I start to smile. Little do they know that after spending...
Desktop website performance tool – Apache JMeter Just a post ago i was wondering about testing my website's performance under heavy load and did this...
Observation point right near Reagan National Airport During my recent visit to Washington, DC friends took me to this spot right near Reagan National Airport....

No comments yet.

Leave a comment

About


Oleksiy Deverishchev is a freelance web developer living in New York City. In this blog he shares his experience with various gadgets and web technologies.

He is available for the following gigs:
  • Microsoft Access projects
  • website design and re-design services
  • php/MySQL developement
  • Java and Grails development
  • virtual private server (VPS) migration, setup and tune-up

For more information and hiring availability please send an email to alex@webandblog.com

Advertisment

Read more

Recent works / current clients

  • BellatAuto Inc - New York / New Jersey used car auto dealer: design and coding.
  • Colette Maison Lumiere - multimedia artist: design and coding for the CMS.
  • Complete Body & Spa - New York City personal training and gym management company: Wordpress template coding.
  • DaleStyle Blog Dale Sudakoff’s fashion blog: Wordpress template coding.
  • DoctorKalitenko.COM - Sergey Kalitenko : antiaging hollistic doctor performing bioidentical replacement therapy. CMS coding and design.
  • Great Jones Spa - premiere New York City Day Spa: coded and designed website and storefront

I am a Freelancers Union Member

Freelancers Union Member Badge