数珠繋ぎのツイートシステムに予約機能を付けました😂 #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, コード, これ, システム, スクロール, スケジュール, ソース, ツイート, ところ, バージョン, パラメーター, ファイル, 一部, , 予定, 予約, 事項, , 使用, 偏頭痛, , 先日, 変更等, 大変, 投稿, 掲載, 数珠繋ぎ, 更新, 機能, 機能等, 此処, 注意, 管理, 編集, 記事, 近日, 追加, ,

E_ERROR | E_WARNING | E_PARSE🐸

2022.06.15

Logging

おはようございます。果報は寝て待て😌。果報(かほう)を家宝だと思い込んでいました・・思い込みって怖いですね。

先日、記載した「更新に失敗しました。 返答が正しい JSON レスポンスではありません。」ですがphp.iniのワーニング(警告表示)が問題でした。そこをE_ERROR | E_WARNING | E_PARSEに修正してあげることで難無く解決済みです。JSONの返却の際に警告表示も返却され正しい値が取得出来ていなかったことに問題があったようです。

因みにこの頃は警告表示も意識してコードを書く機会が多くなりました。その理由はそちらの方がスマートかなって思うからです。数式が美しいと思うように綺麗なコードというものはあります。まだまだ、プログラムのコードは美しく書けませんが意識することによりそれに近づける事は大事になると思っています。

尚、php.iniは大体、/etc/php.iniにあります?、無ければコマンドラインからかコードに下記のように記載してphp.iniは何処に保存しているか調べてみてください。

php -r "echo phpinfo();" | grep "php.ini"
<?php
echo phpinfo();

タグ

Error, etc, ini, json, parse, php, WARNING, かほう, コード, こと, スマート, そこ, そちら, それ, プログラム, もの, レスポンス, ワーニング, , 修正, , 先日, 取得, 問題, 大事, 大体, 失敗, 家宝, 意識, 数式, , 更新, 果報, 機会, 理由, 綺麗, 表示, 解決済み, 記載, 警告, 返却, 返答, , ,

phpのPDOでバインドする時、こうすれば楽。

2020.02.28

Logging

phpのPDOでバインドする時、こうすれば楽ですよね(・(ェ)・)という記述です。前の職場ではsqliでDB接続していたのですが、バインドして作られていたかは忘れてしまいました。ちなみに前の職場のPDOに改修するのは面倒くさいだろうなと感じます。何がめんどくさいかと言えば、今まで導入していたもの全てに対応するというのは、超面倒くさいと思います。

余談:
前の職場を何故辞めたかのお話します。突発的に辞めたと思う人もいるかもしれませんが、基本的に突発的辞めることはないです。突発的に辞めたかのように見えて前々から考えてきっかけを理由に辞めました。具体的な理由に関してはここでは書きません。突発的に辞めたかのように見せかけて計画的です(・(ェ)・)


ソースコードは下記になります。

<?php
ini_set("display_errors",1);
class mysql {
    static $dbh = Null;
    static $host = "localhost";
    static $id = "あいーでぃー";
    static $pass= "パスワード";
    static $dbname = "test";
    static $sql = array(
        "id"=>array("data"=>PDO::PARAM_INT,"val"=>""),
        "name"=>array("data"=>PDO::PARAM_STR,"val"=>"")
    );
    static function connect()
    {
        /* 接続状況をチェックします */
        try {
            static::$dbh = new PDO('mysql:host='.static::$host.';dbname='.static::$dbname.';', static::$id, static::$pass);
            static::$dbh->query('SET NAMES utf8');
          } catch (Exception $e) {
            echo "Failed: " . $e->getMessage();
          }
    }
    static function insert_query(){
        //プリペアドステートメント
        $stmt = static::$dbh->prepare("insert into test1 (id,Name) values(:id,:name);");
        //バインド
        foreach(static::$sql as $key=>&$val){
            $stmt->bindParam(":$key",$val["val"],$val["data"]);
        }
        $stmt->execute();
        $stmt = null;
     }
     static function update_query(){
        //プリペアドステートメント
        $stmt = static::$dbh->prepare("update test1 set Name= :name where id = :id;");
        //バインド
        foreach(static::$sql as $key=>&$val){
            $stmt->bindParam(":$key",$val["val"],$val["data"]);
        }
        $stmt->execute();
        $stmt = null;
     }
     static function select_query(){
        //プリペアドステートメント
        $stmt = static::$dbh->prepare("select * from test1 where id = :id;");
        //バインド
        foreach(static::$sql as $key=>&$val){
            if($key==="id")$stmt->bindParam(":$key",$val["val"],$val["data"]);
        }
        $stmt->execute();
        while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
            printf ("%d (%s)<br>", $row["id"], $row["Name"]);
        }
        $stmt = null;
     }
    static function close(){
        static::$dbh = null;
    }
}
mysql::connect();
// for($i = 0 ;$i<=99;$i++){
//     mysql::$sql["id"]["val"] = $i;
//     mysql::$sql["name"]["val"] = "テスト$i";
//     mysql::insert_query();
// }
for($i = 0 ;$i<=99;$i++){
    mysql::$sql["id"]["val"] = $i;
    mysql::$sql["name"]["val"] = "テスト<font color='red'>$i</font>";
    mysql::update_query();
}
for($i = 0 ;$i<=99;$i++){
    mysql::$sql["id"]["val"] = $i;
    mysql::select_query();
}
mysql::close();

タグ

, class, db, dbh, display, errors, ini, lt, MYSQL, PDO, php, quot, set, sqli, static, お話, きっかけ, コード, ここ, こと, ソース, バインド, もの, 下記, , , 余談, 全て, , 前々, 対応, 導入, 接続, 改修, , 理由, 職場, 記述,

xdebugの動作仕方が分からなかったのでメモ。

2019.06.29

Logging

Xdebugを動作させます。(F5)
次にブラウザを開き動作させたいURLを記入しエンター:D

すると…

debug出来るようになります、設定等は割愛します。
ちなみにphp.iniの方はこんな感じにしてます。

zend_extension ="/xxx/xdebug.so"
xdebug.remote_autostart=1
xdebug.remote_enable=1
xdebug.remote_port=9000
xdebug.remote_connect_back = 1
xdebug.remote_host=IP Address

タグ

, 5, 9000, Address, autostart, back, connect, debug, enable, extension, host, ini, IP, php, port, remote, so, url, xdebug, xxx, zend, エンター, ブラウザ, メモ, 仕方, 割愛, 動作, 感じ, , 記入, 設定,

cronの設定数に制限があるさくらサーバーとかで制限以上に使う方法(´Д`)

2015.01.12

Logging

cronの設定数に制限があるさくらサーバーとかで制限数以上(cron設定を増やす方法
)に使う方法はないかなと考えた結果、自分はこうしました。
一つのPHPファイル(実行ファイル)から複数のファイルをキックすることに!(´Д`)
こうすれば、処理が遅くないファイルなら複数個でも実行できるのではないかと
思ったわけです。結果的に成功しているぽっいです。
※Shellで作れる人は作れるだろうけど自分には無理(´∀`*)ポッいのでPHPで制作しました。
ちなみにさくらレンタルサーバーの場合、php.iniにタイムゾーン設定を
加えてあげてください(date.timezone = Asia/Tokyo ←追加)。
そうしないと動かない恐れがあります。
作っていて思ったことですが、作る考え方はわかるものの、元々メソッドを覚えていない
人間なのでググってメソッド探しにまずヘタりました( ´Д`)=3。その後、完璧なハズとか
思ってソースを実行させるとエラーは出ないものの。思った通りうごかないという事象に
苦しめられること2時間、何でだろうとか思っていて検証してみた結果、メソッドの使い方が
間違っていたり、変数名が間違っていたりとなんとも言えない無情さに襲われましたが
何とか動作するようになったみたいなのでコードをうっぷします。
ソースコードを記載しときます。動作するとは
思いますが誤作動するかもしれないので保証はしません。なお、いつもながら
ソースにはコメントを記載しておりませんのでトレースしてください。
PHPファイルのDLはこちらから( ´Д`)=3?(最終更新日2015/01/12 11:07)
追記2
改良しました。{*改良版はこちら*}
※このPHPファイルを5分置きにキックしていますΣ(゚∀´(┗┐ヽ(・∀・ )ノ。

<?php
//5分刻みに対して有効な無限クローン 処理が負荷の場合どうなるかは知りません。
date_default_timezone_set('Asia/Tokyo');
class cron{

    public function d_m($obj)
    {
            if($obj->m==="*")return true;
            if(preg_match("/,/",$obj->m))return $this->comma($obj->m,date("m"));
            if((int)$obj->m === (int)date("m"))return true;

            return false;
    }

    public function d_d($obj)
    {
            if($obj->d==="*")return true;
            if(preg_match("/,/",$obj->d))return $this->comma($obj->d,date("d"));
            if((int)$obj->d === (int)date("d"))return true;

            return false;
    }

    public function d_H($obj)
    {
            if(preg_match("/\*\/[0-9]{1,2}/",$obj->H)){
                $H = explode("/",$obj->H);
                if((int)$H[1]>0 && ((int)date("H") % (int)$H[1])===0)return true;
            }else{
                if($obj->H==="*")return true;
                if(preg_match("/,/",$obj->H))return $this->comma($obj->H,date("H"));
                if((int)$obj->H === (int)date("H"))return true;

            }
            return false;
    }

    public function d_i($obj)
    {
            if(preg_match("/\*\/[0-9]{1,2}/",$obj->i)){
                $i = explode("/",$obj->i);
                if((int)$i[1]>0 && ((int)date("i") % (int)$i[1])===0)return true;
            }else{
                if($obj->i==="*")return true;
                if(preg_match("/,/",$obj->i))return $this->comma($obj->i,date("i"));
                if((int)$obj->i === (int)date("i"))return true;

            }
            return false;
    }

    //曜日 0=日曜日 6=土曜日
    public function d_w($obj)
    {
            if((int)$obj->w[date("w")]===1)return true;
            return false;
    }

    public  function comma($c="",$t=""){
        if($c==="")return false;
        if($t==="")return false;
        $flg = false;
        foreach(explode(",",$c) as $cc){
            if((int)$cc===(int)$t)$flg = true;
        }
        return $flg;
    }


    public function d_command($obj){
        if($obj->command){
            exec($obj->command . " > /dev/null &");
        }
        return true;
    }

}
if ($argv[1]) {
   $filename = $argv[1];
    if(is_file($filename)){
        $jsn = json_decode(file_get_contents($filename));
        $cron = new cron();
        try {
            foreach($jsn as $obj){
                if($cron->d_m($obj)){
                    if($cron->d_d($obj)){
                        if($cron->d_H($obj)){
                            if($cron->d_i($obj)){
                                if($cron->d_w($obj)){
                                    $cron->d_command($obj);//波動拳{{{{
                                }
                            }
                        }
                    }
                }
            }
        } catch (\Throwable $th) {
            print $th->getMessage();
        }
    }
}

タグ

, Asia, cron, date, ini, php, shell, timezone, Tokyo, いの, キック, こと, サーバー, さくら, ゾーン, タイム, パス, ファイル, ヘタ, ボツ, メソッド, レンタル, わけ, 一つ, , 人間, 処理, 制作, 制限, 場合, 完璧, 実行, , 成功, 方法, 無理, 結果, 考え方, 自分, 複数, 複数個, 設定, 追加,