Showing Twitter Status On Your Group Blog
First a bit of meta discussion: I changed the left sidebar of TikiRobot to show the five most recent status updates from the fellow robots! It was kind of silly to display tweets from people who haven’t updated since last year. If you want your status to show up in the sidebar, and it isn’t there for some reason, lemme know!
Twitter has an API for showing for retrieving the most recent status updates from your friends, so I created a new twitter user to follow the tikirobot posters. Then, I used this python script to fetch the friends timeline and spit out html for the blog. I wanted to do this all in javascript, but the the friends timeline api needs authentication, and I didn’t want to publicize the twitter account password. Plus, this way I can cache the data on our server, so it doesn’t hit twitter so often.
-
#!/usr/bin/python2.5
-
#Copyright(c)2008 TikiRobot.net - Software license GPL version 3.
-
-
import time
-
import datetime
-
import os
-
import fcntl
-
import sys
-
import codecs
-
import re
-
-
# CalculateRelativeTime()
-
#_______________________________________________________________________________
-
def CalculateRelativeTime(str):
-
dt = datetime.datetime.strptime(str, ‘%a %b %d %H:%M:%S +0000 %Y’)
-
now = datetime.datetime.utcnow()
-
delta = now - dt
-
secs = delta.seconds
-
if (delta.days> 0):
-
return “%d days ago”%(delta.days)
-
elif (secs <60):
-
return “%s seconds ago”%(int(secs))
-
elif (secs <3600):
-
return “%s minutes ago”%(int(secs/60))
-
else:
-
return “%s hours ago”%(int(secs/3600))
-
-
# main()
-
#_______________________________________________________________________________
-
print “”“Content-type: text/javascript; charset=UTF-8\n““”
-
-
useCachedRss = True
-
cacheFile = ‘cache/twitter.json’
-
sys.stdout = codecs.getwriter(‘utf8′)(sys.stdout)
-
-
try:
-
stats = os.stat(cacheFile)
-
if (time.time() - stats.st_mtime)> 300:
-
#cache expired
-
useCachedRss = False
-
except OSError:
-
#cache file not found
-
useCachedRss = False
-
-
if useCachedRss:
-
try:
-
#print "reading cached json"
-
fh = open(cacheFile, ‘r’)
-
fcntl.lockf(fh, fcntl.LOCK_SH)
-
contents = fh.read()
-
fcntl.lockf(fh, fcntl.LOCK_UN)
-
fh.close()
-
except:
-
print “got some kind of error when reading cached json. quitting”
-
sys.exit()
-
else:
-
try:
-
#print "fetching new json"
-
import urllib2
-
apiurl = ‘http://twitter.com/statuses/friends_timeline.json?count=5′
-
auth_handler = urllib2.HTTPBasicAuthHandler()
-
auth_handler.add_password(
-
realm=‘Twitter API’,
-
uri=apiurl,
-
user=‘username’,
-
passwd=‘password’
-
)
-
opener = urllib2.build_opener(auth_handler)
-
urllib2.install_opener(opener)
-
urlfh = urllib2.urlopen(apiurl)
-
contents = urlfh.read()
-
urlfh.close()
-
fh = open(cacheFile, ‘w’)
-
fcntl.lockf(fh, fcntl.LOCK_EX)
-
fh.write(contents)
-
fcntl.lockf(fh, fcntl.LOCK_UN)
-
fh.close()
-
except:
-
print “got some kind of error when fetching twitter timeline. quitting”
-
sys.exit()
-
-
-
import json
-
timeline = json.read(contents)
-
htmlstr = “”
-
for i in range(5):
-
name = timeline[i][‘user’][’screen_name’]
-
imgurl = re.sub(r‘_normal.(jpg|png)$’, r‘_mini.\1‘, timeline[i][‘user’][‘profile_image_url’])
-
twit = re.sub(r‘\’‘, ‘'’, timeline[i][‘text’])
-
twit = re.sub(r‘\n‘, ‘ ‘, twit)
-
twit = re.sub(r‘http://tinyurl.com/(\S+)’, r‘<a href="http://tinyurl.com/\1">tinyurl.com/\1</a>’, twit)
-
when = CalculateRelativeTime(timeline[i][‘created_at’])
-
htmlstr += “”“<div class=”twitter“>”“”
-
htmlstr += “”“<img src=”%s“/>”“”%(imgurl)
-
htmlstr += “”“<div class=”twitterRight“>”“”
-
htmlstr += “”“<a href=”http://twitter.com/%s“><strong>%s</strong></a>: ““”%(name, name)
-
htmlstr += twit
-
htmlstr += “”“<span class=”twitterMeta“>- ““” + when + “</span>”
-
htmlstr += “”“</div>”“”
-
htmlstr += “”“<div class=”clear“></div>”“”
-
htmlstr += “”“</div>”“”
-
-
print “”“var tikiTwits = ‘”“”+htmlstr+“‘;”
-
print “”“document.write(tikiTwits);”“”
It’s fun to see that Twitter still uses the Javascript API that I proposed to them over the phone a couple years ago.
Also, dear lazyweb: please send my a python function that converts a UTC date string to PST. Thanks!
Filed under: code code, meta |
2 Comments
Tagged: twitter

