数珠繋ぎのツイートシステムに予約機能を付けました😂 #php #code

2022.10.07

Logging

おはようございます、偏頭痛持ちは雨が降るが一番大変です☔。

先日、数珠繋ぎのツイートシステムを作ったのですが、そのシステムに予約機能を付けました。尚、TwitterAPIのバージョン2でスケジュールのパラメーターが今のところ無いですね。これから先、機能が付くかも知れないですが今のところ無いようです。因みにソースコードは近日中にQiitaGithubにUPします。此処ではソースコードの一部を掲載します(※記事を更新しました下へスクロール🫠)。

Twitter API v2 ツイート数珠繋ぎ

尚、crontabでPHPファイルを叩くようにしています、あと注意事項ですが予約を一度した投稿については変更等は出来ません、編集機能等の機能追加の予定はないです。また、予約管理はsqlite3を使用して管理しています。

<?php
date_default_timezone_set('Asia/Tokyo');
ini_set("display_errors",0);
require_once "./data/tw-config-v2.php";
require_once "../vendor/autoload.php";

use Abraham\TwitterOAuth\TwitterOAuth;

class tw
{
    var $connection = null;
    var $pdo = null;
    function __construct()
    {
        $this->connection = new TwitterOAuth(APIKEY, APISECRET, ACCESSTOKEN, ACCESSTOKENSECRET);
        $this->connection->setApiVersion("2");
    }
    function db_connection()
    {
        try {
            //code...
            $res = $this->pdo = new PDO("sqlite:./data/tw-tweets-db.sqlite3");
        } catch (\Throwable $th) {
            //throw $th;
            //print $th->getMessage();
            $res = false;
        }
        return $res;
    }

    function timecheck($timeonoff, $times)
    {
        if (!$timeonoff) return true;
        $n = new DateTime();
        $t = new DateTime($times);
        return $t <= $n ? true : false;
    }

    function pickup_tweets(mixed $tw_text = null, int $timeonoff = 0, mixed $times = null, string $id = "")
    {
        if (!$times) return false;
        $obj = (object)[];
        $times = preg_replace("/\-/", "/", $times);
        $times = preg_replace("/T/", " ", $times);

        if ($this->timecheck($timeonoff, $times)) {
            if (isset($tw_text) && is_array($tw_text)) {
                foreach ($tw_text as $key => $value) {
                    if (preg_replace("/[ | ]/", "", $value)) {
                        $obj = !$key ? ($this->connection->post("tweets", ["text" => $value], true)
                        ) : ($this->connection->post("tweets", ["reply" => ["in_reply_to_tweet_id" => $obj->data->id], "text" => $value], true)
                        );
                    }
                }
                return true;
            }
        } else {
            return $timeonoff ? $this->save_sqlite($tw_text, $timeonoff, $times, $id): true;
        }
    }

    function save_sqlite($tw_text = null, int $timeonoff = 0, mixed $times = null, string $id = "")
    {
        if ($this->db_connection()) {
            try {
                //code...
                if (isset($tw_text) && is_array($tw_text)) {
                    foreach ($tw_text as $key => &$value) {
                        if (preg_replace("/[ | ]/", "", $value)) {
                            $stmt = $this->pdo->prepare("insert into tweets (tw_id,user,times,tw_text)values(:tw_id,:user,:times,:tw_text)");
                            $stmt->bindValue(":tw_id", $key, PDO::PARAM_INT);
                            $stmt->bindValue(":user", $id, PDO::PARAM_STR);
                            $stmt->bindValue(":times", $times, PDO::PARAM_STR);
                            $stmt->bindValue(":tw_text", $value, PDO::PARAM_STR);
                            $stmt->execute();
                        }
                    }
                }
                $this->pdo = null;
                return true;
            } catch (\Throwable $th) {
                //throw $th;
                return false;
            }
        }
    }
    function tweets_load(string $id = "")
    {
        if (!$id) return false;
        try {
            //code...
            $value = null;
            if ($this->db_connection()) {
                $stmt = $this->pdo->prepare("select * from tweets where user = :user order by times,tw_id asc;");
                $stmt->bindValue(":user", $id, PDO::PARAM_STR);
                $res = $stmt->execute();
                $value = $res ? $stmt->fetchAll() : false;
                $this->pdo = null;
            }
            return $value;            
        } catch (\Throwable $th) {
            //throw $th;
            return false;
        }
    }
    function tweets_update(int $key = 0, int $timeonoff = 0, mixed $times = null, string $id = "",mixed $tw_text="")
    {
        try {
            //code...
            if(!preg_replace("/[ | ]{0,}/","",$tw_text))return false;
            if ($this->db_connection()) {
                $stmt = $this->pdo->prepare("update tweets set tw_text = :tw_text where tw_id = :tw_id and user = :user and times = :times");
                $stmt->bindValue(":tw_id", $key, PDO::PARAM_INT);
                $stmt->bindValue(":user", $id, PDO::PARAM_STR);
                $stmt->bindValue(":times", $times, PDO::PARAM_STR);
                $stmt->bindValue(":tw_text", $tw_text, PDO::PARAM_STR);
                $stmt->execute();
                $this->pdo = null;
            }
        } catch (\Throwable $th) {
            //throw $th;
            return false;
        }
        return true;

    }

    function tweets_delete(int $key = 0, int $timeonoff = 0, mixed $times = null, string $id = "")
    {
        try {
            //code...
            if ($this->db_connection()) {
                $stmt = $this->pdo->prepare("delete from tweets where tw_id = :tw_id and user = :user and times = :times");
                $stmt->bindValue(":tw_id", $key, PDO::PARAM_INT);
                $stmt->bindValue(":user", $id, PDO::PARAM_STR);
                $stmt->bindValue(":times", $times, PDO::PARAM_STR);
                $stmt->execute();
                $this->pdo = null;
            }
        } catch (\Throwable $th) {
            //throw $th;
            return false;
        }
        return true;
    }

    function bat_tweets(mixed $value = null)
    {
        if (!$value) return false;
        $obj = (object)[];
        $t = "";
        foreach ($value as $key => $val) {
            if ($this->timecheck(1, $val["times"])) {
                $obj = ($val["times"]<>$t)? ($this->connection->post("tweets", ["text" => $val["tw_text"]], true)
                ) : ($this->connection->post("tweets", ["reply" => ["in_reply_to_tweet_id" => $obj->data->id], "text" => $val["tw_text"]], true)
                );
                $this->tweets_delete($val["tw_id"], 1, $val["times"], $val["user"]);
                $t = $val["times"];
            } else {
              //  var_dump($val);
              //  break;
            }
        }
    }
}

if ($argv[0]) {
    $tw = new tw();
    $value = $tw->tweets_load(xss_d($argv[1]));
    $tw->bat_tweets($value);
}
function xss_d($val = false)
{
    if (is_array($val)) {
        foreach ($val as $key => $value) {
            $val[$key]  = strip_tags($value);
            $val[$key]  = htmlspecialchars($val[$key]);
        }
    } else {
        $val  = strip_tags($val);
        $val  = htmlspecialchars($val);
    }
    return $val;
}

追記:予約編集機能なども付けました🙄。

GithubとQittaのリンクはこちらです。
Github:https://github.com/taoka-toshiaki/tweets-system-box1
Qitta:https://qiita.com/taoka-toshiaki/items/5ef12b60b267742bf584

タグ

2, , 39, Asia, Code, crontab, date, default, github, ini, lt, php, qiita, Se, set, Sqlite, timezone, Tokyo, TwitterAPI, UP, コード, これ, システム, スクロール, スケジュール, ソース, ツイート, ところ, バージョン, パラメーター, ファイル, 一部, , 予定, 予約, 事項, , 使用, 偏頭痛, , 先日, 変更等, 大変, 投稿, 掲載, 数珠繋ぎ, 更新, 機能, 機能等, 此処, 注意, 管理, 編集, 記事, 近日, 追加, ,

Twitter-API-v2ツイート数珠繋ぎ #コード公開 #php

2022.10.04

Logging

おはようございます。土日祝も関係なくブログは毎日書いています🤮。

さて、今日はPHP言語でTwitterAPIバージョン2(v2)を使用してツイート数珠繋ぎをする方法を抜粋して記載していきます。こういうコードは今のところ出回っていないようです。少し調べれば公式サイトに記載しているのだけども・・・。まだ、日本語に対応した記事が少ないようです。v2でツイートする方法やリツイートする方法は何故かあるのだけどリプライ(Reply)[/statuses/update]する方法が記事としては記載していなかったので?記載します。

<?php
require_once "vendor/autoload.php";
use Abraham\TwitterOAuth\TwitterOAuth;

class tw{
    var $connection = null;
    function __construct()
    {
        $this->connection = new TwitterOAuth(APIKEY, APISECRET,ACCESSTOKEN, ACCESSTOKENSECRET);
        $this->connection->setApiVersion("2");
    }

    function pickup_tweets(mixed $tw_text=null){
         $obj = (object)[];
        if(isset($tw_text) && is_array($tw_text)){
            foreach ($tw_text as $key => $value) {
                if(preg_replace("/[ | ]/","",$value)){
                    $obj = !$key?(
                        $this->connection->post("tweets", ["text" =>$value], true)
                    ):
                    (
                        $this->connection->post("tweets", ["reply"=>["in_reply_to_tweet_id"=>$obj->data->id],"text"=> $value], true)
                    );
                }
            }
            return true;
        }
        return false;
    }
}

最初に結論とコードのアルゴリズムに付いて解説します。まず、tweetsのパラメーターでリプライ出来るように変更されています。v1.1とはそこが変わっているので同じ仕組みを検索しがちですがそれでは検索にヒットしないようです🤔。まずはエンドポイントの変更点の確認が必要みたい👏。

エンドポイントのv1.1からv2への対応表

エンドポイントのv1.1からv2への対応表が公式から出ているので確認してみてください↑。

次にコードの解説ですがまずTwitterOAuthライブラリをインストールを行い、defineなどの設定なども考慮した上で実行してみてください(コードに追記記載が必要)。変数、$tw_textは配列です。また投稿する文字が入っていると考えてください。そしてこのコードを下記のような考え方で実行してみてください。

<?php
       require_once "tw-index.php";
       $tw_text[0] ="test1";
       $tw_text[1] ="test2";
       $tw = new tw();
       if($tw->pickup_tweets($tw_text)){
        $ret["msg"] = "ok";
       }else{
        $ret["msg"] = "NG";
       }
       var_dump($ret);

※前提条件としてtwitter社にAPIの申請を行って受理されている事。

Twitter API v2 ツイート数珠繋ぎ

これで思った通り実行出来たと思います。尚、自分のように管理画面などを作って数珠繋ぎの投稿するのも良いかも知れません🫠。

タグ

2, Abraham, autoload, class, connection, function, lt, null, once, php, quot, Reply, require, statuses, tw, Twitter-API-v, TwitterAPI, TwitterOAuth, UPDATE, use, var, vendor, コード, サイト, ツイート, ところ, バージョン, ブログ, リツイート, リプライ, , 今日, 使用, 公式, 公開, 土日, 対応, 少し, 抜粋, 数珠繋ぎ, 方法, 日本語, 毎日, , 言語, 記事, 記載,

JavaScriptのPromise例えが分からない人のために。

2020.06.06

Logging

自分は『Promiseってなんやねん、わからんわ。』という人でした。皆さん賢いので複雑怪奇なコードで教えてくれていて…わかんない。
Promiseって非同期処理にするための道具です。Promiseって書いてその中に非同期処理の内容を書いてあげる。値を戻したい場合は命名した名前のカッコの中に値を返してあげれば良いが!!、どうも渡せる値は一つだけなのだ。

ちなみにthen(その後)で、非同期処理が終わった後にする処理が書けるですね(´・ω・`)。thenの中に非同期処理の値も返ってくる‥但しひとまとめで、、そんだけの話。またエラーになった時の処理も対応できるってさ…、そしてチェーン(数珠繋ぎ)の様に書くことも可能です、ここではそれらは割愛しますね?。

ちなみに最初、asyncとawaitと混合していて悩んでおりました。asyncとawaitは対になっていると同じような感覚でPromiseとthenは対になっていると考えてください。あまり複雑怪奇に考えずサンプルコードを動かして出来るできないを判断した後に賢い人が書いたリファレンスなどを読むことをオススメします。

最後に単純なソースコードとコンソールの結果を載せときますね。

"use strict";
var a = 0;
const q1 = new Promise((zaru)=>{//zaru...名前付けは何でも良い(予約されているものでなければ
	a++;
	zaru(a + "1..");//データをまとめて返す
});
const q2 = new Promise((zaru)=>{
	a++;
	zaru(a + "2..");
});
const q3 = new Promise((zaru)=>{
	zaru("3~~~~n");
});
const qdaaaaaaaa = new Promise((zaru)=>{
	zaru([1,2,3,"Dahahaha!!"]);
});
Promise.all([q1,q2,q3,qdaaaaaaaa]).then((val)=>{
	console.log(val);
 }
);
qdaaaaaaaa.then((val)=>{
	console.log(val);
});
Array(4) [1, 2, 3, "Dahahaha!!"]
move.js:26
length:4
__proto__:Array(0) [, …]
0:1
1:2
2:3
3:"Dahahaha!!"
Array(4) ["11..", "22..", "3~~~~n", Array(4)]
move.js:21
length:4
__proto__:Array(0) [, …]
0:"11.."
1:"22.."
2:"3~~~~n"
3:Array(4) [1, 2, 3, …]
length:4
__proto__:Array(0) [, …]
0:1
1:2
2:3
3:"Dahahaha!!"

タグ

async, await, javascript, Promise, then, エラー, かっこ, コード, ここ, こと, それら, そん, ため, チェーン, なん, ひとまとめ, 一つ, , , 但し, , 内容, 処理, 割愛, 可能, 同期, 名前, 命名, 場合, , 対応, , 感覚, 数珠繋ぎ, , 最初, 混合, 皆さん, 自分, , 道具,

アロー演算子の数珠繋ぎの作り方?

2020.03.17

Logging

コロナウィルス対策の一環として東京都が“GitHub”に開設した新型コロナウイルス対策サイトがすごいと話題になっているらしいので自分も見てみました。ソースコードはVue.js,TypeScript,React.js,PHPなどなどいろいろな言語が使用されていました。PHPはLaravelの機能が使われてたりして、書き方が綺麗で勉強になるなぁと思ったわけです。参考になりますよね、きれいな書き方のコードを見るとやはり参考になります。

もともと、書き方が古いと自分は古い書き方に合わせます。特に上がプライドが高い人だと出る杭は打たれるみたいな状態になりますので要注意ですね…。そういう人が上にいると徐々にコードを書くのが面白くなくなります。そういうのは大いにあるなと思います。名も知らないひとのコード書きが自分の上司だったらなと思うときがあります。

そう愚痴ってもしょうが無い、その環境を選んだのは自分自身な訳ですからね。
ただ技術力を伸ばしたければやはり環境は大事、辞めたいなら辞めて自分の力を表現できる環境に身をおいた方が断然良い。

前置き長くなりました、、アロー演算子を数珠繋ぎする考え方はこんな感じです。考え方を知っとくと応用が出来るようになります、やはり基準を知るが大事かなといつも思います。

追記:これを応用するとこんな感じになります。追記のソースコードを記載しました(2021.07.05)

<?php
class testA{
    public $a = "";
    public function __construct($a)
    {
        $this->a = $a;
    }
    public function test1($a=""):string{
        return (string)$this->a." ".$a."<br>\n";
    }
    public function test2($a=""):string{
        return (string)$this->a." ".$a."<br>\n";
    }
}
class test{
    public function main($a="Hello"):object
    {
        $this->a = $a;
        return new testA($this->a);
    }
}
$test = new test();
print $test->main()->test1("PHP");
print $test->main("by")->test2("C");
<?php
    class test{
        function main(){
            return new class{
                function testA(){
                    return "testA";
                }
                function testB(){
                    return "testB";
                }
            };
        }
    }
    $test = new test();
    print $test->main()->testA();
    print $test->main()->testB();

タグ

github, JS, Laravel, php, react, TypeScript, vue, アロー, いろいろ, ウィルス, きれい, コード, コロナ, コロナウイルス, サイト, しょう, ソース, とき, ひと, プライド, もともと, わけ, 一環, , 上司, , 作り方, 使用, 勉強, 参考, , 対策, 技術力, 数珠繋ぎ, 新型, 書き方, , 東京都, 機能, 注意, 演算子, 状態, , 環境, 綺麗, 自分, 自身, 言語, , 話題, 開設,