-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathslack.js
75 lines (63 loc) · 2.02 KB
/
slack.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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
const { WebClient } = require("@slack/client");
const rp = require("request-promise");
const fp = require("fastify-plugin");
const web = new WebClient();
const clientId = process.env.SLACK_CLIENT_ID;
const clientSecret = process.env.SLACK_CLIENT_SECRET;
class SlackClient {
constructor(fastify) {
this.fastify = fastify;
this.actionHandlers = [];
fastify.post("/slack/actions", (request, reply) => {
this.handleAction(request, reply);
});
}
handleAction(request, reply) {
let payload = JSON.parse(request.body["payload"]);
request.log.trace("Handling Slack Action payload ", payload);
this.actionHandlers.forEach(handler => handler(payload, request, reply));
}
addActionHandler(action) {
this.actionHandlers.push(action);
}
async getTokenForOauthCode(code) {
let oauthResult = await web.oauth.access({
client_id: clientId,
client_secret: clientSecret,
code: code,
});
if (oauthResult.ok) {
return oauthResult;
} else {
throw new Error(oauthResult.error);
}
}
callbacksForDelayedResponse(responseUrl) {
let formatted = async response => {
await rp.post(responseUrl, { json: true, body: response });
};
let text = async text => {
await rp.post(responseUrl, {
json: true,
body: {
text: text,
response_type: "ephemeral",
},
});
};
let error = async () => {
return await rp.post(responseUrl, {
json: true,
body: {
text: "Sorry an internal error has occurrred",
response_type: "ephemeral",
},
});
};
return { formatted, text, error };
}
}
module.exports = fp((fastify, opts, next) => {
fastify.decorate("Slack", new SlackClient(fastify));
next();
});