Skip to content

Instantly share code, notes, and snippets.

@zuccs
Created March 7, 2017 05:17
Show Gist options
  • Save zuccs/962540225113a626f77ad543abf9f7a6 to your computer and use it in GitHub Desktop.
Save zuccs/962540225113a626f77ad543abf9f7a6 to your computer and use it in GitHub Desktop.
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 = 2;
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.";
}
};
function main() {
var slack = new SlackAPI({
webhookUrl : "USE_YOUR_OWN_URL"
});
var currentAccount = AdWordsApp.currentAccount();
var stats = currentAccount.getStatsFor('YESTERDAY');
var text = 'Clicks: *' + stats.getClicks() + '*' +
'\nImpressions: *' + stats.getImpressions() + '*' +
'\nAverage CPC: *$' + stats.getAverageCpc() + '*' +
'\nAverage Position: *' + stats.getAveragePosition() + '*';
slack.sendMessage({
channel: "#fam",
icon_emoji: ":adwords:",
username: "AdWords Bot",
attachments: [
{
"pretext": "Here are some stats for yesterday:",
"text": text,
"color": "#7CD197",
"mrkdwn_in": ["pretext", "text", "fields"], // enable Markdown on all fields
}
]
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment