Skip to content

Instantly share code, notes, and snippets.

@mpyw
Last active January 31, 2018 13:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mpyw/8bbee4927b743f3ad691d78e151ad578 to your computer and use it in GitHub Desktop.
Save mpyw/8bbee4927b743f3ad691d78e151ad578 to your computer and use it in GitHub Desktop.
ツイート数を常に1000件に保つやつ(デバッグしてない)
<?php
require __DIR__ . '/vendor/autoload.php';
use mpyw\Co\Co;
use mpyw\Cowitter\Client;
const CONSUMER_KEY = '...';
const CONSUMER_SECRET = '...';
const ACESS_TOKEN = '...';
const ACCESS_TOKEN_SECRET = '...';
const USER_ID = 000000;
const CAPACITY = 1000;
Co::wait(function () {
// クライアント生成
$client = new Client([CONSUMER_KEY, CONSUMER_SECRET, ACCESS_TOKEN, ACCESS_TOKEN_SECRET]);
$all = [];
$max_id = null;
do {
// 取れる分だけ取る
$params = [
'user_id' => USER_ID,
'count' => 200,
'include_rts' => true,
'max_id' => $max_id,
];
echo "[FETCH START] GET statuses/user_timeline?" . http_build_query($params, '', '&') . "\n";
$statuses = yield $client->getAsync('statuses/user_timeline', $params);
echo "[FETCH DONE] GET statuses/user_timeline?" . http_build_query($params, '', '&') . "\n";
echo "New " . count($statuses) . " statuses are found.\n";
if ($statuses) {
// 古いものを末尾に追加
array_push($all, ...$statuses);
// 1000件を超えた分だけ削除リクエスト飛ばす
Co::async(
array_map(
function ($status) use ($client) {
echo "[DELETE START] POST statuses/destroy/$status->id_str\n";
yield $client->postAsync("statuses/destroy/$status->id_str");
echo "[DELETE DONE] POST statuses/destroy/$status->id_str\n";
},
array_splice($all, CAPACITY)
),
false
);
// $max_id を末尾の id から 1 引いた値にする
$max_id = end($statuses)['id'] - 1;
}
// 結果が取れた間だけ $max_id を更新しながら続ける
} while ($statuses);
// ストリーミングに接続
echo "[STREAMING START] POST statuses/filter\n";
yield $client->streamingAsync('statuses/filter', function ($status) use ($client, $all) {
// ツイート以外は無視
if (!isset($status->text)) return;
// 新しい1件を前に追加
array_unshift($all, $status);
// 1000件を超えたぶんだけ削除リクエスト飛ばす
Co::async(
array_map(
function ($status) use ($client) {
echo "[DELETE START] POST statuses/destroy/$status->id_str\n";
yield $client->postAsync("statuses/destroy/$status->id_str");
echo "[DELETE DONE] POST statuses/destroy/$status->id_str\n";
},
array_splice($all, CAPACITY)
),
false
);
}, ['follow' => USER_ID]);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment