LoginSignup
0
0

Mastodonに画像付きのトゥート(ツイート)する方法

Last updated at Posted at 2023-07-04

Mastodon-APIに画像付きのトゥート(ツイート)する方法

気付き1:ヘッダーにユーザーエージェントがないと拒否される。
気付き2:配列をhttp_build_queryで変換するとパラメーターが文字化けになる。

<?php
class Mastodon
{
    const host = "mstdn.jp";
    const endpoint1  = "/api/v1/statuses";
    const endpoint2  = "/api/v1/media";

    public function toot($text){
        $data = array('file' => new CURLFile("/var/www/html/t_m/image.png", 'image/png', "image.png"));
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, "https://" . self::host . self::endpoint2);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        curl_setopt($ch, CURLOPT_HTTPHEADER, ['User-Agent: ' . $_SERVER['HTTP_USER_AGENT'], 'Content-Type: multipart/form-data', 'Authorization: Bearer ' . MSTDN_ACCESSTOKEN]);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        $response =   json_decode(@curl_exec($ch));
        curl_close($ch);
        if (isset($response->id)) {
            $postdata = [
                "visibility" => "public",
                "media_ids" => [$response->id],
                "status" => strip_tags($text),
            ];
            $data = json_encode($postdata);
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, "https://" . self::host . self::endpoint1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
            curl_setopt($ch, CURLOPT_HTTPHEADER, ['User-Agent: ' . $_SERVER['HTTP_USER_AGENT'], 'Content-Type: application/json', 'Authorization: Bearer ' . MSTDN_ACCESSTOKEN]);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
            $response =  @curl_exec($ch);
            curl_close($ch);
        }
    }
}
0
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
0
0