-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
87 lines (84 loc) · 2.52 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
const axios = require('axios');
const FormData = require('form-data');
const LRU = require('lru-cache-ext');
const objectHash = require('object-hash-strict');
module.exports = (workspaceUrl, token, { cacheTtl = 60, cacheMaxEntries = 100 } = {}) => {
const lru = new LRU({ maxAge: cacheTtl * 1000, max: cacheMaxEntries });
const call = (endpoint, params, cache = false) => {
const formDataRaw = { token, ...params };
const formData = Object.entries(formDataRaw).reduce((p, [k, v]) => {
p.append(k, v);
return p;
}, new FormData());
const requestParams = {
method: 'post',
url: `https://${workspaceUrl}.slack.com/api/${endpoint}`,
data: formData,
headers: {
// eslint-disable-next-line no-underscore-dangle
'Content-Type': `multipart/form-data; boundary=${formData._boundary}`
}
};
const req = async () => {
const { data } = await axios(requestParams);
return data;
};
if (cache !== true) {
return req();
}
const signature = objectHash({
workspaceUrl, endpoint, token, params
});
return lru.memoize(signature, () => req());
};
const channelMeta = async (name) => {
const rtmStart = await call('rtm.start', {}, true);
const channel = rtmStart.channels.find((chan) => chan.name === name);
if (!channel) {
throw new Error(`Channel "${name}" not found.`);
}
return channel;
};
return {
call,
workspace: {
details: (cache = true) => call('rtm.start', {}, cache)
},
self: {
message: async (msg) => {
const rtmStart = await call('rtm.start', {}, true);
const user = rtmStart.self;
return call('chat.command', {
disp: '/me',
command: '/msg',
text: `${user.name} ${msg}`,
channel: rtmStart.ims.find((im) => im.user === user.id).id
});
}
},
channel: {
meta: channelMeta,
message: async (name, msg) => {
const channel = await channelMeta(name);
return call('chat.postMessage', {
text: msg,
channel: channel.id
});
},
setTopic: async (name, topic) => {
const channel = await channelMeta(name);
return call('conversations.setTopic', {
topic,
channel: channel.id
});
},
setPurpose: async (name, purpose) => {
const channel = await channelMeta(name);
return call('conversations.setPurpose', {
purpose,
channel: channel.id
});
}
}
};
};