17
21

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

TwitterAPIで自動フォロー返しする

Last updated at Posted at 2015-04-26

前書き

Twitterでリクエストがあったのでサンプルを掲載します。

  • ストリーミングで継続的に監視する方法を紹介しますが、cronで定期実行する場合でもストリーミング関連の部分を削除するだけで対応可能です。
  • ライブラリにはTwistOAuthを使用しますが、他のライブラリでも方法は類似しているはずです。
  • ToS的には怪しいですが、運用上自動リムーブ返しがないとフォロー数規制で困るケースがあるので、参考程度にこれも込みのソースにさせていただきます。不要な場合この部分は消してください。
  • 並列リクエスト可能ですが、Twitterにアクセス拒否される要因になるので、あえて逐次リクエストにしています。

ソースコード

ストリーミング利用時・cron利用時ともに必要なコード

<?php

// ライブラリをロード
require 'TwistOAuth.phar';

// テキストとして結果を表示
header('Content-Type: text/plain; charset=utf-8');

// 実行時間を無制限にする
set_time_limit(0);

// APIキー設定
$ck = '***コンシューマーキー***';
$cs = '***コンシューマーシークレット***';
$at = '***アクセストークン***';
$as = '***アクセストークンシークレット***';

// インスタンス生成
$to = new TwistOAuth($ck, $cs, $at, $as);

// カーソルを追跡して全てのIDを配列として取得するクロージャ
// 但し高速化のためキーに格納する
$get_all_ids = function ($endpoint) use ($to) {
    $ids = [];
    $params = [
        'stringify_ids' => '1',
        'cursor'        => '-1',
    ];
    $params['cursor'] = '-1';
    do {
        $result = $to->get($endpoint, $params);
        $ids += array_flip($result->ids);
    } while ($params['cursor'] = $result->next_cursor_str);
    return $ids;
};

// リムーブ実行用クロージャ
$unfollow = function ($user_id) use ($to) {
    try {
        $user = $to->post('friendships/destroy', compact('user_id'));
        echo "Unfollowed @{$user->screen_name}\n";
    } catch (TwistException $e) {
        echo "ID{$user_id}: {$e->getMessage()}\n";
    }
};

// フォロー実行用クロージャ
$follow = function ($user_id) use ($to) {
    try {
        $user = $to->post('friendships/create', compact('user_id'));
        if ($user->protected) {
            echo "Send follow request to @{$user->screen_name}\n";
        } else {
            echo "Followed @{$user->screen_name}\n";
        }
    } catch (TwistException $e) {
        echo "ID{$user_id}: {$e->getMessage()}\n";
    }
};

/* ユーザリストによる処理開始 */
try {
    
    // フレンドとフォロワーそれぞれを取得
    $friends   = $get_all_ids('friends/ids');
    $followers = $get_all_ids('followers/ids');
    
    // 差分を取得
    $friends_only   = array_diff_key($friends, $followers);
    $followers_only = array_diff_key($followers, $friends);
    
    // 1件ずつそれぞれ試行
    foreach ($friends_only as $user_id => $_) $unfollow($user_id);
    foreach ($followers_only as $user_id => $_) $follow($user_id);

} catch (TwistException $e) {
    
    echo "Fatal Error: {$e->getMessage()}\n";
    
}
   
    

ストリーミング利用時のみ必要な追加のコード

/* ストリーミングによる処理開始 */
try {

    // 自分のユーザIDを取得
    $my_id = $to->get('account/verify_credentials')->id_str;
    
    // ストリーミングに接続
    $to->streaming(
       'user',
        function ($status) use ($unfollow, $follow, $my_id) {
            // 自分に対するフォローイベントとリムーブイベントだけを検知
            if (isset($status->event) && $status->target->id_str === $my_id) {
                if ($status->event === 'unfollow') {
                    $unfollow($status->source->id_str);
                } elseif ($status->event === 'follow') {
                    $follow($status->source->id_str);
                }
            }
        }
    );

} catch (TwistException $e) {
    
    echo "Fatal Error: {$e->getMessage()}\n";
    
}
17
21
2

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
17
21

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?