以前、一度twitter APIによるフォロー自動化ツールを作成しました。
今回は、さらにアンフォロー化を実装したプログラムを記載したいと思います。
自動化プログラムのための準備
以下に、以前作成したフォロー自動化ツールの記事を載せておきますので、興味のある方は一読して頂けると幸いです。
【Python】twitterでの検索キーワードからフォロー自動化
必要なモジュール
今回作成するツールも、APIに使用するキーを取得していることを前提に進めていきます。
今回利用するモジュールは、、、
・tweepy
・time
上記で挙げたモジュールをインポートして利用していきます。
それでは、ファイルエディタウィンドウを開いて、任意の名前.pyのファイルを作成・保存してください。
フォロー・アンフォロー自動化ツール
def get_api():
keys = dict(
screen_name = 'xxxxxxxx',
consumer_key = 'xxxxxxxx',
consumer_secret = 'xxxxxxxx',
access_token = 'xxxxxxxx',
access_token_secret = 'xxxxxxxx',
)
SCREEN_NAME = keys['screen_name']
CONSUMER_KEY = keys['consumer_key']
CONSUMER_SECRET = keys['consumer_secret']
ACCESS_TOKEN = keys['access_token']
ACCESS_TOKEN_SECRET = keys['access_token_secret']
auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
auth.set_access_token(ACCESS_TOKEN, ACCESS_TOKEN_SECRET)
api = tweepy.API(auth)
return api, SCREEN_NAMEここでは、APIに使用するキーをそれぞれ取得し、利用できるよう変数に格納しています。こういったAPIに関するプログラムでは馴染みのものですね。
def unfollow(api, followers, friends):
unfollow_cnt = 0
for f in friends:
if f not in followers:
if unfollow_cnt <= 100:
api.destroy_friendship(f)
print("{0}のフォローを解除しました。".format(api.get_user(f).screen_name))
time.sleep(2)
unfollow_cnt += 1
else:
print('一度に解除可能な人数に達したため処理を中断します。')
break
return unfollow_cntここでは、アンフォローに関する関数を定義しています。
それぞれ引数として、api, followes, friendsといった変数を用いています。unfollow_cntをif文の分岐に対する変数として考慮して、実装しています。
def follow(keyword, a_cnt):
follow_cnt = 0
# 検索ワードと追加フォロー数をセットし検索実行
search_results = api.search(q=keyword, count=a_cnt)
for result in search_results:
if follow_cnt <= a_cnt:
try:
screen_id = result.user._json["screen_name"]
api.create_friendship(screen_id)
print("{0}をフォローしました。" .format(screen_id))
time.sleep(2)
follow_cnt += 1
except tweepy.error.TweepError:
print("フォローが失敗しました。")
return follow_cntここでは、フォローに関する関数を定義しています。それぞれ引数として、keyword, a_cntといった変数を用いています。
また、関数として定義した内容として参考URLの記事で説明しているため、興味のある方は一読してみてください。
def yes_no_input(choice):
while True:
if choice in ['y', 'Y']:
return True
else:
return False
if __name__ == "__main__":
u_cnt = 0
f_cnt = 0
api, SCREEN_NAME = get_api()
followers = api.followers_ids(SCREEN_NAME)
friends = api.friends_ids(SCREEN_NAME)
choice = input("フォロー解除を実行しますか? [y/N]: ").lower()
if yes_no_input(choice):
u_cnt = unfollow(api, followers, friends)
keyword = input("検索ワード:")
a_count = input("追加フォロー数:")
a_cnt = int(a_count)
choice = input("フォローを実行しますか? [y/N]: ").lower()
if yes_no_input(choice):
f_cnt = follow(keyword, a_cnt)
print('{}人をフォロー解除、{}人をフォローしました。'.format(u_cnt,f_cnt))
input()ここでは、処理に関するコードを記載しています。yes_no_input関数の定義内容について、下記に記載した処理でのchoice変数の値によって処理を実行するかしないか判断するものとなっています。
それぞれyes_no_input関数で処理選択を行ったのち、自動化機能の関数に関して必要な変数を決定しています。
★ follow-unfollow.py ★
import tweepy
import time
def get_api():
keys = dict(
screen_name = 'xxxxxxxx',
consumer_key = 'xxxxxxxx',
consumer_secret = 'xxxxxxxx',
access_token = 'xxxxxxxx',
access_token_secret = 'xxxxxxxx',
)
SCREEN_NAME = keys['screen_name']
CONSUMER_KEY = keys['consumer_key']
CONSUMER_SECRET = keys['consumer_secret']
ACCESS_TOKEN = keys['access_token']
ACCESS_TOKEN_SECRET = keys['access_token_secret']
auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
auth.set_access_token(ACCESS_TOKEN, ACCESS_TOKEN_SECRET)
api = tweepy.API(auth)
return api, SCREEN_NAME
def unfollow(api, followers, friends):
unfollow_cnt = 0
for f in friends:
if f not in followers:
if unfollow_cnt <= 100:
api.destroy_friendship(f)
print("{0}のフォローを解除しました。".format(api.get_user(f).screen_name))
time.sleep(2)
unfollow_cnt += 1
else:
print('一度に解除可能な人数に達したため処理を中断します。')
break
return unfollow_cnt
def follow(keyword, a_cnt):
follow_cnt = 0
# 検索ワードと追加フォロー数をセットし検索実行
search_results = api.search(q=keyword, count=a_cnt)
for result in search_results:
if follow_cnt <= a_cnt:
try:
screen_id = result.user._json["screen_name"]
api.create_friendship(screen_id)
print("{0}をフォローしました。" .format(screen_id))
time.sleep(2)
follow_cnt += 1
except tweepy.error.TweepError:
print("フォローが失敗しました。")
return follow_cnt
def yes_no_input(choice):
while True:
if choice in ['y', 'Y']:
return True
else:
return False
if __name__ == "__main__":
u_cnt = 0
f_cnt = 0
api, SCREEN_NAME = get_api()
followers = api.followers_ids(SCREEN_NAME)
friends = api.friends_ids(SCREEN_NAME)
choice = input("フォロー解除を実行しますか? [y/N]: ").lower()
if yes_no_input(choice):
u_cnt = unfollow(api, followers, friends)
keyword = input("検索ワード:")
a_count = input("追加フォロー数:")
a_cnt = int(a_count)
choice = input("フォローを実行しますか? [y/N]: ").lower()
if yes_no_input(choice):
f_cnt = follow(keyword, a_cnt)
print('{}人をフォロー解除、{}人をフォローしました。'.format(u_cnt,f_cnt))
input()
出力結果
それでは!!
また、今後もプログラミングに取り組み続けていく中で、実務に利用できる学びを身につけていかなければなりません。
エンジニアの中でもいくつか学ぶ技術は変化しますが、ここではWebスクレイピング・テキストマイニング・機械学習等をご紹介しています。
エンジニアでなくても取り組みたい業務効率化・自動化に関する実務へのヒントとなったPython本をまとめた記事がありますので、そちらも合わせて参照して頂ければ幸いです。

















