talosのプログラミング教室

【Python】Twitter APIで一方的にフォローしている人を洗い出して自動フォロー解除する【2022年1月版】

スポンサーリンク

こんにちは。たろすです。

以前このような記事を書いたのですが、tweepy(4.0.0以降)の仕様が変わっていたので修正しました。

talosta.hatenablog.com

変更点

・idがuser_idに置き換わっている
api.get_user()がキーワード引数しか受け付けなくなった
api.destroy_friendship()がキーワード引数しか受け付けなくなた

コード

前回は
・フォロワー、フォローしている人を取得
・一方的にフォローしている人を抽出
・一方的にフォローしている人をリムーブ
を別プログラムにしていましたが、今回は一つにまとめました。

import tweepy
import pandas as pd
import os
import datetime

CK = '****'    # API KEY
CS = '****'    # API secret key
AT = '****'    # Access token
AS = '****'    # Access token secret

auth = tweepy.OAuthHandler(CK, CS)
auth.set_access_token(AT, AS)
api = tweepy.API(auth, wait_on_rate_limit=True)
user_id = 'XXXX'  # <- あなたのユーザーID

cols = ['user_id']
follower_ids = pd.DataFrame([], columns=cols)
following_ids = pd.DataFrame([], columns=cols)

# フォロワーの取得
print('フォロワーを取得中...', end='')
itr = tweepy.Cursor(api.get_follower_ids, user_id=user_id, cursor=-1).items()
for follower_id in itr:
    record = pd.Series([follower_id], index=follower_ids.columns)
    follower_ids = follower_ids.append(record, ignore_index=True)
print(' Done')

# フォローしている人の取得
print('フォローしている人を取得中...', end='')
itr = tweepy.Cursor(api.get_friend_ids, user_id=user_id, cursor=-1).items() 
for following_id in itr:
    record = pd.Series([following_id], index=following_ids.columns)
    following_ids = following_ids.append(record, ignore_index=True)
print(' Done')

oneside_follow = pd.DataFrame([], columns=['user_id', 'name', 'screen_name', 'description'])

# 一方的にフォローしている人を抽出
print('一方的にフォローしている人を取得中...', end='')
for following_id in following_ids['user_id']:
    if following_id not in follower_ids['user_id'].values:
        user = api.get_user(user_id=following_id)
        record = pd.Series([user.id, user.name, user.screen_name, user.description], index=oneside_follow.columns)
        oneside_follow = oneside_follow.append(record, ignore_index=True)
print(' Done')

removed_users = pd.DataFrame([], columns=['user_id', 'name', 'screen_name', 'description'])

# 一方的にフォローしている人をリムーブする
print('以下のユーザーへのフォローを解除しました。')
for i, user in oneside_follow.iterrows():
    api.destroy_friendship(user_id=user.user_id)
    removed_users = removed_users.append(user, ignore_index=True)
    print('  アカウント名:' + user['name'] + ' / ユーザー名:' + user['screen_name'])

dir = os.path.dirname(__file__) + '/csv'
try:
    os.makedirs(dir)
except FileExistsError:
    pass
removed_users.to_csv(dir + '/removed_users_' + datetime.datetime.now().strftime('%y%m%d%H%M%S') + '.csv')

おわりに

tweepyの仕様の変更に対応しました。