Twitter 和饭否同步

Twitter饭否上看到 Zhaonc, aka Nelson 同学一直在折腾同步,我闲得无聊,也开始折腾这事。他的研究结果是,饭否发的消息最后能自动跑到 Twitter 上,并写得此文 Twitter与饭否同步。于是我非要逆向行驶,目标是搞个 Twitter 发的消息自动跑去饭否的方法,方法现在找到了,于是我开始写本文……

啰嗦完毕,说正事。那些国外的第三方工具啊,大都是不认识饭否的,认识饭否的又竟然不认识中文。Ping.fm 倒是支持 Custom URL ,我尝试写个脚本让他支持饭否,可是又发现速度奇慢,还老丢东西。最后一怒之下自己写了个脚本,用最笨的办法吧,却是最靠谱的。放到 Dreamhost 上 cron 了10分钟一次,效果奇佳。

from xml.dom.minidom import parseString
import urllib
import urllib2
import sys

def post_to_fanfou(msg):
    url = 'http://api.fanfou.com/statuses/update.xml'
    data = urllib.urlencode({'status':msg})
    req = urllib2.Request(url,data)
    username = 'raptium'
    password = 'password'

    passman = urllib2.HTTPPasswordMgrWithDefaultRealm()
    passman.add_password(None, url, username, password)

    authhandler = urllib2.HTTPBasicAuthHandler(passman)
    opener = urllib2.build_opener(authhandler)
    urllib2.install_opener(opener)
    response = urllib2.urlopen(req)

def main():
    f = open('last.txt','r')
    maxid = int(f.read())
    f.close()
    if maxid < 1166717326:
        print 'error'
        sys.exit(-1)

    params = urllib.urlencode({'since_id':maxid})
    f = urllib.urlopen("http://twitter.com/statuses/user_timeline/raptium.xml?%s" % params)
    xmltext = f.read()
    dom = parseString(xmltext)
    statuses = dom.childNodes[0]
    messages = []
    s = 0
    for node in statuses.childNodes:
        if node.nodeName == 'status':
            status = node
            for snode in status.childNodes:
                if snode.nodeName == 'id':
                    n = int(snode.childNodes[0].nodeValue)
                    if n > maxid:
                        maxid = n
                elif snode.nodeName == 'text':
                    messages.append(snode.childNodes[0].nodeValue.encode('utf-8'))
    while len(messages) > 0:
        post_to_fanfou(messages.pop())
        s = s + 1
    f = open('last.txt','w')
    f.write(str(maxid))
    f.close()
    print 'Post %d status to Fanfou.' % s

if __name__ == "__main__":
    main()