-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
255 lines (238 loc) · 8.42 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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
// 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 LocalStorage = require('node-localstorage').LocalStorage;
const SlackStrategy = require('@aoberoi/passport-slack').default.Strategy;
const http = require('http');
const express = require('express');
// *** Initialize event adapter using signing secret from environment variables ***
const slackEvents = slackEventsApi.createEventAdapter(process.env.SLACK_SIGNING_SECRET, {
includeBody: true,
});
// Initialize a Local Storage object to store authorization info
// NOTE: This is an insecure method and thus for demo purposes only!
const botAuthorizationStorage = new LocalStorage('./storage');
// 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] && botAuthorizationStorage.getItem(teamId)) {
clients[teamId] = new SlackClient(botAuthorizationStorage.getItem(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) => {
botAuthorizationStorage.setItem(team.id, extra.bot.accessToken);
done(null, {});
}));
// Initialize an Express application
const app = express();
// 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/[email protected] 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('/slack/events', slackEvents.expressMiddleware());
// *** Attach listeners to the event adapter ***
// *** Greeting any user that says "clean" ***
slackEvents.on('message', (message, body) => {
// Only deal with messages that have no subtype (plain messages) and contain 'hi'
if (!message.subtype && message.text.indexOf('clean') >= 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 the app through the url provided by ngrok?');
}
// Respond to the message back in the same channel
slack.chat.postMessage({ channel: message.channel, text: `I am too tired to clean <@${message.user}>! :tired_face:` })
.catch(console.error);
}
});
slackEvents.on('file_created', (message, body) => {
// Only deal with messages that have no subtype (plain messages) and contain 'hi'
if (message.type === 'file_created') {
console.log('file successfully created:', message);
// 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 the app through the url provided by ngrok?');
}
// Respond to the message back in the same channel
slack.chat.postMessage({ channel: message.channel, text: `I saved your file :file_folder: <@${message.user}>! :tada: :tada:` })
.catch(console.error);
}
});
// *** Greeting any user that says "```" ***
slackEvents.on('message', (message, body) => {
// Only deal with messages that have no subtype (plain messages) and contain 'hi'
if (!message.subtype && message.text.indexOf('```') >= 0) {
console.log('backtick message:', message);
// 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 the app through the url provided by ngrok?');
}
// Respond to the message back in the same channel
slack.chat.postMessage({ channel: message.channel, blocks: [
{
'type': 'section',
'text': {
'type': 'mrkdwn',
'text': 'I saw that you posted a code snippet!\n\n*Do you want to save it as a Gist on GitHub?*',
},
},
{
'type': 'actions',
'elements': [
{
'type': 'button',
'text': {
'type': 'plain_text',
'emoji': true,
'text': 'Yes',
},
'value': 'click_me_123',
'style': 'primary',
},
{
'type': 'button',
'text': {
'type': 'plain_text',
'emoji': true,
'text': 'No',
},
'value': 'click_me_123',
'style': 'danger',
},
],
},
{
'type': 'divider',
},
{
'type': 'section',
'text': {
'type': 'mrkdwn',
'text': '*Here is the information I will save for you...*',
},
},
{
'type': 'section',
'text': {
'type': 'mrkdwn',
'text': '*File name:*\nmy-amazing-gist\n\n*Author:*\n',
},
},
{
'type': 'actions',
'elements': [
{
'type': 'users_select',
'placeholder': {
'type': 'plain_text',
'text': 'Select a user',
'emoji': true,
},
},
],
},
{
'type': 'section',
'text': {
'type': 'mrkdwn',
'text': '*Choose a category*',
},
'accessory': {
'type': 'static_select',
'placeholder': {
'type': 'plain_text',
'text': 'Select a category',
'emoji': true,
},
'options': [
{
'text': {
'type': 'plain_text',
'text': 'Data Structures',
'emoji': true,
},
'value': 'value-0',
},
{
'text': {
'type': 'plain_text',
'text': 'Login Instructions',
'emoji': true,
},
'value': 'value-1',
},
{
'text': {
'type': 'plain_text',
'text': 'Random Stuff',
'emoji': true,
},
'value': 'value-2',
},
],
},
},
] })
.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 the app through the url provided by ngrok?');
}
// Respond to the reaction back with the same emoji
slack.chat.postMessage({ channel: event.item.channel, text: `:${event.reaction}:` })
.catch(console.error);
});
// *** Handle errors ***
slackEvents.on('error', (error) => {
if (error.code === slackEventsApi.errorCodes.TOKEN_VERIFICATION_FAILURE) {
// This error type also has a `body` propery containing the request body which failed verification.
console.error(`An unverified request was sent to the Slack events Request URL. Request body: \
${JSON.stringify(error.body)}`);
} else {
console.error(`An error occurred while handling a Slack event: ${error.message}`);
}
});
// Start the express application
const port = process.env.PORT || 3000;
http.createServer(app).listen(port, () => {
console.log(`server listening on port ${port}`);
});