MastodonAPIに先週の日曜日に鞍替え。#脱TwitterAPI有料化

2023.02.10

Logging

おはようございます、TwitterAPIの有料化始まりましたね😖。

企業ではどういう対応を取るのでしょうか。個人で作っていたサービスはサービス閉鎖する人達が増えてきましたね。自分もBotで高知県の企業を応援するサービスを作っていたのだけど、2月5日にサービスを停止しました。

このブログは予約投稿なので、これが配信された時にはTwitterから具体的なAPIの値段などが発表されていると思います。その発表次第ですがBotを再稼働するという選択も残っているのですが、どうなるかは分からないです。

そんな中でPHP言語を使用しMastodonのAPIを使って「投稿だけ」する。コードを書きましたのでお裾分けです。

https://qiita.com/taoka-toshiaki/items/483340a28c03a1828400

php Mastodon.php 'テスト投稿です'
<?php
require "config.php";
class Mastodon{
    const method = "POST";
    const host = "mstdn.jp";
    const endpoint  = "/api/v1/statuses";
    public static function toot($postdata = null)
    {
        if(!is_null($postdata)){
            $data = http_build_query($postdata);
            exec('curl -X POST -d "'.$data.'" --header "Authorization: Bearer '.ACCESSTOKEN.'" -sS https://'.self::host . self::endpoint.'; echo $?',$output);
            var_dump($output);
        }
    }
}
//    「未収載」    -> 'unlisted'
//    「公開」      -> 'public'
//    「非公開」    -> 'private'
//    「ダイレクト」 -> 'direct'
if($argv[1]){
    $postdata = [
        "visibility"=>"public",
        "status"=>strip_tags($argv[1]),
    ];
    Mastodon::toot($postdata);
}
<?php
define('ACCESSTOKEN','xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx');

タグ

ACCESSTOKEN, API, argv, Authorization, Bearer, BOT, echo, endpoint, exec, gt, header, lt, mastodon, null, php define, php require, quot, toot, Twitter, TwitterAPI,

Twitterで自動投稿する雛形-#脱TwitterAPI。

2023.02.05

Logging

おはようございます、この記事はQiitaに投稿したもののと同じ内容になります。

エンジニアに悲報としか言えない今回の発表・イーロン・マスク氏って👹

2月9日でTwitterAPIが無料で使えなくなるのでその対応をしないといけない。
そんなエンジニアさんもいらっしゃると思います。

APIサービスに月、1万円払えないという会社は中小企業には多いと思います、それで取引を解消される企業とかもあったりするかも。

そんな方は一個VPSサーバーを構えてNodeJSをインストールして下記の雛形コードを元にゴニョゴニョしたら何とかなるかも知れません。🫠

因みにこれはchatGPTとの合作だったりします。

  • いつまで動作するかは保証しません。尚、これは雛形ですので、これに細工をして常時接続で
  • TweetやRTするようにコードを変更しないといけません。もしくは時間を置いてTweetするなど。
node sample.js 'username' 'password' 'テスト投稿'
const puppeteer = require('puppeteer');

const [username, password ,tw] = process.argv.slice(2);

(async () => {
    
    const browser = await puppeteer.launch({ headless: true });
    const page = await browser.newPage();
    await page.goto('https://twitter.com/login');

    await page.waitForTimeout(3000);
    await page.waitForSelector('input[autocomplete="username"]');
    await page.type('input[autocomplete="username"]', username);

    const divs = await page.$$('div[role="button"]');
    await divs[2].click();

    await page.waitForTimeout(3000);
    await page.waitForSelector('input[autocomplete="current-password"]');
    await page.type('input[autocomplete="current-password"]', password);
    

    await page.waitForSelector('div[data-testid="LoginForm_Login_Button"]');
    await page.click('div[data-testid="LoginForm_Login_Button"]');

    await page.waitForNavigation();

    console.log('Login successful');

    await page.waitForTimeout(3000);
    await page.waitForSelector('div[data-testid="tweetTextarea_0"]');
    await page.click('div[data-testid="tweetTextarea_0"]');
    

    await page.waitForSelector('div[data-testid="tweetTextarea_0"]');
    await page.type('div[data-testid="tweetTextarea_0"]',tw);
    await page.waitForTimeout(3000);

    await page.waitForSelector('div[data-testid="tweetButtonInline"]');
    await page.click('div[data-testid="tweetButtonInline"]');
    console.log('Tweet posted');                
    await browser.close();
})();

タグ

async, autocomplete, await browser.close, await browser.newPage, await page.goto, await page.waitForSelector, await page.waitForTimeout, ChatGPT, const, data-testid, div, headless, input, nodejs, password, qiita, require, tw, TwitterAPI, username,

数珠繋ぎのツイートシステムに予約機能を付けました😂 #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, コード, サイト, ツイート, ところ, バージョン, ブログ, リツイート, リプライ, , 今日, 使用, 公式, 公開, 土日, 対応, 少し, 抜粋, 数珠繋ぎ, 方法, 日本語, 毎日, , 言語, 記事, 記載,

自身がフォローしているTwitterアカウントでリスト自動仕分けする方法!?

2022.01.24

Logging

昨日は雨がシトシトと降っていた高知県ですが、あまり寒さを感じなくなってきていますね😌。早く春になれば良いのになって思っております。

ソースコードを読んでいただければ大体分かるかとも思いますが、そんなに難しいコードではありません。タイトル通りの処理をしています。コマンドからファイルを叩くと処理が実行されてそれぞれのリストに仕分けされます、ここでポイントなのはlist_idはどうやって導けばよいのという疑問とTwitterOAuthって何という疑問ぐらいかと思います。

list_idは事前に空のリストを生成すると自動的に割り振られるご自身のリストURLの数値部分になります。次にTwitterOAuthというのは何かというと、これはTwitterAPIを簡単に叩けるライブラリになります。これを事前にインストールすることにより簡単に処理ができます。

尚、ソースコードはTwitterAPI2.0バージョンではありません。そのうち廃止される方で書いています。

<?php
require_once("../vendor/autoload.php");

use Abraham\TwitterOAuth\TwitterOAuth;

if ($argv[0]) {
    require_once "./tw-config.php";

    date_default_timezone_set('Asia/Tokyo');
    $connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, ACCESS_TOKEN, ACCESS_TOKEN_SECRET);
    $response_followers = $connection->get("friends/ids", array(
        'screen_name' => 'zip358com',
        'count' => 1000
    ));
    if ($response_followers->ids) {
        foreach ($response_followers->ids as $key => $val) {
            $response_users = $connection->get("users/show", array(
                'user_id' => $val
            ));
            if(preg_match("/(機械学習|人工知能|AI|Learning)/",$response_users->description)){
                print "[機械学習|人工知能|AI|Learning]". $response_users->id . PHP_EOL . $response_users->description . "," . PHP_EOL;
                $connection->post("lists/members/create", array(
                    'list_id'=>1485120628206497798,
                    'user_id'=>$response_users->id
                ));
            }
            if(preg_match("/(web|WEB|Web|プログラマー|エンジニア|プログラム|プログラミング|API)/",$response_users->description)){
                print "(web|WEB|Web|プログラマー|エンジニア|プログラム|プログラミング|API)". $response_users->id . PHP_EOL . $response_users->description . "," . PHP_EOL;
                $connection->post("lists/members/create", array(
                    'list_id'=>1485121383101526018,
                    'user_id'=>$response_users->id
                ));
            }
            if(preg_match("/(イラスト|写真|デザイン|art|Art|絵|漫画)/",$response_users->description)){
                print "(イラスト|写真|デザイン|art|Art|絵|漫画)". $response_users->id . PHP_EOL . $response_users->description . "," . PHP_EOL;
                $connection->post("lists/members/create", array(
                    'list_id'=>1485121210816294912,
                    'user_id'=>$response_users->id
                ));
            }
            if(preg_match("/(電車|メトロ|運行情報)/",$response_users->description)){
                print "(電車|メトロ)". $response_users->id . PHP_EOL . $response_users->description . "," . PHP_EOL;
                $connection->post("lists/members/create", array(
                    'list_id'=>1485121509320687619,
                    'user_id'=>$response_users->id
                ));
            }            
            if(preg_match("/(高知県|高知市)/",$response_users->description)||preg_match("/(高知県|高知市|kochi)/",$response_users->location)){
                print "(高知県|高知市)". $response_users->id . PHP_EOL . $response_users->description . "," . PHP_EOL;
                $connection->post("lists/members/create", array(
                    'list_id'=>1485121289165893632,
                    'user_id'=>$response_users->id
                ));
            }                        
        }
    }
}

タグ

ID, LIST, Twitte, Twitter, TwitterAPI, TwitterOAuth, url, アカウント, インストール, コード, ここ, こと, コマンド, これ, ご自身, ソース, それぞれ, タイトル, ファイル, フォロー, ポイント, ライブラリ, リスト, 事前, , 処理, 実行, 数値, 方法, , 昨日, 生成, 疑問, , 簡単, 自動, 自身, 部分, , 高知県,

ドロップシッピングという副業を妄想してみた。

2018.07.04

Logging


ドロップシッピングという副業を妄想してみた。
ドロップシッピングとは在庫を持たなくてネットショップを開業することの
出来る仕組みの事を指す。
簡単に言えばアフェリエイトとの最終形態みたいなものです。
商品が売れると5%?20%の収益が発生します。

 
ここで思ったのが売れるのか?
ぐぐると売れないという声が多数聞くのですが
もしもドロップシッピングとかAPI機能があり、これをうまく
使用すれば稼げるじゃないかなと思い始めています。
Twitterのフォロワーが1000ぐらいあれば
なんとかなりそうな気がします。
https://www.moshimo.com/guest/help/detail?id=104
SNSを駆使してサイトへ誘導することは可能だと思います。
ちなみにフォロワーは購入することが出来てしまうのでそこから
TwitterAPIなどでRTなどで何とかすればなんとかなるかも。
問題点はサイトのデザインだと思います、
どれぐらい信用のできるサイトを作るのかというのが
一番の大事なのかなと思っています。
トイウコトデ、このサイトとは別に
独立してドロップシッピングサイトを構築してみようかなと
思っています。
うまく行かなくても月に1000円ぐらいは収益でると思います。
※広告宣伝費を個人がおこなうと、ガンガン無くなりますのでTwitterで
なんとかしようと思います、儲けがでたら広告も出そうかな。
夢は広がります・・・・妄想してみた。
http://www.moshimo.com/pdf/moshimo_api.pdf
https://www.moshimo.com/

タグ

API機能, from Moshimo, from Moshimo_co, TwitterAPI, アフェリエイト, トイウコトデ, どれぐらい信用, ドロップシッピング, ドロップシッピングサイト, フォロワー, 仕組み, 儲け, 副業, 副業入門, 収益, 問題点, 広告宣伝費, 最終形態,