Wednesday, 5 January 2011

The simplest Drupal / Twitter integration possible!

Drupal is extremely frustrating at times. The organisation of which I manage the Drupal site got on Twitter. We only wanted a a simple block with just our latest posts. I tried three solutions before finding the perfect one:

  1. The Twitter module for Drupal
  2. Another Drupal module called JUItter (http://juitter.com/)
  3. The official Twitter widget
  4. Tweet by seaofclouds (http://tweet.seaofclouds.com/)
The last was definitely not least, I can tell you that.

The Twitter module was terrible, much too complicated for this simple task. Besides there is virtually no documentation. A shame for a module of this size! Furthermore the recommended beta didn't really work. After uninstalling (and removing the created views!) I got a long way with the previous stable version, but it seems that twitter stopped allowing old API calls and now only accepts calls made using OAuth.

JUItter seems nice and it is client based (a pro for social media). Above all, it has a ready to use Drupal module, or so they claim. After downloading the zip it contained only 3 files and no traces of any Drupal module. Now something might just be messed up here temporarily, but I went on right away.

The official Twitter javascript widget is rather ok. Just implement the generated code (which creates a twtr object and all that) in a new html Drupal block and you're done. However the script uses document.write so it has to be run by the browser before the document is fully loaded. I, like every serious programmer, like to run my javascript actions using body.onload so it won't mess up loading times for the rest of the site. There was no way to make this script load a-synchronized.

Finally I thought of making a Drupal block, put some javascript jquery code in it and make an ajax call to the twitter api. From there I could parse the XML and use it to display our tweets. However, jquery does need some more configuration to be able to parse the xml file. Upon researching this I came across the best solution:

Tweet by seaofclouds works right away. No hassle whatsoever. It is client based, so no trouble with caching and all that. Use jquery and their .js file. The add the following code to a Drupal block:
<script type="text/javascript">
// <![CDATA[
document.write('<div id="ourtweets"></div>');

$(document).ready(function() {
$("#ourtweets").tweet({
username: "yourtwittername",
join_text: "auto",
avatar_size: 24,
count: 5,
auto_join_text_default: "we said,", 
auto_join_text_ed: "we",
auto_join_text_ing: "we were",
auto_join_text_reply: "we replied to",
auto_join_text_url: "we were checking out",
loading_text: "loading tweets..."
});
});
// ]]>
</script>

Note that I put the creation of the div in javscript, using a document.write. This is because my Drupal configuration does not allow me to post divs in a block's source code.

So once again, Tweet is the solution.