0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Node.jsでTwitter APIを使って画像付きでツイートするメモ upload media v2対応

Last updated at Posted at 2025-09-15

はじめに

上記記事ではできなかったupload media v2を使ってアップロードをする方法です。
他のSNSのように画像とツイートを一緒にapiを呼ぶのではなく、v1と同じく、一度メディアのみアップロードして、返り値のmedia idをくっつけてメッセージっをポストするという方法です。

import {TwitterApi, TwitterApiReadWrite,SendTweetV2Params} from 'twitter-api-v2';
import {promises as fs} from 'fs';
export async function postToXWithImage(message: string, filePath: string): Promise<{ success: boolean }> {
    const {
        API_KEY,
        API_KEY_SECRET,
        ACCESS_TOKEN,
        ACCESS_TOKEN_SECRET,
    } = process.env;
    if (!API_KEY || !API_KEY_SECRET || !ACCESS_TOKEN || !ACCESS_TOKEN_SECRET) {
        throw new Error('Twitter API の認証情報が不足しています。環境変数(API_KEY, API_KEY_SECRET, ACCESS_TOKEN, ACCESS_TOKEN_SECRET)を確認してください。');
    }
    const client: TwitterApi = new TwitterApi({
        appKey: API_KEY,
        appSecret: API_KEY_SECRET,
        accessToken: ACCESS_TOKEN,
        accessSecret: ACCESS_TOKEN_SECRET,
    });
    const twitterClient: TwitterApiReadWrite = client.readWrite
    try {
        let contentType: 'image/jpeg' | 'image/png' = 'image/jpeg'
        if (filePath.endsWith('.png')) {
            contentType = 'image/png'
        }
        const photoData: Buffer = await fs.readFile(filePath)
        const mediaId: string = await client.v2.uploadMedia(photoData, {
            media_type: contentType,
            media_category: 'tweet_image'
        })
        const tweet:SendTweetV2Params = {text: message, media: {media_ids: [mediaId]}}
        await twitterClient.v2.tweet(tweet)
        return {
            success: true
        }
    } catch (e: any) {
        return {
            success: false,
        }
    }
}

まとめ

aiに「いやいや、あんさんmediaupload v1を使ってアップロード使うのが常識っすよ。v2ではアップロードできないっすよ」と割と強い口調で否定されました。押し通す力。

参考

API v2
https://github.com/PLhery/node-twitter-api-v2/blob/master/doc/v2.md#upload-media

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?