LoginSignup
1
0

Twitter API V2では画像ツイートが出来ない-今のところの対処方法。

Posted at

Twitter API V2では画像ツイートが出来ない-今のところの対処方法です。
コマンドラインからの実行した感じになります。
開発環境はPHP8系です。
尚、ライブラリやコンフィグファイルは推測して設置してください🙇。

<?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("これはテストです");
    }    
}

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0