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

ページ無限スクロールの作り方 #インフィニティ#InfinityPageScroll #JavaScript

2022.09.22

Logging

おはようございます、台風14号が過ぎ去ってからいきなり秋模様ですね🫠。

さて、先日ツイートしたページ無限ループが出来るJavaScriptコードを書きました。これを作ろうと思ったキッカケは、自分が運営しているWordPressサイトに巷のページ無限スクロールプラグインが尽く(ことごとく)使用出来なかったので自分で自作した訳です。因みにページ無限スクロールプラグインとはページを送りをしなくてもページの最下までスクロールすると次頁を読み込んでくれるプラグインの事を指します。

下記のコードは自サイト専用なのでそのまま使用することは出来ませんが、重要な部分だけ抜き取って再利用すれば、独自のページ無限ループに対応することは可能かと思います。

コードを読んで頂ければ分かることですが、重要なポイントはページを読み込む方法とそれをDomに変換する方法だと思います。まず、ページを読み込む方法は下記のファンクションで可能です。

fetch(next_url).then(
                response => response.text()
            ).then(data => {

そしてDomに置き換えている所はこの部分になります。これら2つの箇所が重要になります。

                const parser = new DOMParser();
                const doc = parser.parseFromString(data, 'text/html');

これらの事に注意して独自コードを書いてみてください。最後に全コードを記載しときます。


let cnt = 2;
let blk = 0;
async function nextpage() {
    if (cnt !== blk) {
        blk = cnt;
        await (async () => {
            let next_url = "https://fox-black.com/blog/page/" + cnt;
            return await fetch(next_url).then(
                response => response.text()
            ).then(data => {
                const parser = new DOMParser();
                const doc = parser.parseFromString(data, 'text/html');
                let blogs = doc.querySelectorAll('.blogpage');
                cnt++;
                if (blogs[0].innerHTML !== undefined) {
                    document.querySelector(".foxpage").insertAdjacentHTML("beforeend", (function (elm) {
                        let str = "";
                        for (const key in elm) {
                            const element = elm[key];
                            if (element.innerHTML !== undefined) {
                                str += "<div class=\"blogpage\">" + element.innerHTML + "</div>";
                            }
                        }
                        return str;
                    })(blogs));
                } else {
                    if (document.querySelector("#fin") === null) {
                        document.querySelector(".foxpage").insertAdjacentHTML("beforeend", "<div id=\"fin\"></div>");
                    }
                }
            }).catch(error => {
                if (document.querySelector("#fin") === null) {
                    document.querySelector(".foxpage").insertAdjacentHTML("beforeend", "<div id=\"fin\"></div>");
                }
            });
        })();
    }
}

if (navigator.userAgent.match(/iPhone|Android.+Mobile/)) {
    window.addEventListener("scroll", async function () {
        let s = (() => {
            let tgt;
            if ('scrollingElement' in document) {
                tgt = document.scrollingElement;
            } else if (this.browser.isWebKit) {
                tgt = document.body;
            } else {
                tgt = document.documentElement;
            }
            return tgt;
        })();
        if (document.querySelector("#fin") === null && s.scrollTop >= (s.clientHeight - 650)) {
            await nextpage();
        }
    });
} else {
    document.querySelector(".foxpage").addEventListener("scroll", async function () {
        if (document.querySelector("#fin") === null && document.querySelector(".foxpage").scrollTop >= (document.querySelector(".foxpage").scrollHeight - 300)) {
            await nextpage();
        }
    });
}


タグ

14, dom, InfinityPageScroll, javascript, WordPress, インフィニティ, キッカケ, コード, こと, これ, サイト, スクロール, それ, ツイート, プラグイン, ページ, ポイント, ループ, 下記, , 作り方, 使用, 先日, 利用, 可能, 台風, 変換, 対応, 専用, , 方法, 最下, 模様, 次頁, 無限, , , 自作, 自分, , 運営, 部分, 重要,

Twitterの画像を抽出、非API

2018.11.07

Logging

Twitterの画像を抽出、非API
Goutteライブラリを使用してTwitterのメディアを抽出するだけで
APIを使用せずに17枚の画像が抽出することが可能。
これを改良してスクロールさせながらってのは出来ないのではないかな
特にVPSじゃないレンタルサーバーなどでは不可能じゃないのかと思います。

require_once './vendor/autoload.php';
use Goutte\Client;
$client = new Client();
$crawler = $client->request('GET','https://twitter.com/xxxx/media');
$img = $crawler->filter(".AdaptiveMedia-photoContainer.js-adaptive-photo img")->each(function ($node){
return $node->attr('src');
});

タグ

'src', 17, AdaptiveMedia-photoContainer, API, APITwitter, attr, autoload, Client, com, crawler, each, filter, function, GET, Goutte, gt, img, js-adaptive-photo, media', new, node, once, php, request, require, return, Twitter, use, vendor, VPS, xxxx, こと, これ, サーバー, スクロール, ない, メディア, ライブラリ, レンタル, 不可能, 使用, 出来, 可能, 思い, 抽出, 改良, , 特に, 画像, ,