/***********************************
* Slack Notifications API
* check out https://api.slack.com/docs/formatting or
* https://api.slack.com/docs/attachments
***********************************/
function SlackAPI(config) {
this.webhookUrl = config.webhookUrl;
// Send a message to slack. The config can
// be as simple as a string or an object
// for passing more complex messages.
this.sendMessage = function(config) {
if(typeof config == 'object') {
postToSlack(this.webhookUrl, config);
} else {
postToSlack(this.webhookUrl, { text : config });
}
};
// Take care of all the messy stuff like
// retries and status codes.
function postToSlack(url, payload) {
var options = {
method: 'POST',
payload: JSON.stringify(payload),
muteHttpExceptions: true
};
var retries = 3;
while(retries > 0) {
try {
var resp = UrlFetchApp.fetch(url,options);
if(resp.getResponseCode() == 200) {
return true;
} else {
Logger.log(
Utilities.formatString(
"WARNING: Slack returned status code of %s and a message of: %s",
resp.getResponseCode(),
resp.getContentText()
)
);
Logger.log('Waiting 1 seconds then retrying...');
Utilities.sleep(1000);
retries--;
}
} catch(e) {
Logger.log("ERROR: Something failed in UrlFetchApp. Retrying in 1 second...");
Utilities.sleep(1000);
retries--;
}
}
throw "Either UrlFetchApp is broken or the Slack Webhook is not configured properly.";
}
};
// Usage:
var slack = new SlackAPI({
webhookUrl : "https://hooks.slack.com/services/.../.../..."
});
slack.sendMessage('This is a test');
slack.sendSimpleMessage({ //or sendMessage(
channel: "#general",
username: "webhookbot",
text: "This is posted to #general and comes from a bot named webhookbot.",
icon_emoji: ":ghost:",
//icon url
"icon_url" : "https://ssl.gstatic.com/awfe30/aw3_cm_20160229_030026_RC4/cm/18EFA99EA70FA5326D7FAB2041DA3661.cache.png",
//attachment
"attachments": [
{
"fallback": "Your AdWords account has not had any impressions in the past hour!",
"color": "danger",
"fields": [
{
"title": "Account",
"value": AdWordsApp.currentAccount().getName(),
"short": true
},
{
"title": "Priority",
"value": "Critical",
"short": true
}
]
}
]
});
//---------------------------------------------------------------------------------------------------
//simple example
function sendSlackMessage(text, channel) {
var slackMessage = {
text: text,
icon_url:
'https://www.gstatic.com/images/icons/material/product/1x/adwords_64dp.png',
username: 'AdWords Scripts',
channel: channel
};
var options = {
method: 'POST',
contentType: 'application/json',
payload: JSON.stringify(slackMessage)
};
UrlFetchApp.fetch(SLACK_URL, options);
}