This repository has been archived by the owner on Jul 24, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 37
/
index.js
105 lines (93 loc) · 3.91 KB
/
index.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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
// Load environment variables from `.env` file (optional)
require('dotenv').config();
const slackEventsApi = require('@slack/events-api');
const SlackClient = require('@slack/client').WebClient;
const passport = require('passport');
const SlackStrategy = require('@aoberoi/passport-slack').default.Strategy;
const http = require('http');
const express = require('express');
const bodyParser = require('body-parser');
// *** Initialize event adapter using verification token from environment variables ***
const slackEvents = slackEventsApi.createSlackEventAdapter(process.env.SLACK_VERIFICATION_TOKEN, {
includeBody: true
});
// Initialize a data structures to store team authorization info (typically stored in a database)
const botAuthorizations = {}
// Helpers to cache and lookup appropriate client
// NOTE: Not enterprise-ready. if the event was triggered inside a shared channel, this lookup
// could fail but there might be a suitable client from one of the other teams that is within that
// shared channel.
const clients = {};
function getClientByTeamId(teamId) {
if (!clients[teamId] && botAuthorizations[teamId]) {
clients[teamId] = new SlackClient(botAuthorizations[teamId]);
}
if (clients[teamId]) {
return clients[teamId];
}
return null;
}
// Initialize Add to Slack (OAuth) helpers
passport.use(new SlackStrategy({
clientID: process.env.SLACK_CLIENT_ID,
clientSecret: process.env.SLACK_CLIENT_SECRET,
skipUserProfile: true,
}, (accessToken, scopes, team, extra, profiles, done) => {
botAuthorizations[team.id] = extra.bot.accessToken;
done(null, {});
}));
// Initialize an Express application
const app = express();
app.use(bodyParser.json());
// Plug the Add to Slack (OAuth) helpers into the express app
app.use(passport.initialize());
app.get('/', (req, res) => {
res.send('<a href="/auth/slack"><img alt="Add to Slack" height="40" width="139" src="https://platform.slack-edge.com/img/add_to_slack.png" srcset="https://platform.slack-edge.com/img/add_to_slack.png 1x, https://platform.slack-edge.com/img/add_to_slack@2x.png 2x" /></a>');
});
app.get('/auth/slack', passport.authenticate('slack', {
scope: ['bot']
}));
app.get('/auth/slack/callback',
passport.authenticate('slack', { session: false }),
(req, res) => {
res.send('<p>Greet and React was successfully installed on your team.</p>');
},
(err, req, res, next) => {
res.status(500).send(`<p>Greet and React failed to install</p> <pre>${err}</pre>`);
}
);
// *** Plug the event adapter into the express app as middleware ***
app.use('/event', slackEvents.expressMiddleware());
// *** Attach listeners to the event adapter ***
// *** Greeting any user that says "hi" ***
slackEvents.on('message', (message, body) => {
// Only deal with messages that have no subtype (plain messages) and contain 'hi'
if (!message.subtype && message.text.indexOf('hi') >= 0) {
// Initialize a client
const slack = getClientByTeamId(body.team_id);
// Handle initialization failure
if (!slack) {
return console.error('No authorization found for this team. Did you install this app again after restarting?');
}
// Respond to the message back in the same channel
slack.chat.postMessage(message.channel, `Hello <@${message.user}>! :tada:`)
.catch(console.error);
}
});
// *** Responding to reactions with the same emoji ***
slackEvents.on('reaction_added', (event, body) => {
// Initialize a client
const slack = getClientByTeamId(body.team_id);
// Handle initialization failure
if (!slack) {
return console.error('No authorization found for this team. Did you install this app again after restarting?');
}
// Respond to the reaction back with the same emoji
slack.chat.postMessage(event.item.channel, `:${event.reaction}:`)
.catch(console.error);
});
// Start the express application
const port = process.env.PORT || 3000;
http.createServer(app).listen(port, () => {
console.log(`server listening on port ${port}`);
});