Writing a Simple Drupal Module


A while back I had an idea to do a simple Drupal Module to take Environment Canada's weather RSS feed and automatically it to Twitter. I didn't see anything in the Drupal contributed modules, so I decided to write my own. (A proof of concept is running on the website: http://canweather.com.) The logic is quite simple:

  • Read an item from the RSS feed.
  • Record that I have read that item.
  • Process the text to decide whether to post the item, and make any changes (eg. truncate long messages).
  • Post the text to a Twitter account.

Fortunately, most of the work is done. Reading the RSS feed can be done with the core Aggregator module. Posting to Twitter can be done with the contributed Twitter module. The rest is easy!

Writing the function of the module was very quick. Probably the most time consuming was configuring and dissecting the Twitter module which is in turn dependent on the Oauth module. The main code could be summarized as follows:

module_load_include('inc', 'twitter');
$results = db_query("... select stuff from the `aggregator_item` and `twitter_account` tables...");
while ($row = db_fetch_array($results)) {
    $tuid = $row['twitter_uid'];
    $tweet = $row['title'];
    tweetrss_tweet($tuid, $tweet);
    tweetrss_check_row($row); //mark the RSS item as read
}

/**
 * Given a twitter user id ($tuid), post a string ($tweetstring)
 * to twitter.
 */
function tweetrss_tweet($tuid, $tweetstring) {
  $user = twitter_account_load($tuid);
  twitter_set_status($user, $tweetstring);
}

I did create a table to track the twitter accounts and the RSS feeds I want to process. I designed it so that I could process multiple Twitter accounts and multiple RSS feeds. More on that later.