-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathapp.js
417 lines (359 loc) · 11.8 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
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
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
const { App } = require('@slack/bolt');
require('dotenv').config();
const { SecretManagerServiceClient } = require('@google-cloud/secret-manager')
async function accessSecretVersion (name) {
const client = new SecretManagerServiceClient()
const projectId = process.env.PROJECT_ID
const [version] = await client.accessSecretVersion({
name: `projects/${projectId}/secrets/${name}/versions/latest`
})
// Extract the payload as a string.
const payload = version.payload.data.toString('utf8')
return payload
}
(async () => {
// Initializes your app with your bot token and signing secret
const app = new App({
token: process.env.SLACK_BOT_TOKEN || await accessSecretVersion('SLACK_BOT_TOKEN'),
signingSecret: process.env.SLACK_SIGNING_SECRET || await accessSecretVersion('SLACK_SIGNING_SECRET'),
socketMode: false,
appToken: process.env.SLACK_APP_TOKEN || await accessSecretVersion('SLACK_APP_TOKEN'),
});
//create Home tab view
app.event('app_home_opened', async ({ event, client, context }) => {
try {
/* view.publish is the method that your app uses to push a view to the Home tab */
const result = await client.views.publish({
/* the user that opened your app's app home */
user_id: event.user,
/* the view object that appears in the app home*/
view: {
type: 'home',
callback_id: 'home_view',
/* body of the view */
blocks: [
{
"type": "section",
"text": {
"type": "mrkdwn",
"text": "*See list of commands below* :tada:"
}
},
{
"type": "divider"
},
{
"type": "section",
"text": {
"type": "mrkdwn",
"text": "*Available commands:*\n*/postallchannels:* post a message to all channels this bot is a member of."
}
}
]
}
});
}
catch (error) {
console.error(error);
}
});
// Listen for a slash command invocation
app.command('/postallchannels', async ({ ack, body, client, logger }) => {
// Acknowledge the command request
await ack();
// check if userid exists in admin channel, if not, decline request
const user = body.user_id;
const adminList = await getAdminMembers();
//check if user is in admin channel before posting
if (adminList.includes(user)) { console.log("cool, you're an admin") }
else {
console.log("sorry, you're not an admin")
return;
}
try {
// Call views.open with the built-in client
const result = await client.views.open({
// Pass a valid trigger_id within 3 seconds of receiving it
trigger_id: body.trigger_id,
// View payload
view: {
type: 'modal',
// View identifier
callback_id: 'post_all_channels',
title: {
type: 'plain_text',
text: 'Post to all channels'
},
blocks: [
{
type: 'section',
text: {
type: 'mrkdwn',
text: 'Submitting this modal will post your message to all channels the bot is a member of.'
}
},
{
type: 'input',
block_id: 'block_1',
label: {
type: 'plain_text',
text: 'What is your message?'
},
element: {
type: 'plain_text_input',
action_id: 'post_message',
multiline: true
}
}
],
submit: {
type: 'plain_text',
text: 'Submit'
}
}
});
logger.info(result);
}
catch (error) {
logger.error(error);
}
});
// Handle view_submission request for when someone submits modal 'post_all_channels'
app.view('post_all_channels', async ({ ack, body, view, client, logger }) => {
// Acknowledge the view_submission request
await ack();
// Do whatever you want with the input data
// Assume there's an input block with `block_1` as the block_id and `post_message` action_id
const val = view['state']['values']['block_1']['post_message'];
const user = body['user']['id'];
// if user isn't in admin channel then decline submission
postMessageToChannels(val.value);
// Message to send user
let msg = '';
msg = `I posted your message: \n` + val.value;
// Message the user
try {
await client.chat.postMessage({
channel: user,
type:"mrkdwn",
text: msg,
unfurl_links: false,
unfurl_media: false
});
}
catch (error) {
logger.error(error);
}
});
// Listen for a slash command invocation
app.command('/testpost', async ({ ack, body, client, logger }) => {
// Acknowledge the command request
await ack();
// check if userid exists in admin channel, if not, decline request
const user = body.user_id;
const adminList = await getAdminMembers();
//check if user is in admin channel before posting
if (adminList.includes(user)) { console.log("cool, you're an admin") }
else {
console.log("sorry, you're not an admin")
return;
}
try {
// Call views.open with the built-in client
const result = await client.views.open({
// Pass a valid trigger_id within 3 seconds of receiving it
trigger_id: body.trigger_id,
// View payload
view: {
type: 'modal',
// View identifier
callback_id: 'test_post',
title: {
type: 'plain_text',
text: 'Post to all bot_admins'
},
blocks: [
{
type: 'section',
text: {
type: 'mrkdwn',
text: 'Submitting this modal will post your message to all channels the bot is a member of.'
}
},
{
type: 'input',
block_id: 'block_1',
label: {
type: 'plain_text',
text: 'What is your message?'
},
element: {
type: 'plain_text_input',
action_id: 'post_message',
multiline: true
}
}
],
submit: {
type: 'plain_text',
text: 'Submit'
}
}
});
logger.info(result);
}
catch (error) {
logger.error(error);
}
});
// Handle view_submission request for when someone submits modal 'post_all_channels'
app.view('test_post', async ({ ack, body, view, client, logger }) => {
// Acknowledge the view_submission request
await ack();
// Do whatever you want with the input data
// Assume there's an input block with `block_1` as the block_id and `post_message` action_id
const val = view['state']['values']['block_1']['post_message'];
const user = body['user']['id'];
// Message to send user
let msg = '';
msg = `This is a test post: \n` + val.value;
// Message the user
try {
await client.chat.postMessage({
channel: "bot_admins",
type:"mrkdwn",
text: msg,
unfurl_links: false,
unfurl_media: false
});
}
catch (error) {
logger.error(error);
}
});
app.command('/getallchannels', async ({ ack, body, client, logger }) => {
// Acknowledge the command request
await ack();
// check if userid exists in admin channel, if not, decline request
const user = body.user_id;
const adminList = await getAdminMembers();
//check if user is in admin channel before posting
if (adminList.includes(user)) { console.log("cool, you're an admin") }
else {
console.log("sorry, you're not an admin")
return;
}
try {
const allChannelNames = await findAllChannelNames()
let channelNamesList = ''
for (const channel of allChannelNames) {
channelNamesList = channelNamesList.concat(channel,', ')
}
// Message the user (bot user in this case)
await client.chat.postMessage({
channel: user,
text: channelNamesList
});
}
catch (error) {
logger.error(error);
}
});
// Find all channel IDs the bot is a member of (channel names can change, but IDs should remain the same)
async function findChannels() {
const channelIds = [];
try {
// Call the conversations.list method using the built-in WebClient
const result = await app.client.users.conversations({
// The token you used to initialize your app
token: process.env.SLACK_BOT_TOKEN,
types: "public_channel,private_channel"
});
//generate list of channelIds
for (const channel of result.channels) {
channelIds.push(channel.id);
}
}
catch (error) {
console.error(error);
}
return channelIds;
}
// Find all channel names the bot is a member of (channel names can change, but IDs should remain the same)
async function findAllChannelNames() {
const channelNames = [];
try {
// Call the conversations.list method using the built-in WebClient
const result = await app.client.users.conversations({
// The token you used to initialize your app
token: process.env.SLACK_BOT_TOKEN,
types: "public_channel,private_channel"
});
//generate list of channelNames
for (const channel of result.channels) {
channelNames.push(channel.name);
}
}
catch (error) {
console.error(error);
}
return channelNames;
}
// Post a message to a channel your app is in using ID and message text
async function publishMessage(id, text) {
try {
// Call the chat.postMessage method using the built-in WebClient
const result = await app.client.chat.postMessage({
// The token you used to initialize your app
token: process.env.SLACK_BOT_TOKEN,
channel: id,
reply_broadcast: true,
type:"mrkdwn",
text: text,
unfurl_links: false,
unfurl_media: false
// You could also use a blocks[] array to send richer content
});
// Print result, which includes information about the message (like TS)
// console.log(result);
}
catch (error) {
console.error(error);
}
}
async function getAdminMembers() {
try {
// Call the conversations.list method using the WebClient
const result = await app.client.conversations.list({
types: "private_channel",
limit: "9999"
});
const channels = result.channels;
//get adminChannel object
const adminChannel = channels.find( el => el.name === 'bot_admins')
console.log("adminChannel", adminChannel)
//get all member ids in adminChannel
const adminMembers = await app.client.conversations.members({
channel: adminChannel.id,
})
const adminMemberList = adminMembers.members;
return adminMemberList;
}
catch (error) {
console.error(error);
}
}
// Get channels bot is member of, then send a message to all channels
async function postMessageToChannels(message) {
(async () => {
return await findChannels()
})().then(channelIds => {
channelIds.map(id => {
publishMessage(id, message);
})
})
}
// Start your app
await app.start(process.env.PORT || '8080');
console.log('⚡️ Bolt app is running!');
})();