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.

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 = ''
tweetdata = json.loads(urllib2.urlopen(url).read())
text = tweetdata[0]['text']

homedir = os.environ['HOME']
file = open(homedir+'/', 'w')
file.write('<a href="" target="_blank">Latest Tweet:</a>' + ' ' + urlify(text))

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/

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


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

add_action('some_hook', 'latest_tweet');


Hope this helps.

About Pratik Sinha

Linux Nerd, Socialist, Atheist, Adventuristic, Nature Lover, Geeky.

1 comment

Leave a Reply to social media guru Cancel reply