Skip to content

Instantly share code, notes, and snippets.

@PJZ9n
Created June 10, 2020 22:46
Show Gist options
  • Save PJZ9n/2e7fad27d1374ba54af2e2d9d19dc8bc to your computer and use it in GitHub Desktop.
Save PJZ9n/2e7fad27d1374ba54af2e2d9d19dc8bc to your computer and use it in GitHub Desktop.
ツイ廃botのソースコード、とりあえず動くレベルの最悪な実装です。少しでも弄ると壊れます。
<?php
/**
* Copyright (c) 2020 PJZ9n.
*
* This file is part of Tuihai.
*
* Tuihai is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Tuihai is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Tuihai. If not, see <http://www.gnu.org/licenses/>.
*/
declare(strict_types=1);
require_once __DIR__ . "/private/composer/vendor/autoload.php";
use Abraham\TwitterOAuth\TwitterOAuth;
use PJZ9n\Tuihai\DB;
use PJZ9n\Tuihai\Environment\Environment;
use PJZ9n\Tuihai\Log\AppLog;
function response(int $code, string $message): void
{
http_response_code($code);
echo json_encode([
"code" => $code,
"message" => $message,
], JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
exit();
}
//response(503, "Service Unavailable");
//ロガー
$logger = AppLog::getLogger("CheckMention");
//セキュリティチェック
if ($_SERVER["REMOTE_ADDR"] !== "0.0.0.0") {
$logger->warning("ip check failed", [
"ip" => $_SERVER["REMOTE_ADDR"],
]);
response(401, "接続元IP不正");
}
//DB
$db = new DB();
$db->initAlreadyReply();
//bot取得
$bot = new TwitterOAuth(
Environment::TWITTER_API_CONSUMER_KEY,
Environment::TWITTER_API_SECRET_KEY,
Environment::TWITTER_API_BOT_TOKEN,
Environment::TWITTER_API_BOT_TOKEN_SECRET
);
//メンション取得
$mentionsTimeline = $bot->get("statuses/mentions_timeline", ["count" => 200]);
//反転
$mentionsTimeline = array_reverse($mentionsTimeline);
$processedCount = 0;
//自分宛てのメンション回し
foreach ($mentionsTimeline as $mentionTweet) {
$mentionUserScreenName = $mentionTweet->user->screen_name;
$mentionUserId = $mentionTweet->user->id;
/*if ($mentionUserId !== Environment::TWITTER_API_USER_ID) {
$logger->debug("not the user id", [
"id" => $mentionUserId,
]);
continue;
}*/
$mentionTweetId = $mentionTweet->id;
if ($db->isAlreadyReply($mentionTweetId)) {
$logger->debug("already reply", [
"id" => $mentionTweetId,
]);
continue;
}
if (strpos($mentionTweet->text, "時間") !== false) {
function milisec(int $id)
{
$timestamp = strval((($id >> 22) + 1288834974657) / 1000.000);
$timestamp_format = DateTime::createFromFormat("U.u", $timestamp);
$timestamp_format->setTimeZone(new DateTimeZone("Asia/Tokyo"));
return $timestamp_format;
}
//いいね
$bot->post("favorites/create", [
"id" => $mentionTweetId,
]);
if ($bot->getLastHttpCode() !== 200) {
$logger->error("failed favorite", [
"id" => $mentionTweetId,
"status" => $bot->getLastHttpCode(),
]);
continue;
}
$mentionParentTweetId = $mentionTweet->in_reply_to_status_id;
//応答ID生成
$responseId = uniqid();
//時間取得
$time = milisec($mentionParentTweetId)->format("Y-m-d H:i:s.u");
//ツイート生成
$text = "";
$text .= "@{$mentionUserScreenName}";
$text .= "-ツイート時間-\n";
$text .= $time . "\n";
$text .= "ツイートID: {$mentionParentTweetId}\n";
$text .= "(応答ID: " . $responseId . ")";
//ツイート
$bot->post("statuses/update", [
"status" => $text,
"in_reply_to_status_id" => $mentionTweetId,
]);
//var_dump($bot->getLastHttpCode());
$logger->info("SUCCESS TIME REPLY!", [
"tweet_id" => $mentionTweetId,
"to_id" => $mentionUserId,
"to_screen_name" => $mentionUserScreenName,
"response_id" => $responseId,
]);
$processedCount++;
$db->markAlreadyReply($mentionTweetId);
break;
}
if (/*$mentionTweet->text === "@pjz9n_another 1" && */
strpos($mentionTweet->text, "取得") === false) {
$logger->debug("no match text", [
"id" => $mentionTweetId,
]);
continue;
}
//他ユーザー指定モードを設定
$otherUserMode = false;
foreach ($mentionTweet->entities->user_mentions as $entitiesUserMention) {
if ($entitiesUserMention->screen_name === Environment::TWITTER_API_BOT_SCREEN_NAME) {
continue;
}
//他ユーザー指定モード
$otherUserMode = true;
$logger->debug("other user mode", [
"screen_name" => $entitiesUserMention->screen_name,
]);
break;
}
//スタート
$logger->info("check ok", [
"id" => $mentionTweetId,
]);
//いいね
$bot->post("favorites/create", [
"id" => $mentionTweetId,
]);
if ($bot->getLastHttpCode() !== 200) {
$logger->error("failed favorite", [
"id" => $mentionTweetId,
"status" => $bot->getLastHttpCode(),
]);
continue;
}
//データ処理
//ユーザー取得
/*$user = new TwitterOAuth(
Environment::TWITTER_API_CONSUMER_KEY,
Environment::TWITTER_API_SECRET_KEY,
Environment::TWITTER_API_USER_TOKEN,
Environment::TWITTER_API_USER_TOKEN_SECRET
);*/
$user = $bot;
//ツイート取得
$todayTweets = [];
try {
$todayDate = new DateTime(date("Y/m/d 00:00:00"), new DateTimeZone("Asia/Tokyo"));
} catch (Exception $exception) {
$logger->error("DateTime", [
"message" => $exception->getMessage(),
]);
}
$maxTweetId = null;
for ($i = 0; $i < 5; $i++) {
$param = [
"count" => 200,
];
$param["user_id"] = $otherUserMode ? $entitiesUserMention->id : $mentionUserId;
if ($maxTweetId !== null) $param["max_id"] = $maxTweetId;
$userTimelineTweets = $user->get("statuses/user_timeline", $param);
foreach ($userTimelineTweets as $userTimelineTweet) {
if ($maxTweetId !== null && $userTimelineTweet->id === $maxTweetId) continue;
try {
$createdAt = (new DateTime($userTimelineTweet->created_at))->setTimezone(new DateTimeZone("Asia/Tokyo"));
} catch (Exception $exception) {
$logger->error("DateTime", [
"message" => $exception->getMessage(),
]);
}
if ($createdAt < $todayDate) break 2;//終了
$todayTweets[] = $userTimelineTweet;
}
$lastUserTimelineTweet = end($userTimelineTweets);
$maxTweetId = $lastUserTimelineTweet->id;
}
//いいね取得
$todayFavorites = [];
$maxTweetId = null;
for ($i = 0; $i < 5; $i++) {
$param = [
"count" => 200,
];
$param["user_id"] = $otherUserMode ? $entitiesUserMention->id : $mentionUserId;
if ($maxTweetId !== null) $param["max_id"] = $maxTweetId;
$userFavoriteTweets = $user->get("favorites/list", $param);
foreach ($userFavoriteTweets as $userFavoriteTweet) {
if ($maxTweetId !== null && $userFavoriteTweet->id === $maxTweetId) continue;
try {
$createdAt = (new DateTime($userFavoriteTweet->created_at))->setTimezone(new DateTimeZone("Asia/Tokyo"));
} catch (Exception $exception) {
$logger->error("DateTime", [
"message" => $exception->getMessage(),
]);
}
if ($createdAt < $todayDate) break 2;//終了
$todayFavorites[] = $userFavoriteTweet;
}
$lastUserFavoriteTweet = end($userFavoriteTweets);
$maxTweetId = $lastUserFavoriteTweet->id;
}
$tweetCount = 0;
$retweetCount = 0;
$mentionCount = 0;
$mentionUserCount = 0;
$favoriteCount = 0;
foreach ($todayTweets as $todayTweet) {
$tweetCount++;//ツイート
if (isset($todayTweet->retweeted_status)) $retweetCount++;//リツイート
$mentionUserCountForThisTweet = count($todayTweet->entities->user_mentions);
if ($mentionUserCountForThisTweet >= 1) $mentionCount++;//メンション
$mentionUserCount += $mentionUserCountForThisTweet;//メンション人数
}
foreach ($todayFavorites as $todayFavorite) {
$favoriteCount++;
}
//TODO 変数名
$entitiesUserName = $otherUserMode ? $entitiesUserMention->name : $mentionTweet->user->name;
$entitiesUserScreenName = $otherUserMode ? $entitiesUserMention->screen_name : $mentionUserScreenName;
//応答ID生成
$responseId = uniqid();
//返信
$text = "";
$text .= "@" . $mentionTweet->user->screen_name . "\n";
$text .= "-{$todayDate->format("Y/m/d")}のツイ廃ステータス-";
$text .= "{$entitiesUserName}(@.{$entitiesUserScreenName})さん\n";
$text .= "ツイート数(RT含む): " . $tweetCount . "回\n";
$text .= "リツイート数: " . $retweetCount . "回\n";
$text .= "@付きツイート数: " . $mentionCount . "回\n";
$text .= "@メンション数: " . $mentionUserCount . "個\n";
$text .= "いいね数: " . $favoriteCount . "回\n";
$text .= "※" . date("Y/m/d H:i:s") . "時点\n";
$text .= "(応答ID: " . $responseId . ")";
$bot->post("statuses/update", [
"status" => $text,
"in_reply_to_status_id" => $mentionTweetId,
]);
//TODO postの結果確認
$logger->info("SUCCESS REPLY!", [
"tweet_id" => $mentionTweetId,
"to_id" => $mentionUserId,
"to_screen_name" => $mentionUserScreenName,
"response_id" => $responseId,
]);
$processedCount++;
$db->markAlreadyReply($mentionTweetId);
break;
}
//var_dump($todayTweets ?? null);
response(200, "success {$processedCount} count");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment