APIs are great.
Case in point, it only took me about an hour to automatically add my most recent Twitter updates to this blog. (Yes, the Twitter badges would have worked, but for performance and consistency reasons I try not to depend on third party Javascript.)
If you’re reading this in a blog reader, then you can view the new Twitter updates by visiting the blog itself.
A short python script, shown below, is executed every five minutes as a cron job. The script fetches my Twitter feed as JSON, parses it, and writes it back out as an XHTML fragment to the filesystem. My WordPress theme later includes this file when processing the templates.
I could have written this as a WordPress extension, but that would have involved writing PHP, which I try to avoid. This also has the benefit of working equally well with any type of publishing system that can include arbitrary files.
The python script, saved as fetch_latest_twitter.py:
#!/usr/bin/python
# Load the latest update for a Twitter user and leave it in an XHTML fragment
import getopt
import simplejson
import sys
import urllib2
# After parsing
# data.created_at
# date.id
# data.relative_created_at
# data.text
# data.user.description
# data.user.url
# data.user.name
# data.user.location
# data.user.id
# data.user.screen_name
LAST_UPDATE_URL = 'http://twitter.com/t/status/user_timeline/%s?count=1'
TEMPLATE = """
<div class="twitter">
<span class="twitter-user"><a href="http://twitter.com/%s">Twitter</a>: </span>
<span class="twitter-text">%s</span>
<span class="twitter-relative-created-at"><a href="http://twitter.com/dewitt/statuses/%s">Posted %s</a></span>
</div>
"""
def Usage():
print 'Usage: %s [options] twitterid’ % __file__
print
print ‘ This script fetches a users latest twitter update and stores’
print ‘ the result in a file as an XHTML fragment’
print
print ‘ Options:’
print ‘ -h –help : print this help’
print ‘ -o –output : the output file [default: stdout]‘
def FetchTwitter(twitterid, output):
assert twitterid
assert int(twitterid)
url = LAST_UPDATE_URL % twitterid
f = urllib2.urlopen(url)
jsonstring = f.read()
json = simplejson.loads(jsonstring)
data = json[0]
xhtml = TEMPLATE % (data['user']['screen_name'], data['text'], data['id'], data['relative_created_at'])
if output:
Save(xhtml, output)
else:
print xhtml
def Save(xhtml, output):
out = file(output, ‘w’)
print >> out, xhtml
def main():
try:
opts, args = getopt.gnu_getopt(sys.argv[1:], ‘h’, ['help', 'output='])
except getopt.GetoptError:
Usage()
sys.exit(2)
try:
twitterid = args[0]
except:
Usage()
sys.exit(2)
output = None
for o, a in opts:
if o in (”-h”, “–help”):
Usage()
sys.exit(2)
if o in (”-o”, “–output”):
output = a
FetchTwitter(twitterid, output)
if __name__ == “__main__”:
main()
The script is run every five minutes with the following crontab:
*/5 * * * * [/path/to/]fetch_latest_twitter.py [twitterid] –output [/path/to/your/wordpress/theme/]twitter.html
Obviously, replace [twitterid] with your twitter id, and adjust the paths accordingly.
The Wordpress templates were each modified with the following simple line:
<?php include("twitter.html"); ?>
And my unimaginative CSS:
/*
* Twitter
*/
.twitter-user
{
font-size: .8em
}
.twitter-text
{
font-size: .8em
}
.twitter-relative-created-at
{
font-size: .6em
}
The only thing missing is my Twitter image, the URL to which is not included in the JSON structure the script fetches. If I decide I want that, I’ll probably write a second script, also run via cron, that finds that image and saves it locally.
Again, great job, Twitter! A fun evening hack.

January 22nd, 2007 at 12:53 pm
http://simplify3.wordpress.com/2006/12/10/hello-world/trackback/
I think your script is fantastic. I with I knew enough to get that far - I’m a Web1.0 guy who is still getting used to Web2.0! For myself, easily updating my Twitter was necessary, and I have an ancient computer, so I put this together to perhaps make it a tad easier for those with less technical abilities to be able to Twitterfy their things…
http://www.zen72119.zen.co.uk/TwitterSubmitter/
to see Twitter Submitter in action or download the simple to modify HTML at:
http://simplify3.wordpress.com/2006/12/10/hello-world/trackback/
Twitter Submitter works on any browser, any computer system. It allows you to post updates to your Twitter blog. I wrote it as I have a Win95 system and enjoy using Lynx and Opera, and all of the nifty apps accessing the Twitter API are too complex, confusing for me, or only work on a Mac or Vista system!
Also found through: http://twitter.pbwiki.com - Twitter Fan Wiki, among other places!
Kenneth Udut
simplify3@aol.com
http://twitter.com/simplify3
Bringing Web2.0 to the Web1.0 world!
January 22nd, 2007 at 2:43 pm
Excellent! I was going to hack one of the APIs up in Python tonight…but you have saved me time. Now I can watch Heroes!
January 22nd, 2007 at 4:13 pm
[...] So if, like me, you’re reluctantly - or even not so reluctantly - documenting your whereabouts and current state of mind even more obsessively than you used to, I can be found here. If you’re not, but still desperately interested in such information, I advise you to either a.) seek professional help or b.) hit my homepage and scroll down a bit. I’m not as cool as DeWitt, but I am lazy. [...]
January 25th, 2007 at 12:32 pm
“I try not to depend on third party Javascript.”
“[...] fetches my Twitter feed as JSON, parses it, [...]”
I’m confused. Are you depending on third party Javascript, or no?
January 25th, 2007 at 12:38 pm
Oh, sorry, that was ambiguous, wasn’t it?
I try not to use <script /> tags that have a different src domain. For performance reasons mostly.
The one exception is Google, which can serve their .js files more reliably and faster than I serve my own site. So I do use AJAX search and Analytics on this site.
I do hit the Twitter JSON service, but I do that behind the scenes on my server, and it doesn’t matter that I’m seeing 20-30 failed requests a day as it is hidden from the visitors to this site.
January 26th, 2007 at 12:00 am
Hi again! I’ve been busy. Since the other day, TwitterSubmitter is available for Windows95-XP (maybe Vista too - haven’t tested it), but more importantly: twtview 1.3 is available, along with BASIC source and batch files (archaic but it works- i’m old school and it might help others ‘get’ the API a little better).
twtview lets you view the public timeline, your own timeline (with friends) or, with version 1.3 also allows you to view ANY public user’s homepage through a simple text-based Win32 interface. Beautiful and ugly at the same time, but very very fast. Lemme know what you think.
January 26th, 2007 at 12:03 am
http://kudut.freeshell.org/twtsub14.zip Twitter Submiter W32
http://kudut.freeshell.org/twtview.zip Twtview for Win32
http://simplify3.wordpress.com/2006/12/10/hello-world/trackback/ [the annoying site of mine]