Twitter API V2では画像ツイートが出来ないと流れてきたので対処方法

20230602

Logging

おはようございます。先日、Twitter API V2では画像ツイートが出来ないと流れてきたので対処方法を載せときます。Qiitaにも掲載していますが、こちらでも記載します。コードはいつまで使用出来るかは不明ですね、イーロン・マスクのサジカゲンで無料プランでは出来なくなる可能性を秘めています。今のところ、使用できるコードです。PHP8系では動きますがPHP7系は:mixedの部分を退けてあげないと動かないかもです。因みにPythonのサンプルコードが公式にはあったような気がします。

<?php

require_once "tw-config-v2.php";
require_once "vendor/autoload.php";

use Abraham\TwitterOAuth\TwitterOAuth;

class tw
{
    public $connection = null;
    public $media = null;
    public function __construct()
    {
        $this->connection = new TwitterOAuth(APIKEY, APISECRET, ACCESSTOKEN, ACCESSTOKENSECRET);
    }

    /**
     * イメージのエンドポイントを取得する v1.1 そのうち廃止されそう。
     * @param $imageName
     * @return boolean
     */
    public function getImage($imageName = null): bool
    {
        if (empty($imageName)) {
            return false;
        }
        $this->media = $this->connection->upload('media/upload', ['media' => "/var/www/html/tw/tmp/images/$imageName"]);
        return true;
    }

    /**
     * イメージ付きでツイート。
     * @param $text
     * @return mixed
     */
    public function tweet($text = null): mixed
    {
        if (!empty($text) && isset($this->media->media_id_string)) {
            $param = [
                'text' => $text,
                'media' => [
                    'media_ids' => [
                        $this->media->media_id_string
                    ]
                ]
            ];
            $this->connection->setApiVersion('2');
            return $this->connection->post('tweets', $param, true);
        }
        return false;
    }
}

if($argv[0]){
    $tw = new tw();
    if($tw->getImage("php2023.png"))
    {
        $tw->tweet("これはテストです");
    }    
}

タグ

argv, bool, connection, construct, empty, getImage, isset, media', mixed, PARAM, qiita, quot, quot;vendor, return, tmp, tw, Tweet, use AbrahamTwitterOAuthTwitterOAuth, イーロン, サジカゲン,