@terreno/api 57.10.1 → 57.12.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +1 -0
- package/dist/api.js +21 -4
- package/dist/index.d.ts +1 -0
- package/dist/index.js +1 -0
- package/dist/notifiers/slackWebApi.d.ts +83 -0
- package/dist/notifiers/slackWebApi.js +453 -0
- package/package.json +3 -3
- package/src/api.query.test.ts +15 -4
- package/src/api.ts +33 -4
- package/src/index.ts +1 -0
- package/src/notifiers/slackWebApi.test.ts +357 -0
- package/src/notifiers/slackWebApi.ts +567 -0
|
@@ -0,0 +1,567 @@
|
|
|
1
|
+
import * as Sentry from "@sentry/bun";
|
|
2
|
+
import axios, {type AxiosResponse, isAxiosError} from "axios";
|
|
3
|
+
|
|
4
|
+
import {APIError, errorMessage, isAPIError} from "../errors";
|
|
5
|
+
import {logger} from "../logger";
|
|
6
|
+
import {normalizeSlackUserId} from "./slackNotifier";
|
|
7
|
+
|
|
8
|
+
const SLACK_API_URL = "https://slack.com/api";
|
|
9
|
+
const MAX_ATTEMPTS = 3;
|
|
10
|
+
const MAX_CHANNEL_PAGES = 25;
|
|
11
|
+
const INVITE_BATCH_SIZE = 1000;
|
|
12
|
+
const CHANNEL_NAME_PATTERN = /^[a-z0-9_-]{1,80}$/;
|
|
13
|
+
const CHANNEL_ID_PATTERN = /^[CG][A-Z0-9]{8,}$/;
|
|
14
|
+
|
|
15
|
+
const FATAL_INVITE_ERRORS = new Set([
|
|
16
|
+
"cant_invite",
|
|
17
|
+
"channel_not_found",
|
|
18
|
+
"invalid_auth",
|
|
19
|
+
"is_archived",
|
|
20
|
+
"missing_scope",
|
|
21
|
+
"no_permission",
|
|
22
|
+
"not_authed",
|
|
23
|
+
"not_in_channel",
|
|
24
|
+
"token_revoked",
|
|
25
|
+
]);
|
|
26
|
+
|
|
27
|
+
interface SlackApiResponse {
|
|
28
|
+
ok?: boolean;
|
|
29
|
+
error?: string;
|
|
30
|
+
errors?: {user?: string; error?: string}[];
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
interface SlackChannelObject {
|
|
34
|
+
id?: string;
|
|
35
|
+
name?: string;
|
|
36
|
+
name_normalized?: string;
|
|
37
|
+
is_private?: boolean;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
interface SlackChannelResponse extends SlackApiResponse {
|
|
41
|
+
channel?: SlackChannelObject;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
interface SlackMessageResponse extends SlackApiResponse {
|
|
45
|
+
ts?: string;
|
|
46
|
+
channel?: string;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
interface SlackListResponse extends SlackApiResponse {
|
|
50
|
+
channels?: SlackChannelObject[];
|
|
51
|
+
response_metadata?: {next_cursor?: string};
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
export interface SlackInviteFailure {
|
|
55
|
+
userId: string;
|
|
56
|
+
error: string;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
export interface SlackInviteResult {
|
|
60
|
+
invitedUserIds: string[];
|
|
61
|
+
alreadyMemberUserIds: string[];
|
|
62
|
+
failures: SlackInviteFailure[];
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
export interface SlackChannelRef {
|
|
66
|
+
channelId: string;
|
|
67
|
+
name: string;
|
|
68
|
+
isPrivate: boolean;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
export interface CreateSlackPrivateChannelOptions {
|
|
72
|
+
/** Slack channel name: lowercase letters, numbers, hyphens, underscores, max 80. */
|
|
73
|
+
name: string;
|
|
74
|
+
/** Slack member IDs to invite. The bot is already a member because it creates the channel. */
|
|
75
|
+
userIds?: string[];
|
|
76
|
+
initialMessage?: string;
|
|
77
|
+
/** Member IDs to @-mention in `initialMessage`. */
|
|
78
|
+
mentionUserIds?: string[];
|
|
79
|
+
/** Defaults to `SLACK_BOT_TOKEN`. One workspace token for every Terreno app. */
|
|
80
|
+
token?: string;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
export interface SlackPrivateChannelResult {
|
|
84
|
+
channelId: string;
|
|
85
|
+
name: string;
|
|
86
|
+
invites: SlackInviteResult;
|
|
87
|
+
messageTs?: string;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
export interface InviteSlackUsersOptions {
|
|
91
|
+
channelId: string;
|
|
92
|
+
userIds: string[];
|
|
93
|
+
token?: string;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
export interface PostSlackMessageOptions {
|
|
97
|
+
channelId: string;
|
|
98
|
+
text: string;
|
|
99
|
+
blocks?: Record<string, unknown>[];
|
|
100
|
+
mentionUserIds?: string[];
|
|
101
|
+
token?: string;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
export interface PostSlackMessageResult {
|
|
105
|
+
channelId: string;
|
|
106
|
+
messageTs: string;
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
export interface FindSlackChannelOptions {
|
|
110
|
+
name: string;
|
|
111
|
+
token?: string;
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/**
|
|
115
|
+
* Slack channel names are lowercase letters, numbers, hyphens, and underscores,
|
|
116
|
+
* at most 80 characters. Leading and trailing whitespace is removed and the
|
|
117
|
+
* value is lowercased. Any other character is rejected.
|
|
118
|
+
*/
|
|
119
|
+
export const normalizeSlackChannelName = (name: string): string => {
|
|
120
|
+
const normalized = name.trim().toLowerCase();
|
|
121
|
+
const punctuationOnly = /^[_-]+$/u.test(normalized);
|
|
122
|
+
if (!CHANNEL_NAME_PATTERN.test(normalized) || punctuationOnly) {
|
|
123
|
+
throw new APIError({
|
|
124
|
+
code: "slack-channel-name-invalid",
|
|
125
|
+
detail: "Use 1-80 characters: lowercase letters, numbers, hyphens, and underscores.",
|
|
126
|
+
status: 400,
|
|
127
|
+
title: "Invalid Slack channel name",
|
|
128
|
+
});
|
|
129
|
+
}
|
|
130
|
+
return normalized;
|
|
131
|
+
};
|
|
132
|
+
|
|
133
|
+
const requireSlackToken = (token: string | undefined): string => {
|
|
134
|
+
const botToken = token ?? process.env.SLACK_BOT_TOKEN;
|
|
135
|
+
if (!botToken) {
|
|
136
|
+
throw new APIError({
|
|
137
|
+
code: "slack-token-missing",
|
|
138
|
+
status: 500,
|
|
139
|
+
title: "SLACK_BOT_TOKEN is not set",
|
|
140
|
+
});
|
|
141
|
+
}
|
|
142
|
+
return botToken;
|
|
143
|
+
};
|
|
144
|
+
|
|
145
|
+
const requireChannelId = (channelId: string): string => {
|
|
146
|
+
const normalized = channelId.trim().toUpperCase();
|
|
147
|
+
if (!CHANNEL_ID_PATTERN.test(normalized)) {
|
|
148
|
+
throw new APIError({
|
|
149
|
+
code: "slack-channel-id-invalid",
|
|
150
|
+
detail: channelId,
|
|
151
|
+
status: 400,
|
|
152
|
+
title: "Invalid Slack channel id",
|
|
153
|
+
});
|
|
154
|
+
}
|
|
155
|
+
return normalized;
|
|
156
|
+
};
|
|
157
|
+
|
|
158
|
+
const partitionUserIds = (
|
|
159
|
+
userIds: string[]
|
|
160
|
+
): {validUserIds: string[]; invalidUserIds: string[]} => {
|
|
161
|
+
const validUserIds: string[] = [];
|
|
162
|
+
const invalidUserIds: string[] = [];
|
|
163
|
+
const seen = new Set<string>();
|
|
164
|
+
for (const rawId of userIds) {
|
|
165
|
+
const id = normalizeSlackUserId(rawId);
|
|
166
|
+
if (!id) {
|
|
167
|
+
if (rawId.trim()) {
|
|
168
|
+
invalidUserIds.push(rawId);
|
|
169
|
+
}
|
|
170
|
+
continue;
|
|
171
|
+
}
|
|
172
|
+
if (seen.has(id)) {
|
|
173
|
+
continue;
|
|
174
|
+
}
|
|
175
|
+
seen.add(id);
|
|
176
|
+
validUserIds.push(id);
|
|
177
|
+
}
|
|
178
|
+
return {invalidUserIds, validUserIds};
|
|
179
|
+
};
|
|
180
|
+
|
|
181
|
+
const retryAfterMs = (headers: AxiosResponse["headers"] | undefined): number => {
|
|
182
|
+
const retryAfterHeader = "retry-after";
|
|
183
|
+
const raw =
|
|
184
|
+
headers && typeof headers.get === "function"
|
|
185
|
+
? headers.get(retryAfterHeader)
|
|
186
|
+
: (headers as Record<string, unknown> | undefined)?.[retryAfterHeader];
|
|
187
|
+
const seconds = Number(raw);
|
|
188
|
+
if (!Number.isFinite(seconds) || seconds < 0) {
|
|
189
|
+
return 1000;
|
|
190
|
+
}
|
|
191
|
+
return Math.min(seconds * 1000, 2000);
|
|
192
|
+
};
|
|
193
|
+
|
|
194
|
+
const delay = async (ms: number): Promise<void> => {
|
|
195
|
+
if (ms <= 0) {
|
|
196
|
+
return;
|
|
197
|
+
}
|
|
198
|
+
await new Promise((resolve) => {
|
|
199
|
+
setTimeout(resolve, ms);
|
|
200
|
+
});
|
|
201
|
+
};
|
|
202
|
+
|
|
203
|
+
const slackErrorCode = (data: SlackApiResponse | undefined): string =>
|
|
204
|
+
data?.error ?? "unknown_error";
|
|
205
|
+
|
|
206
|
+
const throwSlackApiError = (method: string, data: SlackApiResponse | undefined): never => {
|
|
207
|
+
const slackError = slackErrorCode(data);
|
|
208
|
+
logger.warn("Slack Web API returned an error", {method, slackError});
|
|
209
|
+
const status = slackError === "name_taken" ? 409 : 502;
|
|
210
|
+
const title =
|
|
211
|
+
slackError === "name_taken"
|
|
212
|
+
? "Slack channel name is already taken"
|
|
213
|
+
: "Slack API request failed";
|
|
214
|
+
throw new APIError({
|
|
215
|
+
code: `slack-${slackError.replaceAll("_", "-")}`,
|
|
216
|
+
detail: `${method}: ${slackError}`,
|
|
217
|
+
status,
|
|
218
|
+
title,
|
|
219
|
+
});
|
|
220
|
+
};
|
|
221
|
+
|
|
222
|
+
const isRateLimited = (error: unknown, data?: SlackApiResponse): boolean => {
|
|
223
|
+
if (data?.error === "ratelimited") {
|
|
224
|
+
return true;
|
|
225
|
+
}
|
|
226
|
+
return isAxiosError(error) && error.response?.status === 429;
|
|
227
|
+
};
|
|
228
|
+
|
|
229
|
+
const callSlackApi = async <T extends SlackApiResponse>({
|
|
230
|
+
method,
|
|
231
|
+
body,
|
|
232
|
+
params,
|
|
233
|
+
token,
|
|
234
|
+
acceptApplicationError = false,
|
|
235
|
+
}: {
|
|
236
|
+
method: string;
|
|
237
|
+
body?: Record<string, unknown>;
|
|
238
|
+
params?: Record<string, string | number | boolean>;
|
|
239
|
+
token?: string;
|
|
240
|
+
/** Return an `ok: false` body so the caller can classify per-user invite errors. */
|
|
241
|
+
acceptApplicationError?: boolean;
|
|
242
|
+
}): Promise<T> => {
|
|
243
|
+
const botToken = requireSlackToken(token);
|
|
244
|
+
const headers = {Authorization: `Bearer ${botToken}`};
|
|
245
|
+
let lastTransportError: unknown;
|
|
246
|
+
|
|
247
|
+
for (let attempt = 1; attempt <= MAX_ATTEMPTS; attempt++) {
|
|
248
|
+
try {
|
|
249
|
+
const response = body
|
|
250
|
+
? await axios.post<T>(`${SLACK_API_URL}/${method}`, body, {headers})
|
|
251
|
+
: await axios.get<T>(`${SLACK_API_URL}/${method}`, {headers, params});
|
|
252
|
+
const data = response.data;
|
|
253
|
+
if (!data) {
|
|
254
|
+
throwSlackApiError(method, undefined);
|
|
255
|
+
}
|
|
256
|
+
if (data?.error === "ratelimited" && attempt < MAX_ATTEMPTS) {
|
|
257
|
+
await delay(retryAfterMs(response.headers));
|
|
258
|
+
continue;
|
|
259
|
+
}
|
|
260
|
+
if (data?.ok || acceptApplicationError) {
|
|
261
|
+
return data;
|
|
262
|
+
}
|
|
263
|
+
throwSlackApiError(method, data);
|
|
264
|
+
} catch (error: unknown) {
|
|
265
|
+
if (isAPIError(error)) {
|
|
266
|
+
throw error;
|
|
267
|
+
}
|
|
268
|
+
if (isRateLimited(error) && attempt < MAX_ATTEMPTS) {
|
|
269
|
+
const response = isAxiosError(error) ? error.response : undefined;
|
|
270
|
+
await delay(retryAfterMs(response?.headers));
|
|
271
|
+
continue;
|
|
272
|
+
}
|
|
273
|
+
lastTransportError = error;
|
|
274
|
+
break;
|
|
275
|
+
}
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
const message = errorMessage(lastTransportError);
|
|
279
|
+
logger.error("Slack Web API transport failed", {message, method});
|
|
280
|
+
Sentry.captureException(lastTransportError);
|
|
281
|
+
throw new APIError({
|
|
282
|
+
code: "slack-transport-failed",
|
|
283
|
+
detail: `${method}: ${message}`,
|
|
284
|
+
status: 502,
|
|
285
|
+
title: "Slack API request failed",
|
|
286
|
+
});
|
|
287
|
+
};
|
|
288
|
+
|
|
289
|
+
const mentionPrefix = (mentionUserIds: string[] | undefined): string => {
|
|
290
|
+
const {validUserIds, invalidUserIds} = partitionUserIds(mentionUserIds ?? []);
|
|
291
|
+
for (const value of invalidUserIds) {
|
|
292
|
+
logger.warn("Skipping Slack mention; value is not a Slack member id", {value});
|
|
293
|
+
}
|
|
294
|
+
return validUserIds.map((id) => `<@${id}>`).join(" ");
|
|
295
|
+
};
|
|
296
|
+
|
|
297
|
+
const inviteBatches = async (
|
|
298
|
+
channelId: string,
|
|
299
|
+
userIds: string[],
|
|
300
|
+
token: string | undefined
|
|
301
|
+
): Promise<SlackInviteResult> => {
|
|
302
|
+
const invitedUserIds: string[] = [];
|
|
303
|
+
const alreadyMemberUserIds: string[] = [];
|
|
304
|
+
const failures: SlackInviteFailure[] = [];
|
|
305
|
+
|
|
306
|
+
for (let index = 0; index < userIds.length; index += INVITE_BATCH_SIZE) {
|
|
307
|
+
const batch = userIds.slice(index, index + INVITE_BATCH_SIZE);
|
|
308
|
+
const data = await callSlackApi<SlackChannelResponse>({
|
|
309
|
+
acceptApplicationError: true,
|
|
310
|
+
body: {channel: channelId, force: true, users: batch.join(",")},
|
|
311
|
+
method: "conversations.invite",
|
|
312
|
+
token,
|
|
313
|
+
});
|
|
314
|
+
const topLevelError = data.error ?? "";
|
|
315
|
+
if (!data.ok && FATAL_INVITE_ERRORS.has(topLevelError) && !data.errors?.length) {
|
|
316
|
+
throwSlackApiError("conversations.invite", data);
|
|
317
|
+
}
|
|
318
|
+
if (!data.ok && topLevelError === "already_in_channel" && !data.errors?.length) {
|
|
319
|
+
alreadyMemberUserIds.push(...batch);
|
|
320
|
+
continue;
|
|
321
|
+
}
|
|
322
|
+
if (!data.ok && !data.errors?.length) {
|
|
323
|
+
throwSlackApiError("conversations.invite", data);
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
if (!data.errors?.length) {
|
|
327
|
+
invitedUserIds.push(...batch);
|
|
328
|
+
continue;
|
|
329
|
+
}
|
|
330
|
+
|
|
331
|
+
const accounted = new Set<string>();
|
|
332
|
+
for (const entry of data.errors) {
|
|
333
|
+
const userId = entry.user ? normalizeSlackUserId(entry.user) : undefined;
|
|
334
|
+
if (!userId) {
|
|
335
|
+
continue;
|
|
336
|
+
}
|
|
337
|
+
accounted.add(userId);
|
|
338
|
+
if (entry.error === "already_in_channel") {
|
|
339
|
+
alreadyMemberUserIds.push(userId);
|
|
340
|
+
} else {
|
|
341
|
+
failures.push({error: entry.error ?? "unknown_error", userId});
|
|
342
|
+
}
|
|
343
|
+
}
|
|
344
|
+
if (data.ok) {
|
|
345
|
+
invitedUserIds.push(...batch.filter((id) => !accounted.has(id)));
|
|
346
|
+
}
|
|
347
|
+
}
|
|
348
|
+
|
|
349
|
+
return {alreadyMemberUserIds, failures, invitedUserIds};
|
|
350
|
+
};
|
|
351
|
+
|
|
352
|
+
/**
|
|
353
|
+
* Create a private channel in the workspace for `SLACK_BOT_TOKEN`, invite
|
|
354
|
+
* members, and optionally post the first message.
|
|
355
|
+
*
|
|
356
|
+
* Requires bot scopes `groups:write`, `groups:write.invites`, and `chat:write`.
|
|
357
|
+
* `name_taken` throws a 409. Call `findSlackChannelByName` to reuse a channel
|
|
358
|
+
* the bot can already see.
|
|
359
|
+
*/
|
|
360
|
+
export const createSlackPrivateChannel = async ({
|
|
361
|
+
name,
|
|
362
|
+
userIds = [],
|
|
363
|
+
initialMessage,
|
|
364
|
+
mentionUserIds,
|
|
365
|
+
token,
|
|
366
|
+
}: CreateSlackPrivateChannelOptions): Promise<SlackPrivateChannelResult> => {
|
|
367
|
+
const channelName = normalizeSlackChannelName(name);
|
|
368
|
+
const {validUserIds, invalidUserIds} = partitionUserIds(userIds);
|
|
369
|
+
if (userIds.length > 0 && validUserIds.length === 0) {
|
|
370
|
+
throw new APIError({
|
|
371
|
+
code: "slack-user-id-invalid",
|
|
372
|
+
status: 400,
|
|
373
|
+
title: "Slack invite requires member ids",
|
|
374
|
+
});
|
|
375
|
+
}
|
|
376
|
+
for (const value of invalidUserIds) {
|
|
377
|
+
logger.warn("Skipping Slack invite; value is not a Slack member id", {value});
|
|
378
|
+
}
|
|
379
|
+
|
|
380
|
+
const created = await callSlackApi<SlackChannelResponse>({
|
|
381
|
+
body: {is_private: true, name: channelName},
|
|
382
|
+
method: "conversations.create",
|
|
383
|
+
token,
|
|
384
|
+
});
|
|
385
|
+
const channelId = created.channel?.id?.toUpperCase();
|
|
386
|
+
if (!channelId) {
|
|
387
|
+
throw new APIError({
|
|
388
|
+
code: "slack-channel-missing",
|
|
389
|
+
detail: "conversations.create",
|
|
390
|
+
status: 502,
|
|
391
|
+
title: "Slack API request failed",
|
|
392
|
+
});
|
|
393
|
+
}
|
|
394
|
+
|
|
395
|
+
let invites: SlackInviteResult = {
|
|
396
|
+
alreadyMemberUserIds: [],
|
|
397
|
+
failures: invalidUserIds.map((value) => ({error: "invalid_user_id", userId: value})),
|
|
398
|
+
invitedUserIds: [],
|
|
399
|
+
};
|
|
400
|
+
if (validUserIds.length > 0) {
|
|
401
|
+
try {
|
|
402
|
+
const invited = await inviteBatches(channelId, validUserIds, token);
|
|
403
|
+
invites = {
|
|
404
|
+
...invited,
|
|
405
|
+
failures: [...invites.failures, ...invited.failures],
|
|
406
|
+
};
|
|
407
|
+
} catch (error: unknown) {
|
|
408
|
+
if (!isAPIError(error)) {
|
|
409
|
+
throw error;
|
|
410
|
+
}
|
|
411
|
+
throw new APIError({
|
|
412
|
+
code: error.code,
|
|
413
|
+
detail: error.detail,
|
|
414
|
+
meta: {channelId, channelName},
|
|
415
|
+
status: error.status,
|
|
416
|
+
title: error.title,
|
|
417
|
+
});
|
|
418
|
+
}
|
|
419
|
+
}
|
|
420
|
+
|
|
421
|
+
const text = initialMessage?.trim();
|
|
422
|
+
if (!text && !mentionUserIds?.length) {
|
|
423
|
+
return {channelId, invites, name: created.channel?.name ?? channelName};
|
|
424
|
+
}
|
|
425
|
+
|
|
426
|
+
try {
|
|
427
|
+
const posted = await postSlackMessage({
|
|
428
|
+
channelId,
|
|
429
|
+
mentionUserIds,
|
|
430
|
+
text: text ?? "",
|
|
431
|
+
token,
|
|
432
|
+
});
|
|
433
|
+
return {
|
|
434
|
+
channelId,
|
|
435
|
+
invites,
|
|
436
|
+
messageTs: posted.messageTs,
|
|
437
|
+
name: created.channel?.name ?? channelName,
|
|
438
|
+
};
|
|
439
|
+
} catch (error: unknown) {
|
|
440
|
+
if (!isAPIError(error)) {
|
|
441
|
+
throw error;
|
|
442
|
+
}
|
|
443
|
+
throw new APIError({
|
|
444
|
+
code: "slack-initial-message-failed",
|
|
445
|
+
detail: error.detail,
|
|
446
|
+
meta: {channelId, channelName},
|
|
447
|
+
status: error.status,
|
|
448
|
+
title: "Slack initial message failed",
|
|
449
|
+
});
|
|
450
|
+
}
|
|
451
|
+
};
|
|
452
|
+
|
|
453
|
+
/**
|
|
454
|
+
* Invite staff to a channel the bot already belongs to. Private channels do
|
|
455
|
+
* not allow a bot to join itself; invite the app once, then call this.
|
|
456
|
+
*
|
|
457
|
+
* `groups:write.invites` covers private channels. `channels:write.invites`
|
|
458
|
+
* covers public channels. Member IDs that are already in the channel are
|
|
459
|
+
* reported on `alreadyMemberUserIds` and do not fail the call.
|
|
460
|
+
*/
|
|
461
|
+
export const inviteSlackUsersToChannel = async ({
|
|
462
|
+
channelId,
|
|
463
|
+
userIds,
|
|
464
|
+
token,
|
|
465
|
+
}: InviteSlackUsersOptions): Promise<SlackInviteResult> => {
|
|
466
|
+
const normalizedChannelId = requireChannelId(channelId);
|
|
467
|
+
const {validUserIds, invalidUserIds} = partitionUserIds(userIds);
|
|
468
|
+
if (validUserIds.length === 0) {
|
|
469
|
+
throw new APIError({
|
|
470
|
+
code: "slack-user-id-invalid",
|
|
471
|
+
status: 400,
|
|
472
|
+
title: "Slack invite requires member ids",
|
|
473
|
+
});
|
|
474
|
+
}
|
|
475
|
+
const invited = await inviteBatches(normalizedChannelId, validUserIds, token);
|
|
476
|
+
return {
|
|
477
|
+
...invited,
|
|
478
|
+
failures: [
|
|
479
|
+
...invalidUserIds.map((value) => ({error: "invalid_user_id", userId: value})),
|
|
480
|
+
...invited.failures,
|
|
481
|
+
],
|
|
482
|
+
};
|
|
483
|
+
};
|
|
484
|
+
|
|
485
|
+
/** Post as the bot with `chat:write`. The bot must already be in the channel. */
|
|
486
|
+
export const postSlackMessage = async ({
|
|
487
|
+
channelId,
|
|
488
|
+
text,
|
|
489
|
+
blocks,
|
|
490
|
+
mentionUserIds,
|
|
491
|
+
token,
|
|
492
|
+
}: PostSlackMessageOptions): Promise<PostSlackMessageResult> => {
|
|
493
|
+
const normalizedChannelId = requireChannelId(channelId);
|
|
494
|
+
const prefix = mentionPrefix(mentionUserIds);
|
|
495
|
+
const body = text.trim();
|
|
496
|
+
if (!prefix && !body) {
|
|
497
|
+
throw new APIError({
|
|
498
|
+
code: "slack-message-empty",
|
|
499
|
+
status: 400,
|
|
500
|
+
title: "Slack message text is required",
|
|
501
|
+
});
|
|
502
|
+
}
|
|
503
|
+
const payload: Record<string, unknown> = {
|
|
504
|
+
channel: normalizedChannelId,
|
|
505
|
+
text: prefix && body ? `${prefix} ${body}` : prefix || body,
|
|
506
|
+
};
|
|
507
|
+
if (blocks) {
|
|
508
|
+
payload.blocks = blocks;
|
|
509
|
+
}
|
|
510
|
+
const posted = await callSlackApi<SlackMessageResponse>({
|
|
511
|
+
body: payload,
|
|
512
|
+
method: "chat.postMessage",
|
|
513
|
+
token,
|
|
514
|
+
});
|
|
515
|
+
if (!posted.ts) {
|
|
516
|
+
throw new APIError({
|
|
517
|
+
code: "slack-message-missing",
|
|
518
|
+
detail: "chat.postMessage",
|
|
519
|
+
status: 502,
|
|
520
|
+
title: "Slack API request failed",
|
|
521
|
+
});
|
|
522
|
+
}
|
|
523
|
+
return {channelId: normalizedChannelId, messageTs: posted.ts};
|
|
524
|
+
};
|
|
525
|
+
|
|
526
|
+
/**
|
|
527
|
+
* Find a public channel, or a private channel the bot is already in.
|
|
528
|
+
* Returns undefined when the name is not visible to the bot. Archived
|
|
529
|
+
* channels are skipped. Requires `channels:read` and `groups:read`.
|
|
530
|
+
*/
|
|
531
|
+
export const findSlackChannelByName = async ({
|
|
532
|
+
name,
|
|
533
|
+
token,
|
|
534
|
+
}: FindSlackChannelOptions): Promise<SlackChannelRef | undefined> => {
|
|
535
|
+
const channelName = normalizeSlackChannelName(name);
|
|
536
|
+
let cursor = "";
|
|
537
|
+
|
|
538
|
+
for (let page = 0; page < MAX_CHANNEL_PAGES; page++) {
|
|
539
|
+
const listed = await callSlackApi<SlackListResponse>({
|
|
540
|
+
method: "conversations.list",
|
|
541
|
+
params: {
|
|
542
|
+
cursor,
|
|
543
|
+
exclude_archived: true,
|
|
544
|
+
limit: 200,
|
|
545
|
+
types: "public_channel,private_channel",
|
|
546
|
+
},
|
|
547
|
+
token,
|
|
548
|
+
});
|
|
549
|
+
const match = listed.channels?.find((channel) => {
|
|
550
|
+
const candidate = (channel.name_normalized ?? channel.name ?? "").toLowerCase();
|
|
551
|
+
return candidate === channelName && Boolean(channel.id);
|
|
552
|
+
});
|
|
553
|
+
if (match?.id) {
|
|
554
|
+
return {
|
|
555
|
+
channelId: match.id.toUpperCase(),
|
|
556
|
+
isPrivate: Boolean(match.is_private),
|
|
557
|
+
name: match.name ?? channelName,
|
|
558
|
+
};
|
|
559
|
+
}
|
|
560
|
+
cursor = listed.response_metadata?.next_cursor ?? "";
|
|
561
|
+
if (!cursor) {
|
|
562
|
+
return undefined;
|
|
563
|
+
}
|
|
564
|
+
}
|
|
565
|
+
|
|
566
|
+
return undefined;
|
|
567
|
+
};
|