This simple tutorial will show you how to create a simple (ro)bot that will re-tweet (RT) any particular tweets related to your search results in Twitter. In this example, my bot will re-tweet any tweet that contain “wahihi” word, so I name it Kingdom of Wahihi.
Before we start, we need following requirements:
- Twitter accountYes, the bot needs its username and password.
- PHP interpreterYou can put this script in your own machine or any web hosting services that supports PHP.
- Cron JobCron is an application to execute a job (application/program) in schedule. Available on mostly any web hosting services.
As replacement for Cron Job, you can manually execute the script by visiting the page (open the script using web browser).
Step one, create the bot. I’ts a PHP script, if you’re an alien and never heard of this programming language before, I recommend you to skip this page and visit my other stories shown in the sidebar.
Let’s start with declaration of username and password of your Twitter account:
<?php $user = 'kingdomofwahihi'; $pass = 'password'; ?>
Then grab the keyword:
<?php $search = "http://search.twitter.com/search.atom?q=wahihi"; $xml_source = file_get_contents($search); $x = simplexml_load_string($xml_source); ?>
Above script will fetch search results of “wahihi” from Twitter’s search. The output from Twitter is in Atom (XML) format, so it’s easier for us to read the data using simplexml_load_string() function.
Next, extract the data and retweet them:
<?php foreach($x->entry as $item){ // part one $author_name = $item->author->name; list($name, $mbuh) = explode (" ",$author_name); $author = trim($name); $msg = 'RT @'.$author. ': ' .$item->title; // part two $out = "POST http://twitter.com/statuses/update.json HTTP/1.1rn" ."Host: twitter.comrn" ."Authorization: Basic ".base64_encode ($user.':'.$pass)."rn" ."Content-type: application/x-www-form-urlencodedrn" ."Content-length: ".strlen ("status=$msg")."rn" ."Connection: Closernrn" ."status=$msg"; // part three $fp = fsockopen ('twitter.com', 80); fwrite ($fp, $out); fclose ($fp); } ?>
I divide above lines of code into three parts because they have different task. Part one, the bot will grab author’s name/username and what he/she tweeted then join them into one variable. And add a RT sign as a re-tweet mark.
Part two, we are preparing the variable that we will sent to Twitter’s server, it contains raw HTTP header. I know this bot is gross, but is robust 😛
Part three, open socket to Twitter’s server on port 80 then send the raw HTTP header we have prepared on part two. Now check Twitter to see if your bot is successful.
Leave any comment if you have any questions, but question about how to execute the script won’t be answered :p
Update, September 3rd:
This script is no longer working since Twitter changed its authentication method. You can try this script with OAuth authentication, written by Nazieb.
Leave a Reply