Skip to content

Instantly share code, notes, and snippets.

@codekiln
Created September 13, 2017 23:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save codekiln/72a414d05f236d919232e88ffaef3c94 to your computer and use it in GitHub Desktop.
Save codekiln/72a414d05f236d919232e88ffaef3c94 to your computer and use it in GitHub Desktop.
AWS Lambda Post To Slack Channel from DynamoDB
var AWS = require('aws-sdk');
var path = require('path');
var https = require('https');
/**
* This assumes that messages are added to DynamoDB
* with parameters `name` and `message`.
*
* To get this to work with your slack channel, you
* first need to configure Incoming Webhook for your
* Slack organization.
*
* See the Bonus Activity from [Lab 4 from the AWS Lambda Zombie Workshop](https://github.com/awslabs/aws-lambda-zombie-workshop/blob/master/README.md#lab-4---slack-integration)
* for the context.
**/
exports.handler = function(event, context) {
console.log(JSON.stringify(event, null, ' '));
event.Records.forEach(function(record) {
if (typeof record.dynamodb.NewImage != 'undefined') {
postToSlack(
record.dynamodb.NewImage.name.S,
record.dynamodb.NewImage.message.S,
function (status) {
context.done(null, status);
}
);
} else {
console.log('skipping non-inserts');
}
});
};
function postToSlack(from, body, completedCallback) {
var message = {
username: from,
text: body,
icon_emoji: ":ghost:"
};
var messageString = JSON.stringify(message);
console.log("message sent to slack: ", messageString);
// Options and headers for the HTTP request
var options = {
host: 'hooks.slack.com',
port: 443,
path: '/services/POST/YOUR/SERVICES_URL',
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': Buffer.byteLength(messageString)
}
};
// Setup the HTTP request
var req = https.request(options, function (res) {
res.setEncoding('utf-8');
// Collect response data as it comes back.
var responseString = '';
res.on('data', function (data) {
responseString += data;
});
// Log the responce received from Slack.
// Or could use JSON.parse(responseString) here to get at individual properties.
res.on('end', function () {
console.log('Slack Response: ' + responseString);
completedCallback('API request sent successfully.');
});
});
// Handler for HTTP request errors.
req.on('error', function (e) {
console.error('HTTP error: ' + e.message);
completedCallback('API request completed with error(s).');
});
// Send the HTTP request to the Slack API.
// Log the message we are sending to Slack.
console.log('Slack API call: ' + messageString);
req.write(messageString);
req.end();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment