forked from maxrpeterson/dianabot
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathslackbot-new.js
More file actions
105 lines (92 loc) · 2.31 KB
/
Copy pathslackbot-new.js
File metadata and controls
105 lines (92 loc) · 2.31 KB
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
var async = require('async'),
https = require('https'),
querystring = require('querystring'),
ws = require('ws');
function slackbot(token) {
this.token = token;
this.handlers = [];
this.messageID = 0;
this.selfData = {};
this.mention = "";
return this;
}
slackbot.prototype.api = function(method, params, cb) {
var options, post_data, req;
params['token'] = this.token;
post_data = querystring.stringify(params);
options = {
hostname: 'api.slack.com',
method: 'POST',
path: '/api/' + method,
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': post_data.length
}
};
req = https.request(options);
req.on('response', function(res) {
var buffer;
buffer = '';
res.on('data', function(chunk) {
return buffer += chunk;
});
return res.on('end', function() {
var value;
if (cb != null) {
if (res.statusCode === 200) {
value = JSON.parse(buffer);
return cb(value);
} else {
return cb({
'ok': false,
'error': 'API response: ' + res.statusCode
});
}
}
});
});
req.on('error', function(error) {
if (cb != null) {
return cb({
'ok': false,
'error': error.errno
});
}
});
req.write(post_data);
return req.end();
};
slackbot.prototype.use = function(fn) {
this.handlers.push(fn);
return this;
};
slackbot.prototype.handle = function(data) {
async.series(this.handlers.map(function(fn) {
return function(cb) {
fn(data, cb);
};
}));
return this;
};
slackbot.prototype.sendMessage = function(channel, text) {
var message = {
id: ++this.messageID,
type: 'message',
channel: channel,
text: text
};
return this.ws.send(JSON.stringify(message));
};
slackbot.prototype.connect = function() {
var self = this;
self.api('rtm.start', {agent: 'node-slack', simple_latest: true, no_unreads: true}, function(data) {
self.selfData = data.self;
self.mention = "<@" + self.selfData.id + ">";
self.ws = new ws(data.url);
self.ws.on('message', function(data, flags) {
var message = JSON.parse(data);
self.handle(message);
});
});
};
module.exports = slackbot;