前回の記事:【Python】TwitterのAPIを簡単操作できる「Tweepy」の使い方
こんにちは、ミナピピン(@python_mllover)です!
今日は前回紹介した「Tweepy」というTwitterのAPIをラッピングして簡単に触れるようにしたライブラリを使用して、自分のアカウントのフォローとフォロワーを管理をしていきたいと思います。
要はTwitterのAPIを使って相互フォローしていないユーザーを検索し、フォロワー数に応じてリムるだけです。
Tweepyで相互フォロー管理
コードはgithubにあげているので、そこから引っ張ってきます。
import tweepy
api_dict = {
'my_account_id':['api_pub',
'api_sec',
'access_token',
'access_token_secret'
]
}
# フォローしていなくても外さないアカウントのリスト(リストの中身は例)
unrequited_list = {
'my_account_id':['MSkieller',
'BitcoinSVinfo',
'_unwriter',
'excalibur0922',
'money_button'
]
}
for k, v in api_dict.items():
consumer_key = v[0]
consumer_secret = v[1]
access_token = v[2]
access_secret = v[3]
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_secret)
api = tweepy.API(auth)
#自分のuserid
userid = k
try:
#自分のアカウントのフォロワーをすべて取得する
followers_id = api.followers_ids(userid)
#自分のアカウントのフォローをすべて取得する
following_id = api.friends_ids(userid)
#フォローされていなくてもOKなアカウントの情報を上の辞書から取得
unrequited = unrequited_list[k]
#辞書に登録されているユーザーを1人ずつフォロワーリストに追加
for i in unrequited:
try:
sp_id = api.get_user(i)._json['id']
followers_id.append(sp_id)
except Exception as e:
print(i, e.args)
# API制限などのカウント用変数を定義
api_limit = 0
unfollow_user = 0
follow_user = 0
# フォローしているのにフォロワーにいないユーザーのフォローを解除する
for following in following_id:
if following not in followers_id and api_limit < 40:
userfollowers = api.get_user(following).followers_count
# フォロワー数が10000人以下で自分をフォローしていないユーザーを除外する
if userfollowers < 10000:
username = api.get_user(following).name
print("リムーブするユーザー名", username)
print("フォロワー数", userfollowers)
# フォローを外す
api.destroy_friendship(following)
api_limit += 1
unfollow_user += 1
# フォローを返していないユーザーにフォローを返す
for follower in followers_id:
if follower not in following_id and api_limit < 40:
try:
username = api.get_user(follower).name
print("フォローするユーザー名", username)
api.create_friendship(follower)
api_limit += 1
follow_user += 1
except Exception as e:
e_msg = e.args[0][0]['code']
# api制限に引っかかった場合(エラーコード161)はループ終了
if e_msg == 161:
break
# それ以外の場合はエラーメッセージを表示
else:
print(e.args)
print(f'リムったユーザーは{unfollow_user}人です')
print(f'フォローしたユーザーは{follow_user}人です')
except Exception as e:
print(f'{k}のAPI操作でエラーが発生しました')
print(e.args)
参照:https://github.com/beginerSE/twitter_follow_follower_confirm/blob/master/twitter_ff_confirm.py
if文にapi_limit < 40という条件式を加えているのは一度のアクセスで100人くらいリムーブとフォローをするとエラーになるので、付け加えています。
ガバガバなので、よくわからない部分があればツイッターの方で質問していただけると幸いです。
終わり
こんな性格の悪いスクリプトを書いておいていうのもなんですが、フォローしてるとかしてないとか考えずに、爽やかな気分でSNSをやりたいものですね。

コメント
[…] 関連記事:【Python】Tweepyで相互フォローの確認&フォロバとリムーブを自動化 […]
[…] 関連記事:【Python】Tweepyで相互フォローの確認;フォロバとリムーブを自動化 […]
[…] 関連記事:【Python】Tweepyで相互フォローの確認&フォロバとリムーブを自動化 […]