Doge log

Abby CTO 雑賀 力王のオフィシャルサイトです

TwistedでTwitterにアクセスする

Python Workshop 2007 Twistedの宿題の話。
なんか誰も書いていないような気がするので簡単な回答を書いてみる。
(最低限の回答なので)
お題はTwistedでTwitterにアクセスするだよね。

まずは復習もこめてpublic timelineにアクセスする

twitter_public.py
from twisted.internet import reactor
from twisted.web import client
import simplejson

PUBLIC_TIMELINE_URL = 'http://twitter.com/statuses/public_timeline.json'

def gotPage(data):
    json_list = simplejson.loads(data)
    for json  in json_list:
        print json['user']['screen_name'], json['text']
    

def getTimeline():
    client.getPage(PUBLIC_TIMELINE_URL).addCallback(gotPage)

if __name__ == '__main__':
    getTimeline()
    reactor.run()

Deferredにcallbackを登録していくのがTwistedの基本。
この例ではpublic timelineにアクセスし、値をgotPageというcallbackで受け取っている。
Twitterは値を返すフォーマットを指定できる。
今回はjson形式で受け取る。
jsonpythonのdictに置き換えるsimplejsonモジュールという便利なものがあるのでそれを使っています。
この例ではユーザー名とメッセージを表示しています。
では次、自分のFriendのtimelineを取得してみます。

twitter_friends.py
from twisted.internet import reactor
from twisted.web import client
import simplejson
import base64

FRIENDS_TIMELINE_URL = 'http://twitter.com/statuses/friends_timeline.json'

def gotPage(data):
    json_list = simplejson.loads(data)
    for json in json_list:
        print json['user']['screen_name'], json['text']

def getTimeline(user, password):
    auth_string = base64.encodestring('%s:%s' %  (user, password))
    auth_header = 'Basic %s' % auth_string.strip()
    client.getPage(FRIENDS_TIMELINE_URL, headers={'Authorization':auth_header}).addCallback(gotPage)

if __name__ == '__main__':
    getTimeline('ukuku', 'xxxx')
    reactor.run()

パスワードは見せられませんが...かなり簡単です。
public timeline以外は認証が入るのでパスワードとかを送ってやらないといけません。
client.getPageにはheaderも渡す事ができるのでそこへBasic認証の値を送ってやります。
Basic認証なので簡単です。Basic認証についてはいろいろ調べて下さい)

これも上記と同様の形式で自分のFriendのtimelineを表示します。

ここまでくるともう簡単です。
次にメッセージをPOSTしてみましょう。

twitter_post.py
# coding=utf-8

from twisted.internet import reactor
from twisted.web import client
import simplejson
import base64
import urllib

UPDATE_URL = 'http://twitter.com/statuses/update.json'

def gotPage(data):
    json_list = simplejson.loads(data)
    for json in json_list:
        print json

def postUpdate(user, password, text):
    auth_string = base64.encodestring('%s:%s' %  (user, password))
    auth_header = 'Basic %s' % auth_string.strip()
    post_status = "status=%s" % urllib.quote_plus(text)
    client.getPage(UPDATE_URL, method='POST', headers={'Authorization':auth_header}, postdata=post_status).addCallback(gotPage)

if __name__ == '__main__':
    postUpdate('ukuku', 'xxxx', 'てすと')
    reactor.run()

client.getPageはmethodの指定およびpostするデータも渡す事が出来ます。
methodはPOSTでstatusという名前でメッセージを送信します。
送信する文字列はURLエンコードしなくてはいけないのでquote_plusでエンコードしています。
とまあ簡単に書いてみた。
つーかやっぱtwistedは人気でないね。
そそられるんだけどなかなか手が出ない代物なのかな。
やってみると実はそんなに難しくなくていろんなボットを書くのに重宝すると思う。
うくく。