LoginSignup
25
28

More than 5 years have passed since last update.

pipでtweepyをインストールしてAPI1.1に対応させて使う

Posted at

環境はWindows64bitのPython2.7.3です(まあ関係ないと思うけど)

1. pipのインストール

コマンドプロンプト(or ターミナル)で実行
> easy_install pip

2. tweepyのインストール

コマンドプロンプトで実行
> pip install tweepy
インストールしたらPythonインタプリタ(対話型)で
> import tweepy
して確認しましょう。

3.tweepyを使う

tweepyはpipでインストールできるバージョンはまだAPI1.0のものです。Githubなんかには1.1対応のものがとっくにありますが、pipは導入が楽なのでpipで済むならpipで済ませたいですよね!(git弱者)
スクリプトを書くにあたって、twitterのCK/CS、アクセストークンのデータはすでに取得済みとします。
tweepyでAPIを操作するためのインスタンスを作るのは以下のような流れです

import tweepy

auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
api = tweepy.API(auth_handler=auth, api_root='/1.1', secure=True)

tweepy.APIクラスのコンストラクタにapi_root属性で'/1.1'を入れてあげる事で基本的にはAPI1.1対応ができます。

api.update_status(raw_input())

みたいな感じで投稿ができます。

これだけでうまくいかないケース

API1.0から1.1に変わるときにエンドポイントの構造が変わったAPIがいくつかあります。
今回はツイートを削除するdestroy_status関数を例に取ります
tweepy.APIクラスではdestroy_status関数は次のように宣言されてます

from tweepy.binder import bind_api

destroy_status = bind_api(
                path = '/statuses/destroy.json',
                method = 'DELETE',
                payload_type = 'status',
                allowed_param = ['id'],
                require_auth = True
                )

bind_apiはtweepyがAPIを叩くときに使う関数をラッピングしたクラスです(多分)
API1.1で、statuses/destroyのエンドポイントは/statuses/destroy/{id}.jsonに変わっています。
今回は次のようにしてみました

import tweepy
from tweepy.binder import bind_api

auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
api = tweepy.API(auth_handler=auth, api_root='/1.1', secure=True)

destroy_status_1_1 = bind_api(
                path = '/statuses/destroy/{id}.json',
                method = 'POST',
                payload_type = 'status',
                allowed_param = ['id'],
                require_auth = True
                )
destroy_status_1_1(api, raw_input()) #APIインスタンスとstatus_idを渡す

これでAPI1.1に対応したスクリプトが書けました。

25
28
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
25
28