forked from slackapi/template-triage-bot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
312 lines (275 loc) · 10.5 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
// =============================
// === External dependencies ===
// =============================
// Official Slack packages: Bolt for Javascript & OAuth helpers
const { App } = require("@slack/bolt");
// Our `helpers/db.js` file defines our database connection (powered by Mongoose)
const { AuthedTeam } = require("./helpers/db");
// We'll use the randomstring package to generate, well, random strings for our state store
const { generate: randomStringGenerator } = require("randomstring");
// =====================================
// === Internal dependencies/helpers ===
// =====================================
const triageConfig = require("./config");
const modalViews = require("./views/modals.blockkit");
const appHomeView = require("./views/app_home.blockkit");
const {
getAllMessagesForPastHours,
filterAndEnrichMessages,
messagesToCsv,
} = require("./helpers/messages");
const {
scheduleReminders,
manuallyTriggerScheduledJobs,
} = require("./helpers/scheduled_jobs");
// ====================================
// === Initialization/Configuration ===
// ====================================
// Initialize the Bolt app, including OAuth installer helpers
// (refer to https://github.com/slackapi/bolt)
const app = new App({
signingSecret: process.env.SLACK_SIGNING_SECRET,
clientId: process.env.SLACK_CLIENT_ID,
clientSecret: process.env.SLACK_CLIENT_SECRET,
stateSecret: randomStringGenerator(),
scopes: process.env.SLACK_BOT_SCOPES,
installerOptions: {
authVersion: "v2",
installPath: "/slack/install",
redirectUriPath: "/slack/oauth_redirect",
callbackOptions: {
success: (installation, metadata, req, res) => {
res.writeHead(200, { "Content-Type": "text/html; charset=utf-8" });
res.end(
`Thank you for installing! <a href='slack://app?team=${installation.team.id}&id=${installation.appId}&tab=home'>Click here to visit the app in Slack!</a>`
);
},
failure: (error, installOptions, req, res) => {
console.error(error, installOptions);
res.writeHead(200, { "Content-Type": "text/html; charset=utf-8" });
res.end(
"Uh oh, there was an error while installing. Sorry about that. <a href='/slack/install'>Please try again.</a>"
);
},
},
},
installationStore: {
storeInstallation: async (installation) => {
if (
installation.isEnterpriseInstall &&
installation.enterprise !== undefined
) {
// This is an org level install
throw new Error(
"This app does not currently support Org Level installation"
);
}
if (installation.team !== undefined) {
// single team install
// Create a teamData object with all the `installation` data but with id and name at the top level
let teamData = installation.team;
teamData = Object.assign(teamData, installation);
delete teamData.team; // we already have this information from the assign above
delete teamData.user.token; // we dont want a user token, if the scopes are requested
// Do an upsert so that we always have just one document per team ID
await AuthedTeam.findOneAndUpdate({ id: teamData.id }, teamData, {
upsert: true,
});
return true;
}
throw new Error("Failed saving installation data");
},
fetchInstallation: async (installQuery) => {
if (
installQuery.isEnterpriseInstall &&
installQuery.enterpriseId !== undefined
) {
// This is an org level install
throw new Error(
"This app does not currently support Org Level installation"
);
}
if (installQuery.teamId !== undefined) {
const team = await AuthedTeam.findOne({ id: installQuery.teamId });
return team._doc;
}
throw new Error("Failed to fetch installation data");
},
},
logLevel: "DEBUG",
});
// =========================================================================
// === Define Slack (Bolt) handlers for Slack functionality/interactions ===
// =========================================================================
// Handle the shortcut we configured in the Slack App Config
app.shortcut("triage_stats", async ({ ack, context, body }) => {
// Acknowledge right away
await ack();
// Open a modal
await app.client.views.open({
token: context.botToken,
trigger_id: body.trigger_id,
view: modalViews.select_triage_channel,
});
});
// Handle `view_submision` of modal we opened as a result of the `triage_stats` shortcut
app.view(
"channel_selected",
async ({ body, view, ack, client, logger, context }) => {
// Acknowledge right away
await ack();
const submittedByUserId = body.user.id;
const selectedChannelId =
view.state.values.channel.channel.selected_conversation;
const nHoursToGoBack =
parseInt(view.state.values.n_hours.n_hours.selected_option.value) || 7;
try {
// Get converstion info; this will throw an error if the bot does not have access to it
const conversationInfo = await client.conversations.info({
channel: selectedChannelId,
include_num_members: true,
});
// Join the conversation (necessary for reading its history)
await client.conversations.join({
channel: selectedChannelId,
});
// Let the user know, in a DM from the bot, that we're working on their request
const msgWorkingOnIt = await client.chat.postMessage({
channel: submittedByUserId,
text:
`*You asked for triage stats for <#${selectedChannelId}>*.\n` +
`I'll work on the stats for the past ${nHoursToGoBack} hours right away!`,
});
// Thread a message while we get to work on the analysis
await client.chat.postMessage({
channel: msgWorkingOnIt.channel,
thread_ts: msgWorkingOnIt.ts,
text: `A number for you while you wait.. the channel has ${conversationInfo.channel.num_members} members (including apps) currently`,
});
// Get all messages from the beginning of time (probably not a good idea)
const allMessages = await getAllMessagesForPastHours(
selectedChannelId,
nHoursToGoBack,
client
);
// Use a helper method to enrich the messages we have
const allMessagesEnriched = filterAndEnrichMessages(
allMessages,
selectedChannelId,
context.botId
);
// For each level, let's do some analysis!
const levelDetailBlocks = [];
for (const i in triageConfig._.levels) {
const level = triageConfig._.levels[i];
const allMessagesForLevel = allMessagesEnriched.filter(
(m) => m[`_level_${level}`] === true
);
// Formulate strings for each status
const countsStrings = triageConfig._.statuses.map((status) => {
const messagesForLevelAndStatus = allMessagesForLevel.filter(
(m) => m[`_status_${status}`] === true
);
return `\tMessages ${status} ${triageConfig._.statusToEmoji[status]}: ${messagesForLevelAndStatus.length}`;
});
// Add level block to array
levelDetailBlocks.push({
type: "section",
text: {
type: "mrkdwn",
text: `${triageConfig._.levelToEmoji[level]} *${level}* (${
allMessagesForLevel.length
} total)\n${countsStrings.join("\n")}`,
},
});
}
// Send a single message to the thread with all of the stats by level
await client.chat.postMessage({
channel: msgWorkingOnIt.channel,
thread_ts: msgWorkingOnIt.ts,
blocks: [
{
type: "section",
text: {
type: "mrkdwn",
text: "Here's a summary of the messages needing attention by urgency level and status:",
},
},
].concat(levelDetailBlocks),
});
// Try to parse our object to CSV and upload it as an attachment
try {
// Convert object to CSV
const csvString = messagesToCsv(allMessagesEnriched);
// Upload CSV File
await client.files.upload({
channels: msgWorkingOnIt.channel,
content: csvString,
title: `All messages from the past ${nHoursToGoBack} hours`,
filename: "allMessages.csv",
filetype: "csv",
thread_ts: msgWorkingOnIt.ts,
});
} catch (err) {
logger.error(err);
}
} catch (e) {
// Log error to console
logger.error(e);
// Send error message to DM with the initiating user
const msgError = await client.chat.postMessage({
channel: submittedByUserId,
text: ":warning: Sorry but something went wrong.",
});
// Add details for later debugging in thread
await client.chat.postMessage({
channel: submittedByUserId,
thread_ts: msgError.ts,
text: `Debug info:\n• selectedChannelId=${selectedChannelId}\n• submittedByUserId=${submittedByUserId}\n • nHoursToGoBack=${nHoursToGoBack}`,
});
// Add full error message in thread
await client.chat.postMessage({
channel: submittedByUserId,
thread_ts: msgError.ts,
text: `\`\`\`${JSON.stringify(e)}\`\`\``,
});
}
}
);
app.event("app_home_opened", async ({ payload, context, logger }) => {
const userId = payload.user;
try {
// Call the views.publish method using the built-in WebClient
await app.client.views.publish({
// The token you used to initialize your app is stored in the `context` object
token: context.botToken,
user_id: userId,
view: appHomeView(userId, triageConfig),
});
} catch (error) {
logger.error(error);
}
});
// Handle the shortcut for triggering manually scheduled jobs;
// this should only be used for debugging (so we dont have to wait until a triggered job would normally fire)
app.shortcut(
"debug_manually_trigger_scheduled_jobs",
async ({ ack, context, body }) => {
// Acknowledge right away
await ack();
// Execute helper function to manually trigger the scheduled jobs
manuallyTriggerScheduledJobs();
}
);
// Handle Bolt errors
app.error((error) => {
// Check the details of the error to handle cases where you should retry sending a message or stop the app
console.error(error);
});
(async () => {
// Schedule our dynamic cron jobs
scheduleReminders();
// Actually start thhe Bolt app. Let's go!
await app.start(process.env.PORT || 3000);
console.log("⚡️ Bolt app is running!");
})();