How to Use the Twitter Search API

How To Use the Twitter API

I’ve always wanted to play around with the Twitter API. Everyone seems to be doing it these days. All I needed was a reasonable excuse. So, I decided on integrating relevant Twitter posts into Short.ie.

Recently I created a Twitter account for the new URL shortening service. The purpose of which was to post up new release information, engage with the users and essentially put a ‘face’ onto the service. But for this to be really effective I needed followers, and the best way to get those is to start following people yourself.

Maximising RSS

The only problem was, I needed to know who to follow. This is where Twitter Search comes in. I wanted to follow anyone who was currently using the short.ie service and Twitter Search allowed me to find them.

Getting Comfy with the Twitter API

So, to make my life easier, instead of trawling through the search results by hand and manually following each Short.ie user I decided to write a script to automatically follow everyone who posts a tweet that’s got a Short.ie link in it.

Here’s the code:


// Parse Search Feed
$rss =& new XML_RSS("http://search.twitter.com/search.rss?q=short.ie");
$rss->parse();

// Loop through all Tweets
foreach ($rss->getItems() as $item)
{
    // Get username of who posted it
    $user = substr($item['link'], 19 );
    $posi = strpos($user, '/');
    $user = substr($user, 0, $posi);

    // Follow the user via the Twitter API
    $req = new HTTP_Request('http://twitter.com/friendships/create/'.$user.'.xml');
    $req->setMethod(HTTP_REQUEST_METHOD_POST);

    $req->setBasicAuth('username', 'password');
    $response = $req->sendRequest();
}

It's a very basic script right now, but it will form the basis of a more comprehensive solution as it matures. But, for only 10 lines of code, it's pretty powerful!

The script has 4 main parts:

  • Retrieve and parse the RSS feed for the search
  • Loop through the feed
  • Extract the username from the link of each tweet
  • Use the Twitter API to follow the creator of the tweet

Obviously there are some issue with duplicates to be ironed out, and I think I'd like to store some of this information in a database too, but that can all come later. For now, I can say that I've dipped my toe into the world of the Twitter API and so far I like what I've seen.

Notes

To use this script, you'll need to install and configure PEAR. I used the XML_RSS and HTTP_Request packages in this example.

Sorry, comments for this entry are closed at this time.