CLOVER🍀

That was when it all began.

Tweepyを使って、PythonからTwitterにアクセスする

これは、なにをしたくて書いたもの?

データソースとしてTwitterはけっこう使えるので、Pythonでも扱えるようにしたいな、ということで。

PythonでのTwitterクライアントを、ちょっと探して試してみることにしました。

PythonでのTwitterクライアント

ちょっと探しただけでも、いろいろ見つかりましたね。

Tweepy

Welcome to python-twitter’s documentation! — python-twitter 3.4.2 documentation

Python Twitter Tools (command-line client and IRC bot)

いずれも開発はすでに落ち着いているみたいですが、Streamingを使いたかったことと、Star数からTweepyを試してみることに
しました。

Tweepy

GitHubで見てみると、説明は

Tweepy: Twitter for Python!

という感じです。ええ、シンプル。

Tweepy

GitHub - tweepy/tweepy: Twitter for Python!

ドキュメントは、こちら。

Tweepy Documentation — tweepy 3.9.0 documentation

APIリファレンスは、こちら。

API Reference — tweepy 3.9.0 documentation

よくよく見ると、APIリファレンスだけでは足りないことに気づくのですが、それはあとで補足します。

環境

今回の環境は、こちら。

$ python3 -V
Python 3.8.2

簡単に使ってみる

では、使っていってみましょう。

まずはインストール。

Installation — tweepy 3.9.0 documentation

今回は、Tweepyの3.9.0を使用します。

$ pip3 install tweepy==3.9.0

Getting Startedを見ながら進めていってみましょう。

Getting started — tweepy 3.9.0 documentation

これ以降はPythonコードが登場しますが、以下のimport文があることを前提としています。

import os

import tweepy

Tweepyを使うということはTwitter APIを呼び出すことになるので、Twitter APIのConsumer Key、Consumer Secret、
Access Token、Access Token Secretが必要になります。これらは今回は環境変数に埋め込んでおくことにします。

$ export TWITTER_CONSUMER_KEY=...
$ export TWITTER_CONSUMER_SECRET=...
$ export TWITTER_ACCESS_TOKEN=...
$ export TWITTER_ACCESS_TOKEN_SECRET=...

環境変数に設定した値を、Pythonコードから取得。

consumer_key = os.environ['TWITTER_CONSUMER_KEY']
consumer_secret = os.environ['TWITTER_CONSUMER_SECRET']

access_token = os.environ['TWITTER_ACCESS_TOKEN']
access_token_secret = os.environ['TWITTER_ACCESS_TOKEN_SECRET']

認証・認可設定と、API用のオブジェクトを作成します。

auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)

api = tweepy.API(auth)

これで、Tweepyを使用する準備が整いました。

以下、簡単なサンプルを載せていきます。

タイムラインの取得。

public_tweets = api.home_timeline()
for tweet in public_tweets:
    print(tweet.text)

自分のツイートの取得。

user_tweets = api.user_timeline()
for tweet in user_tweets:
    print(tweet.text)

ツイートする。

api.update_status('[ツイート内容]')

ユーザーの情報を取得する。

user = api.get_user('[id or user_id or screen_name]')
print('screen_name = ' + user.screen_name)

検索する。

search_results = api.search('[クエリ]')
for tweet in search_results:
    print(tweet.text)

APIリファレンスはあるにはあるのですが、正直足りません。特に、戻り値のオブジェクトの情報がこれだとわかりません。

API Reference — tweepy 3.9.0 documentation

というわけで、ソースコードを見てみます。

https://github.com/tweepy/tweepy/blob/v3.9.0/tweepy/api.py

各メソッドに、実際に使用するTwitter APIのドキュメントのURLが埋め込まれているので、こちらを確認すると良いでしょう。

    @property
    def home_timeline(self):
        """ :reference: https://developer.twitter.com/en/docs/tweets/timelines/api-reference/get-statuses-home_timeline
            :allowed_param: 'since_id', 'max_id', 'count'
        """
        return bind_api(
            api=self,
            path='/statuses/home_timeline.json',
            payload_type='status', payload_list=True,
            allowed_param=['since_id', 'max_id', 'count'],
            require_auth=True
        )

オブジェクトの情報としては、こちらも参考になるでしょう。

Introduction to Tweet JSON | Docs | Twitter Developer

その他、参考に。

Code Snippets — tweepy 3.9.0 documentation

Cursor Tutorial — tweepy 3.9.0 documentation

Extended Tweets — tweepy 3.9.0 documentation

ストリーミング

最後に、ストリーミングをやってみます。

Streaming With Tweepy — tweepy 3.9.0 documentation

StreamListenerを継承したクラスを作成して

class MyStreamListener(tweepy.StreamListener):
    def on_status(self, status):
        print(status.text)

Streamに登録します。

streamListener = MyStreamListener()
stream = tweepy.Stream(auth = api.auth, listener=streamListener)

あとは、filterを呼び出すとストリーミングが始まります。

stream.filter(track=['[query]'])

is_asyncTrueにしておくと、ストリームの受信は別スレッドで行われるようになります。

stream.filter(track=['[query]'], is_async = True)

デフォルトでは、filterはずっとブロックします。

ストリーミングに関しては、前述の情報以外にドキュメントがなく、APIリファレンスもありません。

というわけで、ソースコードを見ます。

https://github.com/tweepy/tweepy/blob/v3.9.0/tweepy/streaming.py

実際に使用しているストリーミングのエンドポイントもけっこう簡単にわかるので、これで良いでしょう。

https://github.com/tweepy/tweepy/blob/v3.9.0/tweepy/streaming.py#L451-L452

https://github.com/tweepy/tweepy/blob/v3.9.0/tweepy/streaming.py#L457

        self.url = '/%s/statuses/filter.json' % STREAM_VERSION

これで、TwitterへのアクセスはPythonからもできそうです。