Twitter bot in php with oAuth support

For last couple of days, I was looking into twitter API. One day I asked Lenin vai about a bot he made. He suggested me a Twitter bot. I was so excited at the very beginning. But when I had started I gone through some new features which I didn’t know and of course sometimes silly things give us so much pain 😛

About Tweet Bot:

The bot collects data from one or more locations and then tweets those one by one. Very simple php script. Usable with any website or blog and even any person at Twitter.

Tweet Bot Features:
  • oAuth supported
  • Parses feed with simple feed parser
  • Formatting links by shortening url
  • Format large title
Setting up Tweet Bot

Register application from here. For oAuth support I’ll be using Abraham William’s oAuth Library. Download the Twitter oAuth Library from github. The bot will be getting feeds from RSS. For that we need a parser. So, here we’ll be using Simplepie to parse RSS feed. Download the parser from here.

I always prefer to make a configuration file, just to keep the code clean and ready to use any time.

config.php

define('CONSUMER_KEY', 'YOUR APPLICATION KEY');
define('CONSUMER_SECRET', 'YOUR APPLICATION SECRET');
define('ACCESS_TOKEN', 'YOUR ACCESS TOKEN');
define('ACCESS_TOKEN_SECRET', 'YOUR ACCESS TOKEN SECRET');

/* Change this url as needed */
define('FEED_URL', 'https://mdshaonimran.wordpress.com/feed/');

Now let’s make our hand dirty with some coding 🙂

autobot.php

Connect to twitter via Abraham’s oAuth Library

$connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, ACCESS_TOKEN, ACCESS_TOKEN_SECRET);

Setup Simplepie to parse RSS feed.

$feed = new SimplePie();
$feed->set_feed_url(FEED_URL);
$feed->init();
$feed->handle_content_type();

We need to save the parsed link so that we can prevent the bot tweeting the same thing more than once. Twitter has word limitation of 140 words. So, the bot parses the title as well as the link. It always matches the latest link with the last tweeted one.

/* find the total number of available feed */
$max = $feed->get_item_quantity();

/* Get last tweeted data */
$last_saved_tweet = file_get_contents('last_tweet');

/* Get the first item on the feed */
$item = $feed->get_item(0);

/* permalink of the first item */
$itemlink = $item->get_permalink();

/* save the permalink into file */
file_put_contents('last_tweet', $itemlink);

/* title of the first item */
$itemtitle = $item->get_title();

/* length of the item title */
$titlelength = strlen($itemtitle);

if ($titlelength > 110) {
    $itemtitle = substr($itemtitle, 0, 107) . "...";
}

if ($itemlink != $last_saved_tweet) {

    /* shorten the url with tinyurl */
    $shortlink = file_get_contents("http://tinyurl.com/api-create.php?url=" . $itemlink);

    /* Update status with Abraham's oAuth Library */
    $connection->post('statuses/update', array ('status' => $itemtitle . " " . $shortlink));
}

So, now the Tweet Bot is ready to shoot! 🙂