Twitter の Streaming API と yield の組み合わせがカッコイイ気がしたので自動 follow 書いてみた


http://d.hatena.ne.jp/sugyan/20100423/1271981903
を読んで,Streaming API と yield の組み合わせがカッコイイ気がしたので自動 follow 書いてみた.

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import sys,simplejson,urllib,urllib2,logging
from pit import Pit

class TwitterClone(object):

    def __init__(self, user, passwd,url):
        self.user = user
        self.passwd = passwd
        self.url = url
        self.follow_funcs = []

    def createFriend(self,id):
        url = self.url + ('friendships/create/%s.json' % id)
        r = self.getOpener().open(url,{})
        data = simplejson.loads(r.read())
        return data

    def show(self,screen_name):
        param = {'screen_name':screen_name}
        url = self.url + 'users/show.json?' + urllib.urlencode(param)
        r = self.getOpener().open(url)
        data = simplejson.loads(r.read())
        return data

    def getOpener(self,url=None):
        passman = urllib2.HTTPPasswordMgrWithDefaultRealm()
        if not url:
            url = self.url
        passman.add_password(None, url , self.user, self.passwd)
        authhandler = urllib2.HTTPBasicAuthHandler(passman)
        opener = urllib2.build_opener(authhandler)
        opener.addheaders = [('User-agent',
                              'TwitterCloneClient(http://d.hatena.ne.jp/jYoshiori/)')]
        return opener

    def read_stream(self):
        res = self.getOpener('http://chirpstream.twitter.com/').open('http://chirpstream.twitter.com/2b/user.json')
        for line in res:
            if line.strip():
                yield simplejson.loads(line)

    def start(self):
        for data in self.read_stream():
            if data.get('event') == 'follow':
                self.event_follow(data)
                
    def event_follow(self,data):
        for func in self.follow_funcs:
            func(self,data)
        
    def add_follow_func(self,func):
        self.follow_funcs.append(func)
            
def main():
    log = logging.getLogger();
    log.addHandler(logging.FileHandler("twitter_follow_log"))
    log.setLevel(logging.INFO)
    
    twitter_config = Pit.get('twitter.com',{'require' : {
        'user' : 'Your twitter name',
        'password' : 'Your twitter password'}})

    userName = twitter_config['user']
    twitter = TwitterClone(userName,
                           twitter_config['password'],
                           'http://twitter.com/')

    my_id = twitter.show(userName)['id']

    def my_func(self,data):
        if data['target']['id'] == my_id:
            id = data['source']['id']
            try:
                id = data['source']['id']
                self.createFriend(id)
                log.info('ok %s' % id)
                print 'ok %s' % id
            except:
                log.warn('error %s' % id)
                print 'error %s' % id

    twitter.add_follow_func(my_func)
    twitter.start()
    
if __name__ == '__main__':
    main()


Perl の AnyEvent がどういうのかわからなかったので,
イベントが発生した時の関数を後から足せるような作りにしてみた.


yield かわいいよ yield

っていうか,初めて yield 有効活用出来た気がする……


あと、明日結婚します!!!
ウイッシュリストはこちら……

http://www.amazon.co.jp/wishlist/1U0XYA5QTEODM

http://www.amazon.co.jp/wishlist/1FPZ9YVV0PJ0S