32 Comments »October 31st, 2008

How To Make A Twitter Bot With PHP In Five Minutes

There are quite a few uses I could think of for an automated Twitter bot that posts new tweets for you throughout the day. While this sounds like it would be a hard task it’s actually quite easy and a great project for anyone who wants to learn how to use the Twitter API within PHP. Lets get started.

Step 1 – Create your database.

When creating your database there are a number of things you may want to think of ahead of time. For the sake of making things easy I chose to tone down the code I use and show you how it works. We will create a simple table to store all of the random tweets in.

CREATE TABLE `tweets` (

`id` INT(11) NOT NULL AUTO_INCREMENT,

`tweet` VARCHAR(140) DEFAULT NULL,

PRIMARY KEY (`id`)

)

Run that SQL and you should have a new “tweets” table in your chosen database. Notice how we limited the `tweet` field to 140 characters as well so we don’t have tweets that are too long to appear on Twitter.

Step 2 – Create the PHP to send the tweet.

The next step is to create a php script that will randomly select one of your tweets, and then send it to your Twitter account via Twitter’s API. While this sounds complicated, its very easy to do.

<?php

mysql_connect(“localhost”, “USERNAME”, “PASSWORD”) or die(‘Could not connect to database’);

mysql_select_db(“DATABASE”) or die(‘Could not select database’);

$result = mysql_query (“SELECT * FROM tweets ORDER BY RAND() LIMIT 1″);

while($row = mysql_fetch_array($result)){

$tweet = “$row[tweet]“;

sendTweet($tweet);

}

function sendTweet($msg){

$username = ‘TWITTER-USER-NAME’;

$password = ‘TWITTER-PASS’;

$url = ‘http://twitter.com/statuses/update.xml’;

$curl_handle = curl_init();

curl_setopt($curl_handle, CURLOPT_URL, “$url”);

curl_setopt($curl_handle, CURLOPT_CONNECTTIMEOUT, 2);

curl_setopt($curl_handle, CURLOPT_RETURNTRANSFER, 1);

curl_setopt($curl_handle, CURLOPT_POST, 1);

curl_setopt($curl_handle, CURLOPT_POSTFIELDS, “status=$msg”);

curl_setopt($curl_handle, CURLOPT_USERPWD, “$username:$password”);

$buffer = curl_exec($curl_handle);

curl_close($curl_handle);

if (empty($buffer)) {

echo ‘fail’;

} else {

echo ’success’;

}

}

?>

Not to bad right? Our custom sendTweet() function pretty much takes care of all the dirty work in sending the message to Twitter. Just make sure you edit the code with your password and username for Twitter, and the MySQL login. Once you have your database populated you are all good to go and test the script to see if it works. Just upload it, run it, and you should see either “fail” or “success” on your screen.

Step 3 – Automate with CRON.

After going to Twitter and checking your account to confirm everything is copacetic, it’s time to let your monster loose. Depending on what host you use, CRON access may or may not be available to you. Luckily for me I am hosted with MediaTemple so this is not a problem.

  • Script Location - When using CRON you normally want to upload the file being run into a folder that nobody has access to from the web (root). After you have it in this location, just plug it into CRON with ‘php’ in front of it. Example: php /home/user/root/TwitterBot.php
  • Set The Time - I don’t think I have ever used a control panel that required you to manually enter the time format… I’m pretty sure most people use cPanel which also has drop downs to select when you would like the script to run. I like to run my Twitter bot every 25 minuets or so to keep my Twitter account fresh.

That’s it! Not to hard right… If you have any in-depth questions on the code or need help, feel free to leave a comment. Also leave one if you have usage ideas, new features that could make the script better. As you can now see, this is a valuable tool to have in your chest.

UPDATE 5/8/2009

I have released a full blown version of the script packed with features and a complete backend GUI. This has proven to be a great Twitter marketing too! Unlike all the others, I support mine and its not a billion dollars. Check out the site for all the details.

Get Twitterbotscript now!

Comments

  1. Leila says:

    I think Ezines does this when you submit articles too – its a very good trick, thank you for sharing it.

    Gives us wannabe-techies yet another reason to get moving and start coding!

  2. frank says:

    The question that people need to ask them selves is if something like this is really what we should be doing or allowing??

    If social media is all about being human and connecting with real people then something like this goes directly against the core value.

    Thoughts?


    http://twitter.com/franswaa

  3. vincent says:

    @frank:

    While I agree with you to a point, services like this can be used for a whole lot more than their initial purpose. Don’t get me wrong, I wouldn’t advocate the use of something like this for smamming, but there are a lot of twitter bots that offer good services, based on twitter’s scriptable API. The best thing is, is that the reciever has to APPROVE the sender’s feed – so it’s not like you can start getting spammed without specifically adding the spammer.

  4. Evans says:

    This is smashing! I love the tips and I will definitely play around with the code and see how I can modify it to suit a small personal project am working on.

    Great site :)

  5. Chris says:

    Great post. I think Ill stick to manual tweet updates by a real human being.. for now..

  6. Adam says:

    I have this up and running, but I’m trying to add a feature where it only tweets when someone @reply’s to it, and it includes the @in_reply_to_screen_name at the beginning. I found a perl script that supposedly does this, but I can’t get that to work.

    I’m a total noob, just messing around with this thing trying to get it to work. So far, no luck. Do you know a way to implement this?

    Thanks

  7. Arvid says:

    Shut up, Frank.

  8. If you want to take a look on a bot which provides the scores for the main football (soccer) competitions, check http://twitter.com/twitscores

  9. Thanks for this simple but awesome code sample.
    I think it could come in handy and be modified to do ‘other things’.

    Will definitely play around with it.

  10. Ronald says:

    Great info for new users.
    It would be a great extension if you could link to a tutorial how to maintain this database (edit/add/delete records).

  11. Jordan says:

    As a fellow blogger I like to take the time to let people know when I visited their site. If you could show me the same love at my blog I’d really appreciate it :)

  12. Jonas Lejon says:

    Thanks for the info! I’ve just made a Twitter bot. More info http://download11.com/twitter

  13. k o_0 tig says:

    Thank You for useful code – simply and powerful.

  14. Wayne Shears says:

    Hi Guys,

    I have followed this article all the way through and set up the database with two messages in so far. However whenever I test the script it says ‘fail’. Any ideas guys?

    Thanks.

  15. Patrick says:

    is there a way to do it so it will auto reply to every tweet that includes a certain word?

  16. Web 2.0 says:

    Thanks for great tutorial :)

  17. Mehedi Hasan says:

    Great IDEA… :)

    Thanks a lot…

  18. Frank says:

    Great script. I will be using it to allow http://www.Pay-Talk.com users to send notifications to their followers about their services.

  19. Jason says:

    so i set this up and get a success message, but except for the first time i manually ran the page, i am not seeing the tweets in my account. like i said, the first one showed up so i proceeded to setup the cron. after that, i can’t get it to work even manually and getting the success message. any thoughts?
    thanks for the great tool by the way.
    jason

  20. mutuelle says:

    Very good tuto, thanks for posting.

  21. Rory says:

    The script works fine, but after a couple of tweets twitter stops being updated by this script… any reason why this may be?

Leave a Reply