17
13

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Node.jsでTwitterに画像投稿するメモ

Posted at

Node.js v8.11.3でやってみました。

ライブラリインストール

npm i twitter

コード

こちらを参考に

https://github.com/desmondmorris/node-twitter/tree/master/examples#media

POST 'media/upload'を実行してアップロードしてからmedia_id_stringをセットしてPOST 'statuses/update'を実行すると画像付き投稿がされます。

imagepost.js
'use stritct';

const twitter = require('twitter');
const config = require('./config');
const client = new twitter({
    consumer_key: config.twitter.consumerKey,
    consumer_secret: config.twitter.consumerSecret,
    access_token_key: config.twitter.accessTokenKey,
    access_token_secret: config.twitter.accessTokenSecret
});

const data = require('fs').readFileSync('./image.jpg'); //投稿する画像
const mes = 'Hey Hey Hey'; //投稿するメッセージ

(async () => {
	 //画像のアップロード
    const media = await client.post('media/upload', {media: data});
    console.log(media);
    
    //Twitterに投稿
    const status = {
        status: mes,
        media_ids: media.media_id_string // Pass the media id string
    }
    const response = await client.post('statuses/update', status);
    console.log(response);
})();

実行

17
13
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
17
13

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?