Skip to content

Instantly share code, notes, and snippets.

@scuthbert
Created March 9, 2018 00:28
Show Gist options
  • Save scuthbert/b23d71b3d4fdb491143c93a721d7cc1e to your computer and use it in GitHub Desktop.
Save scuthbert/b23d71b3d4fdb491143c93a721d7cc1e to your computer and use it in GitHub Desktop.
const https = require('https'),
qs = require('querystring'),
ACCESS_TOKEN = "ACCESS_TOKEN_FROM_SLACK",
VERIFICATION_TOKEN = "TOKEN_FROM_SLACK";
// Verify Url - https://api.slack.com/events/url_verification
function verify(data, callback) {
if (data.token === VERIFICATION_TOKEN) {
callback(null, data.challenge);
}
else {
callback("verification failed");
}
}
// Post message to Slack - https://api.slack.com/methods/chat.postMessage
function process(event, callback) {
// test the message for a match and not a bot
if (!event.bot_id && /(clauset|aaron)/ig.test(event.text)) {
var links = ["http://i.imgur.com/AxOhUDD.jpg",
"http://i.imgur.com/k5YKpGu.jpg",
"http://i.imgur.com/n26ytsd.jpg",
"http://i.imgur.com/t7mzMXa.jpg",
"http://i.imgur.com/7eJGf9O.png",
"http://i.imgur.com/GCPNAav.png",
"http://i.imgur.com/lvdKAPM.gif",
"http://i.imgur.com/wFgVcma.gif",
"http://i.imgur.com/cQZTDt5.jpg",
"http://i.imgur.com/qeI2V9C.gif",
"http://i.imgur.com/NBo0hEy.png"];
var text = `<@${event.user}> ` + links[Math.floor(Math.random()*links.length)];
var message = {
token: ACCESS_TOKEN,
channel: event.channel,
text: text
}
}
var query = qs.stringify(message); // prepare the querystring
https.get(`https://slack.com/api/chat.postMessage?${query}`);
callback(null);
}
// Lambda handler
exports.handler = (data, context, callback) => {
const done = (err, res) => callback(null, {
statusCode: err ? '400' : '200',
body: err ? (err.message || err) : JSON.stringify(res),
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
});
console.log(data.body)
switch (JSON.parse(data.body).type) {
case "url_verification":
verify(JSON.parse(data.body), done)
break;
case "event_callback":
process(JSON.parse(data.body).event, done);
break;
default:
done(null);
break;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment