Skip to content

Instantly share code, notes, and snippets.

@kentokento
Created February 12, 2016 03:15
Show Gist options
  • Save kentokento/0e5b79d118f901a76ff2 to your computer and use it in GitHub Desktop.
Save kentokento/0e5b79d118f901a76ff2 to your computer and use it in GitHub Desktop.
lambda send to slack
console.log('Loading function');
const https = require('https');
const url = require('url');
const slack_url = 'https://hooks.slack.com/services/${ここにtoken}';
const slack_req_opts = url.parse(slack_url);
slack_req_opts.method = 'POST';
slack_req_opts.headers = {'Content-Type': 'application/json'};
exports.handler = function(event, context) {
(event.Records || []).forEach(function (rec) {
if (rec.Sns) {
var req = https.request(slack_req_opts, function (res) {
if (res.statusCode === 200) {
context.succeed('success!!');
} else {
context.fail('status code: ' + res.statusCode);
}
});
req.on('error', function(e) {
console.log('problem with request: ' + e.message);
context.fail(e.message);
});
console.log(rec);
var slack_user = "AWS Cloud Watch";
var slack_channel = "#sample";
var icon = ":space_invader:";
var str = "No Message...";
try {
var message = JSON.parse(rec.Sns.Message);
var status = message.NewStateValue;
if (status !== undefined) {
if (status === "OK") {
icon = ":kami:";
} else if (status === "ALARM") {
icon = ":jack_o_lantern:";
} else {
throw ("undefined");
}
str = "*[ " +
status +
" ]: " +
message.AlarmName +
"*" +
"\n```\n" +
message.NewStateReason +
"\n```\n";
} else {
var payload = message.Payload;
if (payload !== undefined) {
icon = payload.icon_emoji;
slack_user = payload.username;
slack_channel = payload.channel;
str = payload.text;
} else {
throw ("undefined");
}
}
} catch(e) {
var str = "*" +
rec.Sns.Subject +
"*\n" +
rec.Sns.Message
}
req.write(JSON.stringify({text: str, channel: slack_channel, icon_emoji: icon, username: slack_user, link_names: 1}));
req.end();
}
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment