PHP
Twitter

長文を140字に自動分割してツイートする

探しても任意のツイートへのリプライ指定ができるツールがなく、
自分用にローカルで動かすために書いたので、色々と適当です。

参考:Twitter APIでつぶやきを取得する
https://qiita.com/yokoh9/items/760e432ebd39040d5a0f

Twitter Apps
https://apps.twitter.com/

twitteroauth
https://github.com/abraham/twitteroauth/releases

index.php
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="robots" content="noindex,nofollow">
    <meta id="_robots" content="noindex,nofollow">
    <title>連続ツイート</title>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
</head>
<body>
<?php
ini_set( 'display_errors', 1 );

// タイムゾーン
date_default_timezone_set('Asia/Tokyo');

require "twitteroauth/autoload.php";
use Abraham\TwitterOAuth\TwitterOAuth;

// APIキー
require "./key.php";
$consumerKey = YOUR_CONSUMER_KEY;
$consumerSecret = YOUR_CONSUMER_SECRET;
$accessToken = YOUR_ACCESSTOKEN;
$accessTokenSecret = YOUR_ACCESSTOKEN_SECRET;

mb_internal_encoding("UTF-8");

if (empty($_REQUEST['text'])) : #=====================================================
?>
<script>
$(document).ready(function(){
    $("#twid").val(window.localStorage.getItem('twId'));
    $("#twtext").val(window.localStorage.getItem('twText'));
    $("#twid").focus();
});
jQuery(function($){
    function changeText () {
        window.localStorage.setItem('twId', $("#twid").val());
        window.localStorage.setItem('twText', $("#twtext").val());
    }
    $("#twid").bind("change keyup click", (changeText));
    $("#twtext").bind("change keyup click", (changeText));
});
</script>
<pre><form action="index.php" method="post">ツイート内容 <input type="submit" value=" 分割 ">

<input type="text" id="twid" name="twid" style="width:400px;max-width:80%;padding:10px;" placeholder="リプライ先のツイート" autocomplete="off"><input type="reset" value="消去" style="margin-left:10px;padding:7px;">

<textarea id="twtext" name="text" style="border:1px solid #999;width:500px;max-width:90%;height:500px;max-height:80%;padding:10px;"></textarea>
</form></pre>
<?php
elseif (empty($_REQUEST['textlist'])) : #=====================================================
?>

<script>
jQuery(function($){
    if (window.localStorage.getItem('twText') == '') {
        location.href = 'index.php';
    }
});
</script>

<pre>
<?php

    if (!empty($_REQUEST['twid'])) {
        $twid = substr($_REQUEST['twid'], strrpos($_REQUEST['twid'], '/')+1);
    } else {
        $twid = '';
    }
    echo '<form action="index.php" method="post">ツイート分割内容 <input type="submit" value="ツイート"><input type="hidden" name="text" value="ok">
<input type="text" name="twid" value="'.$twid.'" readonly style="width:400px;">';

    // リプライするツイートの内容を表示
    if (!empty($twid)) {
    $connection = new TwitterOAuth($consumerKey, $consumerSecret, $accessToken, $accessTokenSecret);
        $statuses = $connection->get("statuses/show/$twid");
        echo '
<textarea style="width:400px;max-width:90%;height:100px;" disabled>'.$statuses->text.'</textarea>';
    }

    $textlist = array();
    $tweetcount = 0;
    $textlist[$tweetcount] = '';
    $count = 0;
    $start = 0;

    $text = trim($_REQUEST['text']);
    $text = preg_replace("/\r\n|\r|\n/", "\n", $text);
    // パターン
    $pattern = '/|(\w*)《(\w*)》/u';
    $noruby = '\1';
    $text = preg_replace($pattern,$noruby,$text);

    $text = str_replace(" ", "", $text);
    $lastchar = '';
    for ($i = 0; $i < mb_strlen($text); $i++) {
        $char = mb_substr($text, $i, 1);

        // 0字の時きたら飛ばす文字
        if (($count == 0) and ($char == '、')) continue;
        if (($count == 0) and ($char == '。')) continue;
        if (($count == 0) and ($char == '」')) continue;

        if (($char == '…') and ($lastchar == '…')) {
            $lastchar = '';
            continue;
        }

        // 空行二回で次のツイート
        if (($char == "\n") and ($lastchar == "\n")) {
            $nextchar = mb_substr($text, $i+1, 1);
            if ($nextchar == "\n") {
                $i++;
                $tweetcount++;
                $textlist[$tweetcount] = '';
                $count = 0;
                $lastchar = '';
                continue;
            }
        }

        // 130字以上の時に来たら分割する文字
        if ($count > 130) {
            if (($char == "\n")) {
                $tweetcount++;
                $textlist[$tweetcount] = '';
                $count = 0;
                $lastchar = '';
                continue;
            }
            if (($char == "「")) {
                $tweetcount++;
                $textlist[$tweetcount] = '「';
                $count = 1;
                $lastchar = '';
                continue;
            }
            if (($char == "―")) {
                $tweetcount++;
                $textlist[$tweetcount] = '―';
                $count = 1;
                $lastchar = '';
                continue;
            }
        }

        $textlist[$tweetcount] .= $char;

        // 130字以上の時に来たら分割する文字
        if ($count > 130) {
            if (($char == "」")) $count = 140;
            if (($char == "、")) $count = 140;
            if (($char == "。")) $count = 140;
        }
        $count++;
        if ($count > 139) {
            $tweetcount++;
            $textlist[$tweetcount] = '';
            $count = 0;
            $lastchar = '';
        } else {
            $lastchar = $char;
        }
    }
    foreach ($textlist as $value) {
        echo "\n".'<textarea class="splittext" name="textlist[]" style="width:400px;max-width:90%;height:100px;margin-top:10px;">'.trim($value).'</textarea>'.mb_strlen($value);
    }
?>

<?php
    echo '</form></pre>';
else : #=====================================================
?>

<script>
if (window.localStorage.getItem('twText') == '') {
    location.href = 'index.php';
}
</script>
<a href="./">新規ツイート</a>

<pre>
<?php
    sleep(1);

    $twitter = new TwitterOAuth($consumerKey, $consumerSecret, $accessToken, $accessTokenSecret);

    $id = $_REQUEST['twid'];
    // ツイート作成
    foreach ($_REQUEST['textlist'] as $value) {
        $tweettime = date("Y/m/d H:i:s");
        $text = $value;
        $result = $twitter->post(
                "statuses/update",
                array("status" => $text, "in_reply_to_status_id" => $id)
        );

        if($twitter->getLastHttpCode() == 200) {
            // ツイート成功
            echo "<b>成功 </b>$tweettime\n$text\n\n";
            $body = $twitter->getLastBody();
            $id = $body->id_str;
        } else {
            // ツイート失敗
            echo "<b style=\"color:red\">失敗 </b>$tweettime\n$text\n\n";
        }

        // 出力バッファの内容を送信する
        @ob_flush();
        @flush();

        sleep(1);
    }
?>
</pre>
<script>
$(document).ready(function(){
    window.localStorage.setItem('twId', '/<?php echo $id ?>');
    window.localStorage.setItem('twText', '');
});
</script>

<?php
endif;
?>
<hr>
</body>
</html>
key.php
<?php

define("YOUR_CONSUMER_KEY", "");
define("YOUR_CONSUMER_SECRET", "");
define("YOUR_ACCESSTOKEN", "");
define("YOUR_ACCESSTOKEN_SECRET", "");

?>