PythonでTwitterのUser Stream

PythonTwitterのUser Streamを取得してみた。残念ながらtweepyは対応していない。何となく難しそうなイメージがあったけど、OAuthの部分をライブラリに任せてしまえば、けっこう簡単。delimited=lengthを付けた場合は、

x
xバイトのデータ
y
yバイトのデータ
z
zバイトのデータ
 :

というデータが返ってくる。改行だけが返ってきてエラーになる場合があったので、長さの取得部分はtweepyのstreaming.pyを参考にした。

import tweepy, urllib, urllib2, json

# tweepyの解説をしているページを参考に取得
consumer_key    = "XXXXXXXXXXXXXXXXXXXXXX"
consumer_secret = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
access_key      = "99999999-XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
access_secret   = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"

def main():
    url = "https://userstream.twitter.com/2/user.json"
    param = {"delimited":"length"}
    header = {}

    auth = tweepy.OAuthHandler(consumer_key,consumer_secret)
    auth.set_access_token(access_key,access_secret)
    auth.apply_auth(url,"POST",header,param)

    req = urllib2.Request(url)
    req.add_header("Authorization",header["Authorization"])
    r = urllib2.urlopen(req,urllib.urlencode(param),90)

    while True:
        len = ""
        while True:
            c = r.read(1)
            if c=="\n": break
            if c=="": raise Exception
            len += c
        len = len.strip()
        if not len.isdigit(): continue
        t = json.loads(r.read(int(len)))
        
        if "user" in t and "text" in t and "created_at" in t and "id" in t:
            print "%s(%s)" % (t["user"]["name"],t["user"]["screen_name"])
            print "%s" % (t["text"],)
            print "%s  id:%s" % (t["created_at"],t["id"])
            print

if __name__=="__main__":
    main()


2017年3月11日追記

tweepy 3系列では動かなくっていた。
そもそも、良く見るとtweepyを使う必要が無いな……。

requestsライブラリか、
pythonのrequestsライブラリの更新に追従 - yattのブログ
tweepyに実装されたUserstreamを使いましょう。
Streaming With Tweepy — tweepy 3.3.0 documentation