Skip to content

Instantly share code, notes, and snippets.

@farski
Last active January 24, 2021 08:20
Show Gist options
  • Save farski/059659cd6883b313d3b5 to your computer and use it in GitHub Desktop.
Save farski/059659cd6883b313d3b5 to your computer and use it in GitHub Desktop.
var url = require('url');
var https = require('https');
var querystring = require('querystring');
var webhookID = 'YOUR/WEBHOOK/integration-id';
var webhookURLBase = 'https://hooks.slack.com/services/';
var webhookURL = [webhookURLBase, webhookID].join('');
var slashCommandToken = 'your-slash-command-token';
var postPayload = function (payload, callback) {
var json = JSON.stringify(payload);
var body = json;
var options = url.parse(webhookURL);
options.method = 'POST';
options.headers = {
'Content-Type': 'application/json',
'Content-Length': Buffer.byteLength(body),
};
var postReq = https.request(options, function (res) {
var chunks = [];
res.setEncoding('utf8');
res.on('data', function (chunk) {
return chunks.push(chunk);
});
res.on('end', function () {
var body = chunks.join('');
if (callback) {
callback({
body: body,
statusCode: res.statusCode,
statusMessage: res.statusMessage
});
}
});
return res;
});
postReq.write(body);
postReq.end();
};
var textForParams = function (params) {
if (params.text && params.text.indexOf(' ') != -1) {
return params.text;
} else {
var intro = "Okay folks, let's move this conversation";
var to = (params.text ? ('#' + params.text).replace(/##/, '#') : 'elsewhere');
return [intro, ' ', to, '.'].join('');
}
};
var payloadForParams = function (params) {
return {
channel: ['#', params.channel_name].join(''),
text: textForParams(params),
link_names: 1,
mrkdwn: true
};
};
var processEvent = function (event, context) {
var params = querystring.parse(event.postBody);
if (params.token !== slashCommandToken) {
context.fail(new Error('Invalid Slash Command token.'));
return;
}
postPayload(payloadForParams(params), function (response) {
if (response.statusCode < 400) {
console.info('Message posted successfully');
context.succeed();
} else if (response.statusCode < 500) {
console.error("Error posting message to Slack API: " + response.statusCode + " - " + response.statusMessage);
context.succeed(); // Don't retry because the error is due to a problem with the request
} else {
// Let Lambda retry
var msg = "Server error when processing message: " + response.statusCode + " - " + response.statusMessage
context.fail(new Error(msg));
}
});
};
exports.handler = function (event, context) {
try {
processEvent(event, context);
} catch (e) {
context.fail(e);
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment