Skip to content

Instantly share code, notes, and snippets.

@yuya
Forked from rcknr/UploadWithMedia.gs
Last active February 24, 2019 04:04
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yuya/8472634 to your computer and use it in GitHub Desktop.
Save yuya/8472634 to your computer and use it in GitHub Desktop.
var API = {
UPDATE_WITH_MEDIA : "https://api.twitter.com/1.1/statuses/update_with_media.json"
};
function oAuthConfig() {
var oAuthConfig = UrlFetchApp.addOAuthService("twitter");
oAuthConfig.setAccessTokenUrl("https://api.twitter.com/oauth/access_token");
oAuthConfig.setRequestTokenUrl("https://api.twitter.com/oauth/request_token");
oAuthConfig.setAuthorizationUrl("https://api.twitter.com/oauth/authorize");
oAuthConfig.setConsumerKey(ScriptProperties.getProperty("consumer_key"));
oAuthConfig.setConsumerSecret(ScriptProperties.getProperty("consumer_secret"));
}
function postImage(tweetText, imageUrl) {
oAuthConfig();
var boundary = "cuthere",
status = tweetText,
picture = UrlFetchApp.fetch(imageUrl).getBlob().setContentTypeFromExtension(),
requestBody, options, request;
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());
options = {
oAuthServiceName : "twitter",
oAuthUseToken : "always",
method : "POST",
contentType : "multipart/form-data; boundary=" + boundary,
payload : requestBody
};
return UrlFetchApp.fetch(API.UPDATE_WITH_MEDIA, options);
}
function tweetTest() {
var tweetText = "GAS update_with_media テスト",
imageUrl = "http://blog-imgs-38.FC2.com/n/e/n/nenesoku/120ebf562bdd2446fbf8459b3e6265e7.jpg";
postImage(tweetText, imageUrl);
}
@vijay-shanker
Copy link

ReferenceError: UrlFetchApp is not defined .. :(

@AlexandraKlein
Copy link

UrlFetchApp is only available on server

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment