Quantcast

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
#!/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'\'', '&#39;', 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!

2 Responses to “Showing Twitter Status On Your Group Blog”

  1. November 8th, 2008 | 5:20 pm
  2. may
    November 10th, 2008 | 10:55 am

    yay! maybe this will get me to twitter more than once every couple months :-)

Leave a reply