-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrocketchat-adapter.js
63 lines (58 loc) · 1.28 KB
/
rocketchat-adapter.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
const request = require('request');
const conf = require('./conf.json');
let authenticated = false;
let authToken = null;
let userId = null;
const rocketchatAdapter = {
login: () => {
return new Promise((resolve, reject) => {
request.post({
url: `${conf.rocketchatProtocol}://${conf.rocketchatHost}/api/v1/login`,
form: {
user: conf.rocketchatUsername,
password: conf.rocketchatPassword
}
}, (error, response, body) => {
body = JSON.parse(body);
if (error) {
return reject(error);
}
if (body.status === 'success') {
authenticated = true;
authToken = body.data.authToken;
userId = body.data.userId;
return resolve(body);
} else {
return reject(body.message);
}
});
});
},
post: msg => {
request.post({
url: 'https://demo.rocket.chat/api/v1/chat.postMessage',
headers: {
'X-Auth-Token': authToken,
'X-User-Id': userId
},
form: {
channel: conf.rocketchatChannel,
text: msg
}
}, error => {
if (error) {
console.log(error);
}
});
},
sendMessage: msg => {
if (authenticated) {
rocketchatAdapter.post(msg);
} else {
rocketchatAdapter.login().then(() => {
rocketchatAdapter.post(msg);
}, err => console.log(err));
}
}
};
module.exports = rocketchatAdapter;