-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbot.js
109 lines (93 loc) · 2.8 KB
/
bot.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
var HTTPS = require('https');
function sendReq(options, body ){
return new Promise(function(resolve, reject) {
var req = HTTPS.request(options, (res) => {
if(res.statusCode < 200 || res.statusCode >= 300){
return reject(new Error('statusCode=' + res.statusCode));
}
var data = '';
console.log(`STATUS: ${res.statusCode}`);
res.on('data', (chunk) => {
//console.log(`BODY: ${chunk}`);
data += chunk;
});
res.on('end', () => {
//console.log("No more data!");
try{
data = JSON.parse(data);
}catch(e){
reject(e);
}
resolve(data);
});
});
//reject on request error
req.on('error', function(err) {
console.log('error with request ' + JSON.stringify(err));
reject(err);
});
req.on('timeout', function(err){
console.log('timeout with request ' + JSON.stringify(err));
reject(err);
});
if(body){
req.end(JSON.stringify(body));
}else{
req.end();
}
});
}
function getChannels(botAuth){
var options;
options = {
hostname: 'www.slack.com',
path: '/api/channels.list',
method: 'GET',
headers: {
'Authorization': botAuth,
'Content-Type': 'application/x-www-form-urlencoded',
}
};
sendReq(options);
}
function botPostMessage(message, botAuth){
var options, body;
options = {
hostname: 'www.slack.com',
path: '/api/chat.postMessage',
method: 'POST',
headers: {
'Authorization': botAuth,
'Content-Type': 'application/json',
}
};
body = {
'channel': 'CB5R6F1K6',
'text': message
};
sendReq(options, body).then(function(data) {
console.log(data);
});
}
//Test API runs the first test API method to verify if things are running properly (for personal experience, not necessary at all)
function testAPI(auth){
var options, x;
x = '';
options = {
hostname: 'www.slack.com',
path: '/api/api.test',
method: 'POST',
auth: 'Authorization: '+ auth,
headers: {
'Content-Type': 'application/json',
}
};
sendReq(options).then(function(body) {
console.log(body.ok);
x = body.ok;
console.log("testing variable from in the scope: " + x);
});
//this gets called before the variable x can be filled due to normal NodeJS asynchronous flow
// console.log("testing variable from outside the scope: " + x);
}
module.exports = botPostMessage;