forked from mishk0/slack-bot-api
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.ts
361 lines (294 loc) · 8.13 KB
/
index.ts
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
"use strict";
import WebSocket, { EventEmitter } from "ws";
import fetch from "node-fetch";
const _ = require("lodash");
const extend = require("extend");
const { setWsHeartbeat } = require("ws-heartbeat/client");
export default class Bot extends EventEmitter {
private token: string;
private name: string;
private channels: any[] = [];
private users: any[] = [];
private groups: any[] = [];
private ims: any[] = [];
public ws: WebSocket | null = null;
public retryAfter: number | null = null;
constructor(params?: any) {
super(params);
this.token = params.token;
this.name = params.name;
console.assert(params.token, "token must be defined");
}
public async connect() {
const data = await this._api("rtm.connect");
if (!data) {
this.emit("error", new Error(data.error ? data.error : data));
}
this.ws = new WebSocket(data.url);
setWsHeartbeat(this.ws, '{ "kind": "ping" }');
this.emit("start");
this.ws.on("error", (data: any) => {
this.emit("error", new Error(data?.error ?? data));
});
this.ws.on("open", (data: any) => {
this.emit("open", data);
});
this.ws.on("close", (data) => {
this.emit("close", data);
});
this.ws.on("message", (data) => {
try {
this.emit("message", JSON.parse(data.toString()));
} catch (e) {
console.log(e);
}
});
}
public async getChannels() {
if (this.channels.length) {
return { channels: this.channels };
}
return await this._api("conversations.list");
}
public async getUsers() {
if (this.users.length) {
return { members: this.users };
}
return await this._api("users.list");
}
public async getGroups() {
if (this.groups.length) {
return { groups: this.groups };
}
return await this._api("conversations.list");
}
public async getUser(name: string) {
const data = await this.getUsers();
const res = _.find(data.members, { name: name });
console.assert(res, "user not found");
return res;
}
public async getChannel(name: string) {
const data = await this.getChannels();
const res = _.find(data.channels, { name: name });
console.assert(res, "channel not found");
return res;
}
public async getGroup(name: string) {
const data = await this.getGroups();
const res = _.find(data.groups, { name: name });
console.assert(res, "group not found");
return res;
}
public async getUserById(id: string) {
const data = await this.getUsers();
const res = _.find(data.members, { id: id });
console.assert(res, "user not found");
return res;
}
public async getChannelById(id: string) {
const data = await this.getChannels();
const res = _.find(data.channels, { id: id });
console.assert(res, "channel not found");
return res;
}
public async getGroupById(id: string) {
const data = await this.getGroups();
const res = _.find(data.groups, { id: id });
console.assert(res, "group not found");
return res;
}
public async getChannelId(name: string) {
const channel = await this.getChannel(name);
return channel.id;
}
public async getGroupId(name: string) {
const group = await this.getGroup(name);
return group.id;
}
public async getUserId(name: string) {
const user = await this.getUser(name);
return user.id;
}
public async getUserByEmail(email: string) {
const data = await this.getUsers();
return _.find(data.members, { profile: { email: email } });
}
public async getChatId(name: string) {
const user = await this.getUser(name);
const chatId = _.find(this.ims, { user: user.id });
const data = (chatId && chatId.id) || this.openIm(user.id);
return typeof data === "string" ? data : data.channel.id;
}
public async openIm(userId: string) {
return await this._api("conversations.open", { user: userId });
}
public async getImChannels() {
if (this.ims.length) {
return { ims: this.ims };
}
return await this._api("conversations.list");
}
public async postEphemeral(
id: string,
user: string,
text: string,
params: any
) {
params = extend(
{
text: text,
channel: id,
user: user,
username: this.name,
},
params || {}
);
return await this._api("chat.postEphemeral", params);
}
public async postMessage<T = any>(id: string, text: string, params: any) {
params = extend(
{
text: text,
channel: id,
username: this.name,
},
params || {}
);
return await this._api<T>("chat.postMessage", params);
}
public async updateMessage(
id: string,
ts: string,
text: string,
params: any
) {
params = extend(
{
ts: ts,
channel: id,
username: this.name,
text: text,
},
params || {}
);
return await this._api("chat.update", params);
}
public async postMessageToUser(
name: string,
text: string,
params?: any,
cb?: (value: any) => void
) {
return await this._post(
(params || {}).slackbot ? "slackbot" : "user",
name,
text,
params,
cb
);
}
public async postMessageToChannel(
name: string,
text: string,
params?: any,
cb?: (value: any) => void
) {
return await this._post("channel", name, text, params, cb);
}
public async postMessageToGroup(
name: string,
text: string,
params?: any,
cb?: (value: any) => void
) {
return await this._post("group", name, text, params, cb);
}
private async _post(
type: "group" | "channel" | "user" | "slackbot",
name: string,
text: string,
params?: any | null,
cb?: (value: any) => void
) {
const method = {
group: "getGroupId",
channel: "getChannelId",
user: "getChatId",
slackbot: "getUserId",
}[type];
const itemId = await (this as any)[method](name);
const data = await this.postMessage(itemId, text, params);
return cb?.(data._value);
}
public async postTo(
name: string,
text: string,
params: any,
cb: (value: any) => void
) {
const data = await Promise.all([
this.getChannels(),
this.getUsers(),
this.getGroups(),
]);
name = this._cleanName(name);
const all = [].concat(data[0].channels, data[1].members, data[2].groups);
const result = _.find(all, { name: name });
console.assert(result, "wrong name");
if (result["is_channel"]) {
return await this.postMessageToChannel(name, text, params, cb);
} else if (result["is_group"]) {
return await this.postMessageToGroup(name, text, params, cb);
} else {
return await this.postMessageToUser(name, text, params, cb);
}
}
private _cleanName(name: string) {
if (typeof name !== "string") {
return name;
}
const firstCharacter = name.charAt(0);
if (firstCharacter === "#" || firstCharacter === "@") {
name = name.slice(1);
}
return name;
}
private _preprocessParams(params?: any) {
const searchParams = new URLSearchParams();
searchParams.append("token", this.token);
if (!params) {
return searchParams;
}
for (const [key, value] of Object.entries(params)) {
if (typeof value === "object") {
searchParams.append(key, JSON.stringify(value));
continue;
}
searchParams.append(key, value as string);
}
return searchParams;
}
private async _api<T extends { ok?: boolean } & any = any>(
methodName: string,
params?: any
): Promise<T> {
const response = await fetch(`https://slack.com/api/${methodName}`, {
method: "POST",
body: this._preprocessParams(params),
});
// Keep track of last retry so we can handle accordingly if needed
this.retryAfter = response.headers.has("retry-after")
? Number(response.headers.get("retry-after"))
: null;
const data = await response.json();
/**
* Response data always contain a top-level boolean property ok,
* indicating success or failure
*/
if (!response.ok || !data.ok) {
throw data;
}
return data as T;
}
}