LoginSignup
12
6

More than 5 years have passed since last update.

tweepyでtwitterのリスト周りを触る

Posted at

こんにちは、@yushun_oです。
yushun.meでソフト公開してます。よかったら見てください。
最近tweepyを使って遊んでいたのですが、思ったよりtwitterのリスト周りの日本語の情報が少なくて困ってしまったので、自分の使いそうなところをまとめておきました。
念のため環境を書いておきます。
Mac OS X Yosemite
Python 3.5.2

準備

pip install tweepy
でtweepyをインストール

https://apps.twitter.com/
ここで"Create New App"してCONSUMER_KEY等々を取得

myauth.py
# -*- coding:utf-8 -*-
import tweepy

CONSUMER_KEY = "xxx"
CONSUMER_SECRET = "xxx"
auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
ACCESS_TOKEN = "xxx"
ACCESS_SECRET = "xxx"
auth.set_access_token(ACCESS_TOKEN, ACCESS_SECRET)
api = tweepy.API(auth)

これでfrom myauth import apiでapiがいつでも呼び出せます。

tweepyでリストを触る

さっそく、今回の本題であるtwitterのリスト周りを触っていきます。

リストの作成/削除

create_destory_list.py
from myauth import api
screen_name="" #リスト作成者の@~~の~~
listname="" #リストの名前
api.destroy_list(owner_screen_name=screen_name,slug=listname)  #slug...リスト名が日本語のときは注意*1
api.create_list(name="作りたいリストの名前",mode="public",description="説明") #modeは、"public"か"private"で公開、非公開を選べる

*1..."mylist"という名前のリストを作成した場合は、そのままslug="mylist"となりますが、"マイリスト"という名前のリストを作成した場合は、slug="list○"という風になってしまいます。対処法は後述します。

リスト一覧を取得

get_all_list.py
from myauth import api
screen_name="" #リスト作成者の@~~の~~
for twilist in api.lists_all(screen_name=screen_name):
    print("slug="+twilist.slug)
    print("name="+twilist.name)

各Listクラスのslugとnameを出力してます。
僕は、日本語の名前のリストのときslugを特定する方法をこれしか知りません。(ご存知の方いたら教えてください。)
tweepyでリストを扱うときは、リストの名前を英語にすることをおすすめします。

リストのユーザーを取得

最後にリストに追加されてるユーザーを取得する方法です。tweepyのCursorクラスを使って取得します。

get_member_of_list.py
from myauth import api
screen_name="" #リスト作成者の@~~の~~
listname="" #リストの名前
for member in tweepy.Cursor(api.list_members,slug=listname,owner_screen_name=screen_name).items():
    print(member.screen_name)

おわりに

注意するところは、slugの部分くらいだったと思います。
list周りの全てを触れることはできてないので、この記事で足りなければ本家(github)を参考にしてください。
https://github.com/tweepy/tweepy/blob/master/tweepy/api.py
拙い記事でしたが、tweepyはほんとに使いやすいので、ぜひ皆さん使ってみてください。

12
6
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
12
6