Skip to content

Instantly share code, notes, and snippets.

@PeterBerthelsen
Created January 21, 2019 16:23
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save PeterBerthelsen/72e74401dea8a6a3230d1680db642984 to your computer and use it in GitHub Desktop.
Save PeterBerthelsen/72e74401dea8a6a3230d1680db642984 to your computer and use it in GitHub Desktop.
sendTweet Function
function sendTweet(TweetText, IdInResponseTo, ImageAttachURL){
//////////////////////////Set Variables///////////////////////////////////////////////////////
var ss = SpreadsheetApp.getActiveSpreadsheet(); //spreadsheet
var logsheet = ss.getSheetByName("TweetLog");
var lastRow = Math.max(logsheet.getLastRow(),1) + 1;
var twitterKeys= { //Twitter Authentication Tokens to pass through props
TWITTER_CONSUMER_KEY: "[YOUR VALUE HERE]",
TWITTER_CONSUMER_SECRET: "[YOUR VALUE HERE]",
TWITTER_ACCESS_TOKEN: "[YOUR VALUE HERE]",
TWITTER_ACCESS_SECRET: "[YOUR VALUE HERE]"
}
var props = PropertiesService.getScriptProperties(); //New Properties Service
props.setProperties(twitterKeys); //Pass Authentication through Service
var params = new Array(0); //Array for params (reply, images, etc)
var service = new Twitter.OAuth(props); //Attempt Connection with Service
console.log("sendTweet Initiated!"); //log function start
console.log("using params:" //log params passed through function
+ "|TweetText: " + TweetText
+ "|IdInResponseTo: " + IdInResponseTo
+ "|ImageAttachURL: " + ImageAttachURL);
//////////////////////////Authenticate////////////////////////////////////////////////////////
if (!service.hasAccess()) { //If credentials do NOT grant access...
console.log("Authorization Failed"); //log authentication failure
} else { //If credentials grant access...
console.log("Authentication Successful"); //log authentication success
var status = TweetText; //Tweet text
//////////////////////////Reply/Thread////////////////////////////////////////////////////////
if (IdInResponseTo == 0 || IdInResponseTo == null) { //If no reply is provided...
console.log("No reply ID provided."); //log no reply
} else { //If Reply (or thread) is set up...
var ReplyId = IdInResponseTo; //variable for replies, passed to .sendTweet
console.log("In response to: " + ReplyId) //log response to
params.in_reply_to_status_id = ReplyId; //send with reply
params.auto_populate_reply_metadata = true; //auto-mentions previous user (for thread)
}
//////////////////////////Upload Images///////////////////////////////////////////////////////
if (ImageAttachURL == 0 || ImageAttachURL == null){ //If no image URLs are listed...
console.log("No images detected!"); //Log no images detected
} else { //If image URLs are listed...
try{ //Attempt to upload images from URLs
var mediaId = new Array(0); //IDs for uploads, will be CSVs
var imgs = ImageAttachURL.split(","); //Split URL string into individual links
console.log(imgs.length + " images detected!"); //Log number of images to upload
for (i in imgs){ //For each image detected...
console.log("processing upload: " + imgs[i]); //Log the upload
var blob = UrlFetchApp.fetch(imgs[i]).getBlob(); //Get URL and convert to Blob format
var imageId = service.uploadMedia(blob); //set imageID variable to pass through .uploadMedia
if (imageId) { //If imageId is valid...
if (i == 0) { //If it's the first image...
mediaId = mediaId + imageId.media_id_string; //get media ID (used to tweet image)
} else if (i < 4) { //If it's the second, third, or fourth image
mediaId = mediaId + "," + imageId.media_id_string; //get media ID
console.log(imageId.media_id_string + " uploaded"); //log media ID number
} else { //If 4 images have already been added to mediaId...
console.log("Maximum Image (4) already attached! " +
imageId.media_id_string + " NOT included"); //Prevents tweet error for more than 4 images
}
} else { //If imageId is not found...
console.log("Image upload FAILED!"); //log failure
}
} //next image
console.log("MEDIA ID(s): " + mediaId); //Log number of successful uploads
params.media_ids = mediaId; //set media_ids to string value containing uploaded IDs
} catch (e) { //If image upload fails (bad URL, etc)...
console.log("FAILURE! Error captured: " + e); //Catch and log error
}
} //end of URL list parsing
//////////////////////////Send Tweet & Process Response///////////////////////////////////////
try{ //attempt to send tweet
var response = service.sendTweet(status, params); //enter status & params, return response
if (response) { //If response is detected...
console.log("Posted Tweet ID: " + response.id_str); //log response
try { //attempt to log...
logsheet.insertRowBefore(2); //insert row for logs
logsheet.getRange(2,1).setValue(Date()); //timestamp
logsheet.getRange(2,2).setValue(response.id_str); //tweet id
logsheet.getRange(2,3).setValue(response.text); //tweet text
logsheet.getRange(2,4).setValue(response.in_reply_to_status_id_str); //reply to
logsheet.getRange(2,5).setValue(ImageAttachURL); //image urls
} catch (err) { //if unable to log (formula bar execution)...
console.log("unable to update logs. Error thrown: " + err); //log error
}
return (response.id_str); //return tweet ID (useful for threads & logs)
} else { //if no response is detected...
console.log("No Response"); //log failure
}
} catch (e) { //catch errors from Twitter resource library
console.log("Error: " + e); //log error messages
return(response.id_str);
}
} //end access-required functions
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment