Skip to content

Instantly share code, notes, and snippets.

@grrowl
Created April 27, 2016 08:26
Show Gist options
  • Save grrowl/8b7d2f34cc33ef5227f498a423f01801 to your computer and use it in GitHub Desktop.
Save grrowl/8b7d2f34cc33ef5227f498a423f01801 to your computer and use it in GitHub Desktop.
Google Docs script to automate Twitter posting
// source: https://ctrlq.org/code/19702-twitter-image-upload
function autoTweet() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName("schedule"); // This must match the sheet name!
var rows = sheet.getRange("A:D").getValues();
var titleList = [], newValues = [],
response, doc, title;
var twitterCallback = function(rowIndex, err, result) {
if (err) {
sheet.getRange("A:A").offset(rowIndex, 0, 1, 2).setValues([ [ "", new Date() + "\r\n" + err.toString() ] ])
throw err;
return
}
sheet.getRange("A:A").offset(rowIndex, 0, 1, 2).setValues([ [
"" + result.text +"\r\n"+ result.id_str,
new Date()
] ])
}
for (var rowIndex = 0, len = rows.length; rowIndex < len; rowIndex++) {
if (rows[rowIndex][1] == '') {
Logger.log('next post image: '+ rows[rowIndex][2])
Logger.log('next post text: '+ rows[rowIndex][3])
sendTweetwithImage({
image: rows[rowIndex][2],
text: rows[rowIndex][3]
}, twitterCallback.bind(this, rowIndex));
break;
}
}
Logger.log("No tweets found")
return null;
}
function sendTweetwithImage(post, callback) {
// get access tokens from https://dev.twitter.com/oauth/tools/signature-generator/12277450?nid=619
// https://dev.twitter.com/oauth/pin-based
// authorize, callback is "oob" for pin based
// call https://api.twitter.com/oauth/authenticate?oauth_token=<oayth token>
// https://api.twitter.com/oauth/access_token ? oauth_verifier=<pin>
var twitterKeys= {
TWITTER_CONSUMER_KEY: "xxx",
TWITTER_CONSUMER_SECRET: "xxx",
TWITTER_ACCESS_TOKEN: "yyy",
TWITTER_ACCESS_SECRET: "yyy"
};
var props = PropertiesService.getUserProperties();
props.setProperties(twitterKeys);
var twit = new Twitter.OAuth(props);
if ( twit.hasAccess() ) {
try {
var imageUrl = post.image;
var imageBlob = twit.grabImage(imageUrl, "image/jpeg");
var uploadImg = twit.uploadMedia(imageBlob);
if (uploadImg) {
var response = twit.sendTweet(post.text, {
media_ids: uploadImg.media_id_string
});
if (response) {
Logger.log("Tweet Sent " + response.id_str);
callback(null, response)
} else {
// Tweet could not be sent
// Error will be handled below, or
// Go to View -> Logs to see the error message
}
}
} catch (f) {
Logger.log(f.toString());
callback(f)
}
}
}
// util functions for the sheet
function encode(value) {
return encodeURIComponent(value);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment