日記

更新頻度はあまり高くはありませんがネタがあったら書いていこうと思います。

Python+tweepyで自動フォロー装置を作った。

PythonでTwitterAPIを使ってみました。 PythonにはtweepyというTwitterAPIのラッパーライブラリがあるのでそれを使ってみました。

こんな感じになりました。

def followAndUnfollow(api):
    followersIds = api.followers_ids()
    friendsIds = api.friends_ids()


    #フォロアーにそのユーザが存在しなければアンフォロー
    for friendId in friendsIds:
        count = 0
        for followerId in followersIds:
            if friendId==followerId:
                break
            count+=1   
        if count == len(followersIds):
            try:
                api.destroy_friendship(friendId)
                print 'Destoroyed friendship with %s' %friendId
            except tweepy.error.TweepError:
                print 'I could not destroy this friendship.:('

    #フォローしていないフォロアーがいればフォロー
    for followerId in followersIds:
        count=0
        for friendId in friendsIds:
            if followerId == friendId:
                break
            count += 1
        if count == len(friendsIds):
            try:
                api.create_friendship(followerId, True)
                print 'Created friendship with %s :)' %followerId
            except tweepy.error.TweepError:
                print 'I could not create this friendship.:('

あとはこれを適当なサーバにデプロイしてスケジューラで実行すれば、勝手にフォロー、アンフォローをしてくれると思います。

たまにidを参照できずにエラーが出るので例外処理を入れました。