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

New Topic/Question



MultiQuote








|