Last active
April 11, 2018 06:31
-
-
Save saagarjha/ea067aff9674e8382c15d3b7dec66594 to your computer and use it in GitHub Desktop.
Google Apps Script to post new xkcd comics to a Slack channel
This file contains 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
function postUpdatedxkcdIfNecessary() { | |
var properties = PropertiesService.getUserProperties(); | |
var latestComic = JSON.parse(UrlFetchApp.fetch("http://xkcd.com/info.0.json").getContentText()); | |
if (latestComic["num"] > properties.getProperty("lastComic")) { | |
var title = latestComic["title"]; | |
var imageURL = latestComic["img"]; | |
var altText = latestComic["alt"]; | |
var number = latestComic["num"]; | |
var day = latestComic["day"]; | |
var month = latestComic["month"]; | |
var year = latestComic["year"]; | |
var message = { | |
"token": "[SLACK AUTHENTICATION TOKEN]", | |
"channel": "#xkcd", | |
"text": "New xkcd!", | |
"username": "xkcd bot", | |
"icon_url": "[AVATAR URL]", | |
"attachments": JSON.stringify([ | |
{ | |
"title": title, | |
"image_url": imageURL, | |
}, | |
{ | |
"fields": [ | |
{ | |
"title": "Alt text:", | |
"value": altText, | |
"short": false, | |
}, | |
{ | |
"title": "Number", | |
"value": number.toFixed(0), | |
"short": true, | |
}, | |
{ | |
"title": "Date Posted", | |
"value": month + "/" + day + "/" + year, | |
"short": true, | |
}, | |
{ | |
"title": "This comic on explain xkcd:", | |
"value": "http://www.explainxkcd.com/wiki/index.php/" + number.toFixed(0), | |
"short": false, | |
} | |
], | |
}, | |
]), | |
}; | |
var options = { | |
"method": "post", | |
"payload": message, | |
}; | |
var response = JSON.parse(UrlFetchApp.fetch("https://slack.com/api/chat.postMessage", options).getContentText()); | |
// Set that there was a new latest comic only if there wasn't any errors | |
// (i.e. so that we try again next time) | |
if (response["ok"]) { | |
properties.setProperty("lastComic", number); | |
} else { | |
Logger.log(response); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment