Created
May 3, 2016 15:23
-
-
Save jimkang/0d82372c5c0e718d134e96d1ca6fa290 to your computer and use it in GitHub Desktop.
One way to post an image to Twitter, starting with an imageURL
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var request = require('request'); | |
var async = require('async'); | |
// TODO: This could be in its own package. | |
function postImage(opts, allDone) { | |
var twit; | |
var dryRun; | |
var imgurl; | |
var altText; | |
var caption; | |
if (opts) { | |
twit = opts.twit; | |
dryRun = opts.dryRun; | |
imgurl = opts.imgurl; | |
altText = opts.altText; | |
caption = opts.caption; | |
} | |
var mediaPostData; | |
async.waterfall( | |
[ | |
getImage, | |
postMedia, | |
postMetadata, | |
postTweet | |
], | |
allDone | |
); | |
function getImage(done) { | |
var requestOpts = { | |
url: imgurl, | |
encoding: null | |
}; | |
request(requestOpts, checkResponse); | |
function checkResponse(error, response) { | |
if (error) { | |
done(error); | |
} | |
else if (response.statusCode !== 200) { | |
done(new Error('Could not get image. Status code: ' + response.statusCode)); | |
} | |
else if (response.headers['content-type'].indexOf('image/') !== 0) { | |
done(new Error('Did not receive image as response.')); | |
} | |
else { | |
done(null, response); | |
} | |
} | |
} | |
function postMedia(imageResponse, done) { | |
debugger; | |
var mediaPostOpts = { | |
media_data: new Buffer(imageResponse.body).toString('base64') | |
}; | |
twit.post('media/upload', mediaPostOpts, done); | |
} | |
function postMetadata(theMediaPostData, done) { | |
debugger; | |
// Save this for other functions in the above scope. | |
mediaPostData = theMediaPostData; | |
var metaParams = { | |
media_id: mediaPostData.media_id_string, | |
alt_text: { | |
text: altText | |
} | |
}; | |
twit.post('media/metadata/create', metaParams, done); | |
} | |
function postTweet(metaDataPostData, response, done) { | |
debugger; | |
if (dryRun) { | |
console.log('Would have tweeted: using', opts); | |
callNextTick(done); | |
} | |
else { | |
var body = { | |
status: caption, | |
media_ids: [ | |
mediaPostData.media_id_string | |
] | |
}; | |
twit.post('statuses/update', body, done); | |
} | |
} | |
} | |
module.exports = postImage; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment