Create a Twitter Bot With PHP, YOURLs and Cron

Ever since I’ve been on Twitter I’ve been fascinated by Twitter bots. You know, automated Twitter posting robots. There are all sorts of Twitter bots. Most of them are Twitter accounts with a single purpose that are run by some sort of programming. Most often they monitor Twitter’s RSS feed for specific keywords and either reply to or retweet them.

A lesser used (I think) kind of Twitter bot is the kind that will post specific links on a scheduled basis. A couple of weeks ago I came up with an idea for one of these and set out to create it.

The tools I used were PHP, YOURLs (to create a short URL for the links the bot would post), Abraham Williams’s PHP library for Twitter OAuth and a cron job. Here’s how to do it:

  1. Before you start coding you must register the bot as an app on Twitter. To do that go to http://dev.twitter.com/, log in using the Twitter account you’d like to use the bot from and register your app. After that’s done you’ll have proper OAuth keys to use to post to Twitter from your bot.
  2. For the sake of this example we’ll build a bot that will post a link to the day’s Dilbert comic strip. The URL for a given day’s Dilbert strip is as follows:
    http://www.dilbert.com/strips/YYYY-MM-DD/
    To adjust this URL to be able to work on any day simply do a little PHP date substitution and assign it to a variable as follows:
    $url = "http://www.dilbert.com/strips/".date("Y")."-".date("m")."-".date("d")."/";
  3. Now that you have a variable that holds the URL for the strip you’re ready to send it to YOURLs for shortening. (Different URL shortening services have different ways to use their APIs. If you’re not using YOURLs consult the documentation for the API of your service of choice. Continue at step 6 once you have your shotened URL.) First create the URL for the API call and assign it to a variable:
    $link = "http://yourdomain.com/yourls/yourls-api.php?signature=yoursignature&action=shorturl&format=xml&url=".urldecode($url);
    Replace “yourdomain.com” and “yoursignature” in the above code with the domain of your YOURLs installation and the signature for your YOURLs user name.
  4. Use CURL to initiate the API call and retrieve the resulting XML containing the short URL:
    $ch = curl_init($link);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $reply = curl_exec($ch);
    curl_close($ch);
  5. Parse the XML returned by the above code, retrieve the short URL and assign it to a variable:
    $xml = new DOMDocument();
    $xml->loadXML($reply);
    $node = $xml->getElementsByTagName('shorturl')->item(0);
    $shorturl = $node->textContent;
  6. Create the body of the Tweet and assign it to a variable:
    $message = "Today's Dilbert (".date("F j, Y").") - ".$shorturl;
  7. Now it’s time to log into Twitter using OAuth and post the Tweet. Before doing this be sure to include the OAuth library in the script with a simple include statement:
    require_once('twitteroauth.php');
  8. Define the OAuth keys for the application. These keys were supplied by Twitter when you registered your app in step 1 (use your keys in place of the Xs).
    define("CONSUMER_KEY", "XXXXXXXXXXXXXXXXXXXXXX");
    define("CONSUMER_SECRET", "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX");
    define("OAUTH_TOKEN", "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX");
    define("OAUTH_SECRET", "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX");
  9. Log into Twitter:
    $connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, OAUTH_TOKEN, OAUTH_SECRET);
    $content = $connection->get('account/verify_credentials');
  10. Post your Tweet:
    $connection->post('statuses/update', array('status' => $message));
  11. Upload your code and twitteroauth.php & OAuth.php from the PHP library for Twitter OAuth to a directory on your web space.

Your bot is coded and ready to run. You can try it by going to the URL for it and checking your Twitter feed for the result.

Since it’s coded in PHP you’ll need to set a cron job to run it at the time you’d like it to run. Consult the cron documentation for your web provider to learn how to do this.

If you want to see the bot created above in action then subscribe to my twitter feed and watch it at 8:30 AM Eastern time.

Tags: , , ,

If you enjoyed this post, please consider to leave a comment or subscribe to the feed and get future articles delivered to your feed reader.

Comments

[…] This post was mentioned on Twitter by golddave and golddave, golddave. golddave said: Published a new blog post: Create a Twitter Bot With PHP, YOURLs and Cron http://golddave.com/lknzPJ […]

Great idea. Can this configuration be used for an rss feed or only for websites that have 1 daily update, such as dilbert? For example, if I were running a news site twitter account, and there were multiple posts on a given day for the date? make sense?

Jesse –

The basic workings of this script would work for that. You’d need to add a function to read the RSS feed. That’s actually on my todo list for when I have some free time.

– Dave

Awesome! I just subscribed to your email updates, so I will look out for new updates from you. Any reccomended readings for setting up a cron job. I am a semi-noob?

Jesse – How you set up a cron job depends on your web provider. Different providers have different ways of doing it. I suggest you check with your provider for details on their method.

one more thing…I was searching for ways after I read your post again, to create my own bot for rss feeds, what would be the advantages of creating something like this on my own server as opposed to using twitterfeed?

I like the idea of hosting it myself, but just wanted your take on it?

Jesse –

The advantage of doing this on your own server is that you have control. But that also means you have responsibility for maintaining it as well.

Also, the big picture idea here is to have a bot that relies on a database. In your case you could have a database with a list of RSS feeds to be used by a single bot. This could be easier to maintain on your own than it may be in friend feed.

Hi Dave,
You wrote a very nice and good explained post here.
Just wanted ti share with you my own robot at http://www.twitfwd.com, you can use it to send DM to multiple users and to post tweets in more than one account at once.
Of course I also used the fantastic abraham’s oauth library.

Have a nice day

[…] And Easy RSS Parsing With PHP Posted by Dave February 20, 2011 When I wrote about creating a Twitter bot with PHP, etc. last week I had in mind to continue developing the idea. To this end I’ve created a bot that […]

I was able to create the short url, but retrieving it with your code didn’t work. Any ideas why?

Since I am on the server I did this:
$test_link=’mylink’;
require_once ‘/pathto/load-yourls.php’;
global $ydb;
$table = YOURLS_DB_TABLE_URL;
$url_array = $ydb->get_row(“SELECT * FROM `$table` WHERE `url` = ‘”.$test_link.”‘;”);
echo $url_array->keyword;

From this I can reconstruct the url with my short domain.

Also, I can do the following to reconstruct the whole link with the short url:
echo $url_array->title;

Jack –

What if you use JSON instead of XML for the YOURLs API call? Like this:

$link = “http://yourdomain.com/yourls/yourls-api.php?signature=yoursignature&action=shorturl&format=json&url=”.urldecode($url);
$reply=mb_convert_encoding(file_get_contents($link),”HTML-ENTITIES”,”UTF-8″);
$json_l=json_decode($reply,true);
$shorturl = $json_l[shorturl];

This code is actually more efficient. Let me know if this works for you.

– Dave

In the end I did the yourls a different way.
I used a subset of the yourls-api. This way I could also add the title and check for duplicates.

With your way, there was occasionally a difference between the original long url and the one that made it to the database, but even when adding your urldecode filter and the yourls filters I couldn’t reproduce it.

Also, if one is making a true bot (multiple tweets) 2 settings should be modified in load-yourls:
YOURLS_FLOOD_DELAY_SECONDS – I set it to 0
and YOURLS_FLOOD_IP_WHITELIST – add IP addresses you are using

I am not sure why I needed both, but it wouldn’t work with just adding the ip address to the YOURLS_FLOOD_IP_WHITELIST.

Now it’s working well.

Next step: send the tweets to different twitter accounts based on topic.
My current site is not using this stuff yet, but I am hoping to release the v2 with this stuff by the end of the month.

Cheers
Jack

Jack –

What do you mean by “a subset of the yourls-api”? Occasionally I get an issue where the title doesn’t make it into the database. It sounds like you’ve worked around that issue.

As for duplicates I use an if statement (if ($json_l[status]==”success”)) and only post within this condition. If YOURLs returns anything other than “success” I don’t post it and hence don’t end up posting duplicates.

Tweeting from different accounts based on topic should likewise be able to be handled by an if statement that shouldn’t be too hard to figure out.

– Dave

Thanks for this. Went through about a dozen different sites explaining OAuth, and yours was by far the easiest to follow.

[…] across this post which lead me to a Twitter OAuth class which made the whole process dead […]

Hello,

can i test the bot from a WAMP localhost?

Diego – I haven’t tried but I don’t see why not. It doesn’t hurt to try it. Let us know how it goes.

Hello Dave

nice post

do you have the php code for yourls Geo Redirect Plugin

I’ve been looking everywhere

thanks

yellowfrog –

The only URL I know for that plugin is down. But here it is (in case it comes back up):
http://www.techblessings.com/projects/geo-redirect/

Good luck,
Dave

[…] written before about creating a Twitter bot so I won’t repeat all of the details here. Just as in the previous post I’m using PHP […]

Hi, I’m trying to make a twitter bot that will tweet when a player is on deck, up to bat, and then the result of his at-bat (all live). Would this be a good tutorial to follow?

Depends on the data source and other factors. Read the post and see if you think it’ll work for you.

Indeed, very useful and interesting writing. Thank you 😀
I recently wrote about Displaying Advertisements before redirection in Yourls. You should read it. 🙂
http://taimoorsultan.com/show-ads-before-redirection-in-yourls/
Thanks! Happy New Year

I got this issue:
Fatal error: Class ‘OAuthSignatureMethod_HMAC_SHA1’ not found in … But the class is exists on OAuth.php.
How come?

I don’t understand your question.

[…] Lag din egen Twitter-bot […]

Leave a comment

(required)

(required)