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

2023.06.02

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, イーロン, サジカゲン,

(´ι _` )アッそうなんだそうなんだPHP fileメソッド

2015.11.09

Logging


PHPのfileメソッドっていうのが便利です。
ファイルを配列として引っこ抜いてくれる。こんな関数便利だなと
おそらく他の言語でも常識的にある関数なんだろうけど
自分はあまり知らなかったので便利だなと。
もうひとつ便利な関数は配列の中に空の値があったりすると
その配列を削除してくれるarray_filterとかいうものです。
これは便利・・・何故かってPHP、配列の中が空でも
値があるよって判断するです。そういう時に少し便利です。
emptyは使えないので・・・。もし配列が空でも必要な場合は
strlenとかでバイト数を数えるなどで対応するしか無いですね。
そういう事でメモがてらに残しときます。

$hoge = file("hoge.txt");
for($i=0;$i<sizeof($hoge);$i++){
echo hoge[$i]."<br>\n";
}
print($hoge);
$hoge2 = array_filter($hoge);
print($hoge2);

タグ

0, 2, array, br, echo, empty, file, filter, For, gt, hoge, lt, php, print, sizeof, strlen, txt, アッ, これ, バイド, ファイル, メソッド, メモ, もうひとつ, もの, , , , 便利, , 判断, 削除, 場合, 対応, 少し, 必要, , , 自分, 言語, 配列, 関数,