3 Replies - 35871 Views - Last Post: 24 July 2010 - 11:29 PM Rate Topic: -----

#1 no2pencil  Icon User is online

  • Head MFIC
  • member icon

Reputation: 5061
  • View blog
  • Posts: 26,433
  • Joined: 10-May 07

[PHP] Building Automated Twitter Bot with Twitters API functionality

Post icon  Posted 04 June 2009 - 08:46 PM

Building a Twitter Bot : by #2pencil
Written for Dream In Code : 06.04.2009

Twitter... the final frontier!

Ok, so maybe that's going a bit overboard, but you can't deny that it is currently one of the hotest web sites out there right now.

So, to build a Twitter bot, isn't hard, & by the end of this tutorial, hopefully I will have successfully conveyed to you how to get your own automated Twitter service up & running.

We really need 3 things :
1.) Text (less than 140 Characters of Text)
2.) A Server Side Language (this tutorial uses PHP)
3.) A timer

*Part 1* The text

There wouldn't really be much to Twitter without the text now, eh? So for an automated service, we need to stash that text somewhere. At 1st I spend all of my time stuffing text into a database, but that got boring & easily expected. So I decided to go all 'Grant Imahara' & create my own robot style text app. It's really just like mad libs, but you can throw some other random tricks into your mix.

In our 1st example, we'll build a random tweet. That is, gibberish to be posted onto Twitter. It will be held in a function called RandomTweet that take the login as an argument, & then calls SendTweet, the meat of the Twitter automated functionality.

<?php
 /*
  *
  * Building the Tweet *
  *
  */
  
function RandomTweet($login) {
   $MAX=6; // Build the color array
   $color= array ("red", "blue", "green", "orange", "white", "purple", "pink");
   $rnd_color=rand(0,$MAX); // Get a random value
   $tweet="By far, my favorite color is ".$color[$rnd_color]; // built the tweet
   sendTweet($login,$tweet); // Upload to twitter
}
?>



Feel free to get creative :)

Moving on, we'll get into the server side functionality. In order to involk the Twitter API through PHP, we use CURL. So if you don't have the CURL library installed, now would be the time to be doing that!

For reference, the full Twitter API can be referenced here.

The Twitter API update will require that we are authenticated. So to do so we'll request the login $username:$password to be sent to the function. It's my personal preference to build the variable $login & simply pass that to the functions that require the login credentials. & of course, our 2nd requirement is the tweet text itself.


<?php
 /*
  *
  * Sending the Tweet *
  *
  */

  // $login is build with $username.":".$password 
  // for example no2pencil:secret
  
function sendTweet($login,$tweet){
   // It's important to note the Twitter limit of 140 characters
  if(sizeof($tween) > 140) { 
	die("Twitter Limit is 140!");
  }
  $url = 'http://twitter.com/statuses/update.xml'; // Assign the variable $url with the update API call
  $curl_handle = curl_init();					  // Initilize curl handle
  curl_setopt($curl_handle, CURLOPT_URL, $url);	// Send the URL
  curl_setopt($curl_handle, CURLOPT_POSTFIELDS, "status=".$tweet);  // Add our tweet
  curl_setopt($curl_handle, CURLOPT_USERPWD, $login); // Authenticate

  $buffer = curl_exec($curl_handle);			   // Gather the results into $buffer
  curl_close($curl_handle);
  if (empty($buffer)) {							// Check for failure & report
	die('Buffer Failure');
  }
}
?>



That's it! At this point you should have your update.

Now to make this is a full time gig, we simply need to make a timer. For my timer I've opted to use cron jobs. I built a shell command that calls curl to the PHP page via an cron job that executes in 1 hour increments. It's important to not over-do it with your Twitter account, unless you are trying to get it closed down as per the Rate Limits. Some commands (as per the reference above) are limited to their hourly usage, while others are not.

Some other interesting functions :

<?php
 /*
  *
  * Gathering a Random Follower *
  *
  */

function fetch_random_follower($login) {
	$ch = curl_init();			   // Init curl
	$target = 'http://twitter.com/statuses/followers.xml';  // Twitter API
	curl_setopt($ch, CURLOPT_URL, $target); 
	curl_setopt($ch, CURLOPT_USERPWD, $login); // Authenticate
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
	$str = curl_exec($ch);
	preg_match_all('#<screen_name>([^<]+)</screen_name>#', $str, $matches); // Scrape screen_name entries
	$i=0;
	foreach($matches[0] as $k -> $match) {  // Build an array of your followers
	  $i++;
	}
	if($fetch > 1) {
	  die('Your account does not support adding more than 1 follower per hour.');  // Uh oh, you've over done it!
	}
	echo "<p>You have ".$i." followers!</p>";  // Show the amount of followers
	$random_follower=rand(0,$i-1); // Pick a follower... any follower
	$random_twitter=strip_tags($matches[0][$random_follower]); // Grab just the name, not the entire XML string!
  return $random_twitter; // Paydirt!
}

function findFriends($login,$random_twitter) {
	// Lets make some friends!
	$ch = curl_init(); // Init
	$target="http://twitter.com/statuses/friends/".$random_twitter.".xml"; // Twitter API
	curl_setopt($ch, CURLOPT_URL, $target);
	curl_setopt($ch, CURLOPT_USERPWD, $login); // Authenticate
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
	$str = curl_exec($ch);  
	curl_close ($ch);
	preg_match_all('#<screen_name>([^<]+)</screen_name>#', $str, $matches); // Scrape the screen_name values
	$i=0;
	foreach($matches[0] as $k -> $match) { // Build the array
		$i++;
	}
	if($i > 2) {
		/* Now that we have our random user, randomly grab one of their followers, & follow them */
		echo "<p>".$random_twitter." has ".$i." followers...impressive!</p>";
		$random_follower=rand(0,$i-1);
		$random_twitter=strip_tags($matches[0][$random_follower]);
		echo "<p>I would very much like to follow ".$random_twitter."</p>";
		$ch = curl_init();
		//$target="http://twitter.com/notifications/follow/".$random_twitter.".xml";
		$target="http://twitter.com/friendships/create/".$random_twitter.".xml?follow=true";
		
		curl_setopt($ch, CURLOPT_VERBOSE, TRUE);
		curl_setopt($ch, CURLOPT_NOBODY, FALSE);
		curl_setopt($ch, CURLOPT_HEADER, TRUE);
		curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
		curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 2);
		curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
		curl_setopt($ch, CURLOPT_POST, TRUE);
		curl_setopt($ch, CURLOPT_URL, $target);
		curl_setopt($ch, CURLOPT_USERPWD, $login);
		$str = curl_exec($ch);
		echo "<p>Sending ".$target." returns : </p><p><pre>".$str."</pre></p>";
		curl_close ($ch);
	}
	else {
		echo "<p>".$random_twitter." does not have enough friends worth following...poor bastard!</p>";
	}
}
?>



In all of my examples, when pulling back the results from curl, I've sent XML requests to the Twitter API. This isn't the only option. You can send a request for either XML or JSON formatted results.

Now you've got all the tools to get your Twitter account automated. Be adviced, no one is going to find it as cool as you do. Some friends will get tired of your constant updates & ramblings. But the more random, the more fun :)

To see this Twitter Bot in action (along with other functionality :) ) feel free to check it out at : http://twitter.com/yardsalesgalore!

Is This A Good Question/Topic? 1
  • +

Replies To: [PHP] Building Automated Twitter Bot with Twitters API functionality

#2 gabehabe  Icon User is offline

  • GabehabeSwamp
  • member icon




Reputation: 1376
  • View blog
  • Posts: 10,951
  • Joined: 06-February 08

Re: [PHP] Building Automated Twitter Bot with Twitters API functionality

Posted 28 July 2009 - 02:39 AM

You don't have to use CURL. I did this before, it's pretty simple:

<?php
	$username = "gabehabe";
	$password = "password";
	$tweet = "Tweeting from PHP is simpler than @akroncdnr's tutorial. :)/>";
	$params = array("http" => array(
					"method" => "POST",
					"content" => "status=" . urlencode($tweet)
					));
	$ctx = stream_context_create($params);
	$fp = fopen("http://$username:$password@twitter.com/statuses/update.xml", 'rb', false, $ctx);
?>

Was This Post Helpful? 0
  • +
  • -

#3 lansa  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 3
  • Joined: 01-September 09

Re: [PHP] Building Automated Twitter Bot with Twitters API functionality

Posted 01 September 2009 - 11:12 PM

This not working..

<code>
foreach($matches[0] as $k -> $match)
</code>
Was This Post Helpful? 0
  • +
  • -

#4 Valek  Icon User is offline

  • The Real Skynet
  • member icon

Reputation: 541
  • View blog
  • Posts: 1,708
  • Joined: 08-November 08

Re: [PHP] Building Automated Twitter Bot with Twitters API functionality

Posted 24 July 2010 - 11:29 PM

Gravedig, I know, but for future reference, it should be $k => $match, not $k -> $match). '->' is an object operator. '=>' is used with key => value pairs.
Was This Post Helpful? 1
  • +
  • -

Page 1 of 1