Skip to content

Instantly share code, notes, and snippets.

@msadig
Created June 21, 2018 15:01
Show Gist options
  • Save msadig/30dccada8104adc823336eaadce1cc6c to your computer and use it in GitHub Desktop.
Save msadig/30dccada8104adc823336eaadce1cc6c to your computer and use it in GitHub Desktop.
Post media files to Twitter using Google Apps Script
function getTwitterService() {
// Check https://github.com/gsuitedevs/apps-script-oauth1#usage
// for the docs
return OAuth1.createService('twitter')
// Set the endpoint URLs.
.setAccessTokenUrl('https://api.twitter.com/oauth/access_token')
.setRequestTokenUrl('https://api.twitter.com/oauth/request_token')
.setAuthorizationUrl('https://api.twitter.com/oauth/authorize')
// Set the consumer key and secret.
.setConsumerKey(TWITTER.CONSUMER_KEY)
.setConsumerSecret(TWITTER.CONSUMER_SECRET)
// Set the name of the callback function in the script referenced
// above that should be invoked to complete the OAuth flow.
.setCallbackFunction('authCallback')
// Set the property store where authorized tokens should be persisted.
.setPropertyStore(PropertiesService.getUserProperties());
}
function tweetPicFromURL(url) {
try {
var boundary = "cuthere";
var picture = UrlFetchApp.fetch(url).getBlob().setContentTypeFromExtension();
var status = "Test status";
var requestBody = Utilities.newBlob("--"+boundary+"\r\n"+
"Content-Disposition: form-data; name=\"status\"\r\n\r\n"+status+"\r\n"+
"--"+boundary+"\r\n"+
"Content-Disposition: form-data; name=\"media[]\"; filename=\""+picture.getName()+"\"\r\n"+
"Content-Type: "+picture.getContentType()+"\r\n\r\n").getBytes();
requestBody = requestBody.concat(picture.getBytes());
requestBody = requestBody.concat(Utilities.newBlob("\r\n--"+boundary+"--\r\n").getBytes());
var options =
{
method: "post",
contentType: "multipart/form-data; boundary="+boundary,
payload: requestBody
};
// twitter stuff
var api = 'https://api.twitter.com/1.1/statuses/update_with_media.json';
var twitterService = getTwitterService();
var response = twitterService.fetch(api, options);
Logger.log(response);
return response;
}
catch(e){Logger.log(e)}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment