Retreive your Latest Twitter Update (Tweet) using Python

I used to display my latest tweet using PHP code as part of my WordPress theme’s function.php. However that did not work reliably and used to slow down page loading a wee bit. Hence I decided to generate the html code for the latest tweet as a background/cron process and just read the generated data in WordPress. Here’s how I do it.

#!/usr/bin/python
import urllib2
import simplejson as json
import os
import re

def urlify(urlstr):
  pat1 = re.compile(r"(^|[\n ])(([\w]+?://[\w\#$%&~.\-;:=,?@\[\]+]*)(/[\w\#$%&~/.\-;:=,?@\[\]+]*)?)", re.IGNORECASE | re.DOTALL)
  pat2 = re.compile(r"#(^|[\n ])(((www|ftp)\.[\w\#$%&~.\-;:=,?@\[\]+]*)(/[\w\#$%&~/.\-;:=,?@\[\]+]*)?)", re.IGNORECASE | re.DOTALL)
  urlstr = pat1.sub(r'\1<a href="\2" target="_blank">\2</a>', urlstr)
  urlstr = pat2.sub(r'\1<a href="http:/\2" target="_blank">\2</a>', urlstr)
  return urlstr

url = 'http://twitter.com/statuses/user_timeline/free_thinker.json?count=1'
tweetdata = json.loads(urllib2.urlopen(url).read())
text = tweetdata[0]['text']

homedir = os.environ['HOME']
file = open(homedir+'/humbug.in/path_to_data/latesttweet.html', 'w')
file.write('<a href="http://twitter.com/free_thinker" target="_blank">Latest Tweet:</a>' + ' ' + urlify(text))
file.close()

You can adapt the above code for your needs. Change ‘free_thinker’ to your twitter username. You will also need to change the path where you want the code to be written to. You will also have to create a cron job so that the script is called every five minutes or so.

*/5 * * * * /path_to_script/latest-tweet.py

In WordPress, you can adapt the following code-snippet to grab the data from latesttweet.html and display it wherever you wish to.

<?php

function latest_tweet() {
  $latesttweet = file_get_contents('/path_to_data/latesttweet.html');
  echo $latesttweet;
}

add_action('some_hook', 'latest_tweet');

?>

Hope this helps.

1 comment

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.