-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
58 lines (52 loc) · 1.86 KB
/
app.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
const axios = require('axios');
const db = require('./db');
const security = require('./security');
const signingSecret = process.env.SLACK_SIGNING_SECRET;
const token = process.env.SLACK_BOT_TOKEN;
exports.handler = (event, context, callback) => {
if (security.validateSlackRequest(event, signingSecret)) {
const body = JSON.parse(event.body);
switch (body.type) {
case "url_verification": callback(null, body.challenge); break;
case "event_callback": processRequest(body, callback); break;
default: callback(null);
}
}
else callback("verification failed");
};
const processRequest = (body, callback) => {
switch (body.event.type) {
case "message": processMessages(body, callback); break;
case "app_mention": processAppMention(body, callback); break;
default: callback(null);
}
};
const processMessages = (body, callback) => {
console.debug("message:", body.event.text);
callback(null);
};
const processAppMention = (body, callback) => {
const item = body.event.text.split(":").pop().trim();
db.saveItem(item, (error, result) => {
if (error !== null) {
callback(error)
} else {
const message = {
channel: body.event.channel,
text: `Item: \`${item}\` is saved to *Amazon DynamoDB*!`
};
axios({
method: 'post',
url: 'https://slack.com/api/chat.postMessage',
headers: { 'Content-Type': 'application/json; charset=utf-8', 'Authorization': `Bearer ${token}` },
data: message
})
.then((response) => {
callback(null);
})
.catch((error) => {
callback("failed to process app_mention");
});
}
});
};