30
loading...
This website collects cookies to deliver better user experience
const twitter = require('twitter-lite');
exports.newClient = function (subdomain = 'api') {
return new twitter({
subdomain,
consumer_key: '',
consumer_secret: '',
access_token_key: '',
access_token_secret: ''
});
}
const apiClient = config.newClient();
const uploadClient = config.newClient('upload');
const fs = require('fs');
const path = require('path');
const mediaFile = fs.readFileSync(path.join(__dirname, 'hello_world.png'));
const base64image = Buffer.from(mediaFile).toString('base64');
Next, it's similar to what we did in this tutorial where a request is depending on the result of another request.
The first request is for uploading image using media/upload endpoint and the uploading subdomain. This means using uploadClient here and returns an object with media_id attribute which we save for the next step.
// Uploading an image
uploadClient.post('media/upload', { media_data: base64image })
.then(media => {
console.log('You successfully uploaded media');
var media_id = media.media_id_string;
}).catch(console.error);
You can see full details for this request here.
The second request is the normal tweeting using statuses/update endpoint to tweet with the image, which uses the apiClient.
// tweeting with text and image
apiClient.post('statuses/update', { status: 'Hello world!', media_ids: media_id })
.then(tweet => {
console.log('Your image tweet is posted successfully');
}).catch(console.error);
You can see full details for this request here.
everything in place now and we can run the app in Command Prompt using:
node index.js
const fs = require('fs');
const path = require('path');
const config = require('./config');
const apiClient = config.newClient();
const uploadClient = config.newClient('upload');
const mediaFile = fs.readFileSync(path.join(__dirname, 'hello_world.png'));
const base64image = Buffer.from(mediaFile).toString('base64');
uploadClient.post('media/upload', { media_data: base64image })
.then(media => {
console.log('You successfully uploaded media');
var media_id = media.media_id_string;
apiClient.post('statuses/update', { status: 'Hello world!', media_ids: media_id })
.then(tweet => {
console.log('Your image tweet is posted successfully');
}).catch(console.error);
}).catch(console.error);