-
Notifications
You must be signed in to change notification settings - Fork 0
/
tinyspeck.js
284 lines (232 loc) · 8.56 KB
/
tinyspeck.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
//
// Adapted from https://github.com/johnagan/tinyspeck
// This does much of the heavy-lifting for our bot. It does things like sending data to Slack's API,
// parsing the Slack messages received, implementing the event handler as well as setting up a Web Server
// to listen for WebHooks and set up the routes to serve pages for OAuth and the Add to Slack button.
//
"use strict";
const dispatcher = require('httpdispatcher'),
http = require('http'),
axios = require('axios'),
WebSocket = require('ws'),
qs = require('querystring'),
EventEmitter = require('events'),
datastore = require("./datastore.js").data,
oauthd = require('./oauthd.js'),
add_to_slack = 'https://slack.com/oauth/authorize?scope=bot,chat:write:bot,pins:read,reactions:read,stars:read,commands&client_id=' + process.env.SLACK_CLIENT_ID;
class TinySpeck extends EventEmitter {
/**
* Contructor
*
* @param {Object} defaults - The default config for the instance
*/
constructor(defaults) {
super();
this.cache = {};
// message defaults
this.defaults = defaults || {};
// loggers
this.on('error', console.error);
}
/**
* Create an instance of the TinySpeck adapter
*
* @param {Object} defaults - The default config for the instance
* @return {TinySpeck} A new instance of the TinySpeck adapter
*/
instance(defaults) {
return new this.constructor(defaults);
}
/**
* Send data to Slack's API
*
* @param {string} endPoint - The method name or url (optional - defaults to chat.postMessage)
* @param {object} args - The JSON payload to send
* @return {Promise} A promise with the API result
*/
send(/* ...args */) {
let args = 1 <= arguments.length ? Array.prototype.slice.call(arguments, 0) : [];
let endPoint = 'chat.postMessage'; // default action is post message
// if an endpoint was passed in, use it
if (typeof args[0] === 'string') endPoint = args.shift();
// use defaults when available
let message = Object.assign({}, this.defaults, args);
// call update if ts included
if (message.ts && endPoint === 'chat.postMessage') endPoint = 'chat.update';
return this.post(endPoint, message);
}
/**
* Parse a Slack message
*
* @param {object|string} message - The incoming Slack message
* @return {Message} The parsed message
*/
parse(message) {
if (typeof message === 'string') {
try { message = JSON.parse(message); } // JSON string
catch(e) { message = qs.parse(message); } // QueryString
}
// message button payloads are JSON strings
if (message.payload) message.payload = JSON.parse(message.payload);
return message;
}
/**
* Digest a Slack message and process events
*
* @param {object|string} message - The incoming Slack message
* @return {Message} The parsed message
*/
digest(message) {
let event_ts = this.parse(message).event_ts;
let event = this.parse(message).event;
let command = this.parse(message).command;
let type = this.parse(message).type;
let trigger_word = this.parse(message).trigger_word;
let payload = this.parse(message).payload;
// wildcard
this.emit('*', message);
// notify incoming message by type
if (type) this.emit(type, message);
// notify slash command by command
if (command) this.emit(command, message);
// notify event triggered by event type
if (event) this.emit(event.type, message);
// notify webhook triggered by trigger word
if (trigger_word) this.emit(trigger_word, message);
// notify message button triggered by callback_id
if (payload) this.emit(payload.callback_id, message);
return message;
}
/**
* Event handler for incoming messages
*
* @param {mixed} names - Any number of event names to listen to. The last will be the callback
* @return {TinySpeck} The TinySpeck adapter
*/
on(/* ...names */) {
let names = 1 <= arguments.length ? Array.prototype.slice.call(arguments, 0) : [];
let callback = names.pop(); // support multiple events per callback
names.forEach(name => super.on(name, callback));
return this; // chaining support
}
/**
* Start RTM
*
* @param {object} options - Optional arguments to pass to the rtm.start method
* @return {WebSocket} A promise containing the WebSocket
*/
rtm(options) {
return this.send('rtm.start', options).then(res => {
this.cache = res.data.self;
let ws = new WebSocket(res.data.url);
ws.on('message', this.digest.bind(this));
ws.on('close', () => this.ws = null);
ws.on('open', () => this.ws = ws);
return Promise.resolve(ws);
});
}
/**
* WebServer to listen for WebHooks
*
* @param {int} port - The port number to listen on
* @param {string} token - Optionally provide a token to verify
* @return {listener} The HTTP listener
*/
listen(port, token) {
// handle oauth from Slack
dispatcher.onGet("/auth/grant", function(req, res) {
if(req.params.code){
res.writeHead(200, {'Content-Type': 'text/html'});
let html = '<p>Success! Authed ok</p>';
res.end(html);
} else {
res.writeHead(200, {'Content-Type': 'text/html'});
let html = '<p>Failed! Something went wrong when authing, check the logs</p>';
res.end(html);
}
// get the code, turn it into a token
let code = req.params.code;
oauthd.oauth(code).then(function(body) {
//store body.access_token;
datastore.set("bot_token", body.access_token).then(function(){
console.log("token stored");
});
}).catch(function(error) {
console.log(error);
res.send(error);
});
});
// Display the Add to Slack button
dispatcher.onGet("/", function(req, res) {
res.writeHead(200, {'Content-Type': 'text/html'});
let html = '<h1>Example Onboarding Slack Bot</h1><p>This project demonstrates how to build a Slack bot using Slack\'s Events API.</p><p>To test it out:</p><a id="add-to-slack" href="'+add_to_slack+'"><img alt="Add to Slack" height="40" width="139" src="https://platform.slack-edge.com/img/add_to_slack.png" srcset="https://platform.slack-edge.com/img/add_to_slack.png 1x, https://platform.slack-edge.com/img/[email protected] 2x" /></a><script src="https://button.glitch.me/button.js" data-style="glitch"></script><div class="glitchButton" style="position:fixed;top:20px;right:20px;"></div>';
res.end(html);
});
return http.createServer((req, res) => {
let data = '';
req.on('data', chunk => data += chunk);
req.on('end', () => {
let message = this.parse(data);
// notify upon request
this.emit(req.url, message);
// new subscription challenge
if (message.challenge){ console.log("verifying event subscription!"); res.end(message.challenge); return exit(); }
// digest the incoming message
if (!token || token === message.token) this.digest(message);
// close response
res.end();
});
dispatcher.dispatch(req, res);
}).listen(port, '0.0.0.0', () => {
console.log(`listening for events on port ${port}`);
});
}
/**
* POST data to Slack's API
*
* @param {string} endPoint - The method name or url
* @param {object} payload - The JSON payload to send
* @return {Promise} A promise with the api result
*/
post(endPoint, payload) {
let token = payload.token;
payload = payload[0];
if (!/^http/i.test(endPoint)) {
// serialize JSON params
if (payload.attachments)
payload.attachments = JSON.stringify(payload.attachments);
// serialize JSON for POST
payload = qs.stringify(payload);
} else {
if(isJSON(payload.attachments)){
payload.attachments = JSON.parse(payload.attachments);
}
}
if(endPoint.indexOf('hooks')!=-1){
return axios({ // responding to slash command
url: endPoint,
data: payload,
method: 'post',
headers: { 'user-agent': 'TinySpeck' }
});
} else {
return axios({ // responding to event
url: endPoint+"?token="+token,
data: payload,
method: 'post',
baseURL: 'https://slack.com/api/',
headers: { 'user-agent': 'TinySpeck', Authorization: "Bearer " + token }
});
}
}
}
function isJSON(data) {
var ret = true;
try {
JSON.parse(data);
}catch(e) {
ret = false;
}
return ret;
}
module.exports = new TinySpeck();