LoginSignup
24
20

More than 3 years have passed since last update.

Tweepyの使い方 ~その2~ 【フォロー、いいねなど】

Posted at

はじめに

公式ドキュメントを参考にtweepyの使い方をまとめていこうと思います。
※前回: Tweepyの使い方 ~その1~ 【Tweetの取得】

事前準備

import tweepy
# 取得したAPIキー
consumer_key = '*********************************'
consumer_secret = '*************************************'
access_token = '*******************************************'
access_token_secret = '****************************************'

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

api = tweepy.API(auth)

フォロー/ フォロワー

フォロー, フォロワー数表示

以下のようにapi.me()で自分のアカウントのUser型が返されます。
返された値を見ると、'followers_count': 112のようにあることからapi.me().followers_countとすることで値を取得できます。
このdict型っぽいUser型のkeyを見ることで、同様に他の情報も取得することができます。

api.me()
# 長いので無視してかまいません。
>> User(_api=<tweepy.api.API object at 0x7efcf29adc50>, _json={'id': 1147865430297468928, 'id_str': '1147865430297468928', 'name': 'キタ', 'screen_name': 'ki_rii9', 'location': '日本 福岡', 'profile_location': None, 'description': 'python/ 機械学習/ flask/ Atcoder/ 初心者 競プロer 初心者 kaggler/ 九大B1/ GLEAP #TORYUMON #チャレキャラ', 'url': 'https://t.co/6QXllpbNqu', 'entities': {'url': {'urls': [{'url': 'https://t.co/6QXllpbNqu', 'expanded_url': 'https://qiita.com/kitarikes', 'display_url': 'qiita.com/kitarikes', 'indices': [0, 23]}]}, 'description': {'urls': []}}, 'protected': False, 'followers_count': 112, 'friends_count': 268, 'listed_count': 1, 'created_at': 'Sun Jul 07 13:50:19 +0000 2019', 'favourites_count': 807, 'utc_offset': None, 'time_zone': None, 'geo_enabled': False, 'verified': False, 'statuses_count': 135, 'lang': None, 'status': {'created_at': 'Thu Dec 26 17:50:38 +0000 2019', 'id': 1210256620657102849, 'id_str': '1210256620657102849', 'text': '知らないうちにReactが追加されていたので完走! !\n「React 学習コース Ⅳ」コースを修了しました! https://t.co/dAKcZhNNMS #Progate', 'truncated': False, 'entities': {'hashtags': [{'text': 'Progate', 'indices': [79, 87]}], 'symbols': [], 'user_mentions': [], 'urls': [{'url': 'https://t.co/dAKcZhNNMS', 'expanded_url': 'https://prog-8.com/lessons/react/study/4', 'display_url': 'prog-8.com/lessons/react/…', 'indices': [55, 78]}]}, 'source': '<a href="http://twitter.com" rel="nofollow">Twitter Web Client</a>', 'in_reply_to_status_id': None, 'in_reply_to_status_id_str': None, 'in_reply_to_user_id': None, 'in_reply_to_user_id_str': None, 'in_reply_to_screen_name': None, 'geo': None, 'coordinates': None, 'place': None, 'contributors': None, 'is_quote_status': False, 'retweet_count': 0, 'favorite_count': 6, 'favorited': False, 'retweeted': False, 'possibly_sensitive': True, 'lang': 'ja'}, 'contributors_enabled': False, 'is_translator': False, 'is_translation_enabled': False, 'profile_background_color': 'F5F8FA', 'profile_background_image_url': None, 'profile_background_image_url_https': None, 'profile_background_tile': False, 'profile_image_url': 'http://pbs.twimg.com/profile_images/1189529639242223622/YrkeODbb_normal.jpg', 'profile_image_url_https': 'https://pbs.twimg.com/profile_images/1189529639242223622/YrkeODbb_normal.jpg', 'profile_banner_url': 'https://pbs.twimg.com/profile_banners/1147865430297468928/1570725567', 'profile_link_color': '1DA1F2', 'profile_sidebar_border_color': 'C0DEED', 'profile_sidebar_fill_color': 'DDEEF6', 'profile_text_color': '333333', 'profile_use_background_image': True, 'has_extended_profile': True, 'default_profile': True, 'default_profile_image': False, 'can_media_tag': True, 'followed_by': False, 'following': False, 'follow_request_sent': False, 'notifications': False, 'translator_type': 'none', 'suspended': False, 'needs_phone_verification': False}, id=1147865430297468928, id_str='1147865430297468928', name='キタ', screen_name='ki_rii9', location='日本 福岡', profile_location=None, description='python/ 機械学習/ flask/ Atcoder/ 初心者 競プロer 初心者 kaggler/ 九大B1/ GLEAP #TORYUMON #チャレキャラ', url='https://t.co/6QXllpbNqu', entities={'url': {'urls': [{'url': 'https://t.co/6QXllpbNqu', 'expanded_url': 'https://qiita.com/kitarikes', 'display_url': 'qiita.com/kitarikes', 'indices': [0, 23]}]}, 'description': {'urls': []}}, protected=False, followers_count=112, friends_count=268, listed_count=1, created_at=datetime.datetime(2019, 7, 7, 13, 50, 19), favourites_count=807, utc_offset=None, time_zone=None, geo_enabled=False, verified=False, statuses_count=135, lang=None, status=Status(_api=<tweepy.api.API object at 0x7efcf29adc50>, _json={'created_at': 'Thu Dec 26 17:50:38 +0000 2019', 'id': 1210256620657102849, 'id_str': '1210256620657102849', 'text': '知らないうちにReactが追加されていたので完走! !\n「React 学習コース Ⅳ」コースを修了しました! https://t.co/dAKcZhNNMS #Progate', 'truncated': False, 'entities': {'hashtags': [{'text': 'Progate', 'indices': [79, 87]}], 'symbols': [], 'user_mentions': [], 'urls': [{'url': 'https://t.co/dAKcZhNNMS', 'expanded_url': 'https://prog-8.com/lessons/react/study/4', 'display_url': 'prog-8.com/lessons/react/…', 'indices': [55, 78]}]}, 'source': '<a href="http://twitter.com" rel="nofollow">Twitter Web Client</a>', 'in_reply_to_status_id': None, 'in_reply_to_status_id_str': None, 'in_reply_to_user_id': None, 'in_reply_to_user_id_str': None, 'in_reply_to_screen_name': None, 'geo': None, 'coordinates': None, 'place': None, 'contributors': None, 'is_quote_status': False, 'retweet_count': 0, 'favorite_count': 6, 'favorited': False, 'retweeted': False, 'possibly_sensitive': True, 'lang': 'ja'}, created_at=datetime.datetime(2019, 12, 26, 17, 50, 38), id=1210256620657102849, id_str='1210256620657102849', text='知らないうちにReactが追加されていたので完走! !\n「React 学習コース Ⅳ」コースを修了しました! https://t.co/dAKcZhNNMS #Progate', truncated=False, entities={'hashtags': [{'text': 'Progate', 'indices': [79, 87]}], 'symbols': [], 'user_mentions': [], 'urls': [{'url': 'https://t.co/dAKcZhNNMS', 'expanded_url': 'https://prog-8.com/lessons/react/study/4', 'display_url': 'prog-8.com/lessons/react/…', 'indices': [55, 78]}]}, source='Twitter Web Client', source_url='http://twitter.com', in_reply_to_status_id=None, in_reply_to_status_id_str=None, in_reply_to_user_id=None, in_reply_to_user_id_str=None, in_reply_to_screen_name=None, geo=None, coordinates=None, place=None, contributors=None, is_quote_status=False, retweet_count=0, favorite_count=6, favorited=False, retweeted=False, possibly_sensitive=True, lang='ja'), contributors_enabled=False, is_translator=False, is_translation_enabled=False, profile_background_color='F5F8FA', profile_background_image_url=None, profile_background_image_url_https=None, profile_background_tile=False, profile_image_url='http://pbs.twimg.com/profile_images/1189529639242223622/YrkeODbb_normal.jpg', profile_image_url_https='https://pbs.twimg.com/profile_images/1189529639242223622/YrkeODbb_normal.jpg', profile_banner_url='https://pbs.twimg.com/profile_banners/1147865430297468928/1570725567', profile_link_color='1DA1F2', profile_sidebar_border_color='C0DEED', profile_sidebar_fill_color='DDEEF6', profile_text_color='333333', profile_use_background_image=True, has_extended_profile=True, default_profile=True, default_profile_image=False, can_media_tag=True, followed_by=False, following=False, follow_request_sent=False, notifications=False, translator_type='none', suspended=False, needs_phone_verification=False)

# 例
api.me().followers_count
# フォロワー数確認
>> 112

api.me().friends_count
# フォロー数確認
>> 268

api.me().description
# プロフィールコメント表示
>> 'python/ 機械学習/ flask/ Atcoder/ 初心者 競プロer 初心者 kaggler/ 九大B1/ GLEAP #TORYUMON #チャレキャラ'

フォロー, フォロワーのユーザー情報取得

api.friends()でフォローしているユーザーの情報を取得できます。
デフォルトでは20個分取得できますが、引数にcount=100などとすることで最大値を指定できます。

len(api.friends())
# フォローしているユーザーのUser型のリストを取得
>> 20

len(api.friends(count=100))
>> 100

これはリスト型を返しているので、このままfor文を使ったループ処理を行うことができます。

for user in api.friends(count=100):
  if user.followed_by :
    # フォローが返ってきているユーザーのみ表示
    print(user.name)

len([user.name for user in api.friends(count=100) if user.followed_by])

>> 40

user.nameで名前を表示するのは気が引けるので、len()で数だけ......(40/100)

指定したユーザーのフォロー

api.create_friendship()でフォローすることができます。
引数にid(User型.idで取得できる垢固有のid)やscreen_name(@以下)で指定できます。
以下の例ではqiitaの公式アカウントをフォローしてみます。

api.create_friendship(screen_name='Qiita')

同様にapi.destroy_friendship(id/screen_name/user_id)でフォロー解除できたり、api.show_friendship(source_id/source_screen_name, target_id/target_screen_name)でアカウント間のフォロー関係を見ることができます。(詳しくはドキュメント参照)

いいね!

いいねしたツイートの表示

api.favorites()でいいねしたツイートを参照することができます。
デフォルトでは自分のアカウントのいいね情報が返され、これまでと同様にidやscreen_nameでユーザーを指定し、countで取得する最大数を指定します。

# 例
api.favorites(screen_name='ki_rii9', count=50)
# 注意:自分のアカウントです。フォローよろしくお願いします。(?)

ツイートへのいいね!

api.create_favorite(id)でいいね!できます。
試しに、タイムラインの一番上にあるツイートをいいねしようと思います。

api.create_favorite(id=api.home_timeline()[0].id)

api.destroy_favorite(id)で解除も可能です。

おわりに

APIを使ってフォローやツイートへのいいね!ができるようになりました。
次回は(次回があれば...)自動いいね、自動フォローを使ってフォロワー増加を試みようと思います。

24
20
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
24
20