python-twitterで各種情報を取得

Twitterのアカウントを作って10年にもなる。だらだら使いつつ、フォロー/フォロアーの数がビミョーに減ったりすると気になって仕方がない。でもユーザー一覧を見てもだれが減ったのか思い出せないのは切ない。ということでTwitter APIを使って定期的に自動収集する仕組みを作って自己満足しよう。

前提

help.twitter.com

  • Unix環境にanyenv/pyenvを導入する

github.com

(当方のUnix環境はVPSCentOS 6が動いているが、Python 3.7 以降のインストールに失敗するので、Python 3.6.10 で動かす)

github.com

python-twitter のドキュメント

python-twitter.readthedocs.io

すべてはここに書いてあるので、英語は頑張って読もう

cronで自動実行するとき

pyenvのpythonバイナリはフルパスで指定するとよい

PYTHON="$HOME/.anyenv/envs/pyenv/shims/python"

API アクセスするためのインスタンスを生成

import twitter

API_KEY = 'ULB.........'
API_SECRET_KEY = 'A8e........'
ACCESS_TOKEN = '99999999-4DX........'
ACCESS_TOKEN_SECRET = 'dXj........'

api = twitter.Api(consumer_key=API_KEY,
                  consumer_secret=API_SECRET_KEY,
                  access_token_key=ACCESS_TOKEN,
                  access_token_secret=ACCESS_TOKEN_SECRET)

フォローしているユーザー一覧の取得

next_cursor = -1
watchdog = 50

while watchdog > 0:
  watchdog = watchdog - 1

  next_cursor, prev_cursor, friends = api.GetFriendsPaged(cursor=next_cursor)

  for friend in friends:
    id = friend.id
    screen_name = friend.screen_name
    #print(id, screen_name)

  if next_cursor <= 0:
    break

GetFriendsPaged()は、1コールで200人の情報を取得できる。201人以上フォローしているときは、戻り値のnext_cursorが 0 以外の値になるため、その値を名前引数cursorに渡すことで次のページを取得できる。これを繰り返すとよい。
watchdogはwhileループの無限実行防止用のウォッチドッグタイマを模したもの)
戻り値friendsは、ユーザーの配列である。ユーザーは辞書型で、キー名はUser object — Twitter Developersを参照のこと。

フォローされているユーザー一覧の取得

next_cursor = -1
watchdog = 50

while watchdog > 0:
  watchdog = watchdog - 1

  next_cursor, prev_cursor, followers = api.GetFollowersPaged(cursor=next_cursor)

  for follower in followers:
    id = follower.id
    screen_name = follower.screen_name
    #print(id, screen_name)

  print(next_cursor, len(followers))
  if next_cursor <= 0:
    break

GetFriendsPaged()の代わりにGetFollowersPaged()を使う以外はフォローしているユーザーを取得する方法と同じ。

リストの取得と、リストに登録されているメンバー一覧取得

lists = api.GetLists()

for list in lists:
  list_id = list.id
  list_slug = list.slug

  watchdog = 50
  next_cursor = -1

  while watchdog > 0:
    watchdog = watchdog - 1

    next_cursor, prev_cursor, members = api.GetListMembersPaged(list_id=list_id,cursor=next_cursor)

    for member in members:
      id = member.id
      screen_name = member.screen_name
      #print(list_slug, "\t", screen_name, "\t", id)

    if next_cursor <= 0:
      break

GetLists()は、リスト辞書の配列を返す(要素数は最大100)。辞書のキーはGET lists/list — Twitter Developersを参照のこと。slugはリストに付けた名前が格納されている。なぜslugなのだろう...
GetListMembersPagedは、リストの内部IDを名前引数list_idに渡すことで、リストに登録されたユーザーの一覧を1ページあたり100人取得できる。101人以上登録しているリストは、前述のようにカーソル値で順次取得していく。

スクリーンネームからIDを取得

SCREEN_NAME = 'specified_screen_name'
user = api.GetUser(screen_name=SCREEN_NAME)

print(SCREEN_NAME, user.id)

特定のユーザーを認識するには、ユーザー自身が変更できるスクリーンネームよりも、APIで取得できるIDが良い。
このユーザーオブジェクトから、statusprotectedの両属性を確認することで、自分から見たそのユーザーの状態が分かる。

  status が取得できる status が未設定
protected = true 鍵アカウント ブロックされている
protected が未設定 通常アカウント ブロックされている

※ツイート数が0の場合も、statusは未設定になる