python版的饭否到twitter的同步代码。

参考raptium同学的文章。
Twitter 和饭否同步

做个反向的。

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

def post_to_twitter(msg):
    url = 'http://twitter.com/statuses/update.xml'
    data = urllib.urlencode({'status':msg})
    req = urllib2.Request(url,data)
    username = 'YOUR_USERNAME'
    password = 'YOUR_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 = f.read()
    f.close()
#   if maxid < 1166717326:
#       print 'error'
#       sys.exit(-1)

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

if __name__ == "__main__":
    main()

2 thoughts on “python版的饭否到twitter的同步代码。

Leave a Reply