Create Your Own Automated Twitter Robot in PHP

This is just a mockup, a simple prototype, which is way too fresh for any actual use. Steps are as follows: 1) Authentication 2) RSS lookup 3) Parsing 4) Thanking for retweets 5) Shooting random stuff at people that mention your robot.

Create a Tweeter feed Clone in PHP Platform: - All this is going to be setup on a linux box running crond and acting every 15 minutes or so Here’s a brief list of features we will implement: * Runs in console, no HTTP access * Authentication via OAuth, tweeting via OAuth * RSS lookup, parsing, forming tweets in bound of 140 characters including a postfix (hashtag or RT) * Tweeting ‘thank you for retweeting’ to users that retweet the robot * Following people that retweet the robot * Acting strange on users that mention the robot

Make sure you pick Read and Write access as our robot will use POST calls to update its status. don’t lose your Consumer key and Consumer secret – we’ll be using those in our app for identity. Make sure you install everything right – the magpie functions work. Create a new PHP file .net/curl For Twitter OAuth Class: . 1) One will be running every 15 minutes. Now. curl functions are available and the Twitter OAuth class is Authentication: Storing the Access Tokens We’ll divide our application in two parts. Curl to access the Twitter API and the Twitter OAuth Class which is dependent on the Curl functions. Also note that we’re preventing all HTTP access to the robot control.http://github. Note that you can ask Twitter to reset the values for you in case somebody got unwanted access to them.http://ru2. so make sure you pick Client application and not web. Browse to the Twitter OAuth Clients page (assuming you’re logged into Twitter) and register a new application.php. For Magpie RSS: .net/ For Curl: . plus we’re making a personalized robot. Don’t give them out to anybody you don’t trust unless you’d like people tweeting “from YourApp”. What you also need is a login and API key :Click here: . so the ‘from’ string in the tweets is a must). The request and access URLs are not important. they’re the same for everyone. 2) Second one will run once for authentication.http://magpierss. Setting up the Environment We will be using Magpie RSS to parse RSS feeds.Registering an App at Twitter OAuth Clients This is mandatory if we’re using OAuth (don’t go with basic authentication because Twitter will be closing that down sooner or later. thus we’ll be using PIN based OAuth.

Like this: # php oauth.Automated Serverside Tweeting Using OAuth http://kovshenin. identified as @twittername .com/archives/automatic-tweet-oauth/ Twitter API: PIN-based OAuth Using PHP oauth_token=whatever # php oauth.php validate 123456 Access tokens stored.php register Request tokens aquired. proceed to this link: What’s important here is that oauth.php will run on its own and will accept parameters via command line.

Say files as access_token and access_token_secret. The main point of this file is to get your access tokens written to disk. . tweet the names! } elseif ($action == "reply") { // Read the names. if ($action == "feed") { $feed_name = $argv[2]. through an action parameter passed by the command line. tweet the feeds } elseif ($action == "rthx") { // Read the names..php reply Writing strange stuff to peoples that mentioned you. Say something! } So the robot control will look something like this: # php robot.Make sure your control flows similar to this: $action = $argv[1].php rthx Thanking peoples for the retweets and following them all # php robot. otherwise ask for registration. umm. // Read the feeds. If the files are present. Feeding Twitter from RSS You need to distinguish different actions which the robot is supposed to do.php feed wordpress Feeding your public timeline with wordpress articles # php robot. then your robot will be able to tweet. access tokens are stored somewhere on disk.** So after you’ve validated your OAuth session.

From there on we’ll go with code: // Store the feed settings into $feed $feed = $feeds[$feed_name]. $access_token_secret). $bitly_url = "http://api.1".= "&login=$bitly_login&apiKey=$bitly_key".= "&longUrl=$url_escaped". . $bitly_url . "mashable" => array("url" => "http://feeds2.feedburner. remember? I’m assuming you’ve stored them into $access_token and $access_token_secret respectively and initialized the $oauth object: $oauth = new TwitterOAuth($oauth_consumer_key. $bitly_url . $access_token. // Fetch the feed and store the prefix $rss = fetch_rss($feed["url"]) shortening and then shorten the link // This is the place where you have to use your bit. $oauth_consumer_secret. $url = $item["link"].org/development/feed/". allow spaces and punctuation if (ereg('^[[:alnum:][:blank:][:punct:]]+$'. // Let's make sure our feeds are in English. // Loop through the feed items foreach ($rss->items as $item) { // All simple enough here $title = trim($item["title"]). Make sure that you’ve already written a check for access_token and access_token_secret and gave out an error message if they didn’t exist or were login // And the API key $url_escaped = urlencode($url). We’ll make our robot tweet #wordpress tweets and read out mashable’s website and tweet headlines via @mashable. We cannot tweet without those. The second parameter (“wordpress” in the control above example) would be stored into a $feed_name variable.bit.Define an associative array of feeds: $feeds = array( "wordpress" => array("url" => "http://wordpress. $title)) { // Escape the URL for bit. "postfix" => "via (@mashable)"). $postfix = $feed["postfix"]. "postfix" => "#wordpress"). ).com/Mashable".ly/shorten?version=2.

117else $shorttitle = $title. // Post the message to Twitter $oauth>OAuthRequest('https://twitter. // Add the title to the message $message = $shorttitle.. use them wisely.".120)).com/statuses/update. // Wait a couple of mintes before the next tweet // Don't try and flood Twitter. ". postfix // Form a new message from the short URL and the $message = " $shorturl $postfix".$shortened_url = json_decode(file_get_contents($bitly_url)). // If everything went okay. array('status' => $message). you // Only 150 API calls per hour. go on if ($shortened_url->errorCode == 0) { // Retrieve the shortened url from the json foreach ($shortened_url->results as $key => $shorturl = $value->shortUrl. } } } have . sleep(rand(60. remember. $length = strlen($message).. 0. // We should trim down the title if it's too long // So that our tweets are 120 characters or less if (strlen($title) > 120-$length) $shorttitle = substr($title. object $value) $length) .$message.xml'. 'POST').

if ($since_id > 0) { } else { $since_id = 1. // Loop through the retweeters popping variables out of the array while ($mention_this_guy = array_pop($users_to_rthx)) . $tweet_mentions = "". } } // Remove duplicates (we don't thank somebody twice in a tweet) $users_to_rthx = array_unique($users_to_rthx). $tweet_prefix = "".xml" . file_put_contents("retweets_since_id". // Make the XML an object $mentions = simplexml_load_string($mentions). // Err. // Loop through the tweets foreach ($mentions->status as $status) { // Let's see if somebody retweeted you. // Read the last tweet's id and store it into the retweets_since_id file $last_id = ($mentions->status[0]->id > $since_id) ? $mentions>status[0]->id : $since_id. "via @yourname")) { // Add the guy to the retweeters array $users_to_rthx[] = $status->user->screen_name. "rt @yourname") || strpos(strtolower($status->text).com/statuses/mentions. // Setup the tweet prefix and initialize the mentions variable // The tweet_prefix is just in case . (string)$last_id). remember to replace @yourname if (strpos(strtolower($status->text). . array("count" => 50.) $tweet_prefix = "Thanks for the retweets! ". "since_id" => $since_id). "GET"). // Setup an array which will contain users to retweet and follow $users_to_rthx = array(). but in general the code should look something like this: // Read the since_id from a file $since_id = @file_get_contents("retweets_since_id"). } // Send the Twitter API request for the latest 50 mentions // That were posted after the since_id parameter we read earlier $mentions = $oauth>OAuthRequest("http://twitter.Automatically Thank Your Retweeters and… Follow them! Be very very careful here as you don’t want to thank the retweeters too much. You’ll need to think of a mechanism to store the id of the latest retweet that you already thanked and use it in the since_id parameter when calling the Twitter API.

com/statuses/ " (" . $mention_this_guy . "POST").$mention_this_guy . strlen($message) .xml'. } // If he doesn't push him back into the variable. strlen($message) . $mention_this_guy.xml'.com/friendships/create/" . " (" . // If we've got something left in the mentions. " ". array('status' => $message). $tweet_postfix . echo "Tweeting: " . // Send the friendhips create (follow) request to the API echo "Following: " . sleep(rand(5.30)). "@". trim($tweet_mentions) . $tweet_mentions .= "@".30)). array('status' => $message). } } $message = $tweet_prefix . add him if (strlen($tweet_prefix . ". // Send the status update request to the Twitter API $oauth>OAuthRequest('https://twitter. } $tweet_mentions = "". // Wait a few seconds before the next round sleep(rand(5. . $mention_this_guy). $message . we need to tweet that if (strlen($tweet_mentions) > 0) { $message = $tweet_prefix .{ // If the popped guy fits into our brand new tweet.xml". echo "Tweeting: " . ") \n". $oauth>oAuthRequest("https://twitter. 'POST'). // Reset $tweet_mentions = "". // Format the message and output to screen (for debugging) $tweet_postfix. tweet and reset // The $tweet_mentions variable for the other retweeters else { array_push($users_to_rthx.$mention_this_guy) < 140) { $tweet_mentions . 'POST'). $tweet_postfix. ") \n". $oauth->OAuthRequest('https://twitter. array(). trim($tweet_mentions) . $message .

we send them a strange message mentioning their name.". 'POST'). "Interesting . "So you really think I'm not human? Well. // Format the message and tweet a random quote $message = "@". $random_quotes[array_rand($random_quotes)].) You can add your own $random_quotes = array( "Wha?". " " .$mention_this_guy .. } . array('status' => $message). instead we work with ones that don’t contain “rt” and “via” at all. makes me think . $message ..Did Somebody Say Anything? Random Replies Whenever somebody mentions your name (and it is not a retweet). ") \n". Don’t forget to store the replies_since_id too as we don’t want to message users multiple times (infinite number of times actually) because they’ll block the frustrating robot.30)). *sigh*" ). "Affirmative sir!"..xml'. The code looks exactly like the retweeters thank code above.. In this part the names are stored in the $users_to_reply array and goes like this: // The loop while ($mention_this_guy = array_pop($users_to_reply)) { // Some random quotes .. Here’s the while loop that actually tweets. "Hmm. Umm.".com/statuses/update. // Wait a little sleep(rand(5. except that we don’t search for “rt @yourname” and “via @yourname”. strlen($message) . $oauth->OAuthRequest('https://twitter. " (" . echo "Tweeting: " .

The last part is adding the whole stuff to crontab for automated work.php feed wordpress */16 * * * * php /home/youruser/twibots/robot.php feed mashable # Thank and follow the retweeters once every half an hour */30 * * * * php /home/youruser/twibots/robot.php reply . Open up /etc/crontab and add a few lines: # Feed mashable and wordpress tweets once every 15-16 minutes */15 * * * * php /home/youruser/twibots/robot.php rthx # Reply to people hourly 01 * * * * php /home/youruser/twibots/robot.

Sign up to vote on this title
UsefulNot useful