-
Notifications
You must be signed in to change notification settings - Fork 0
/
node_helper.js
95 lines (81 loc) · 2.07 KB
/
node_helper.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
var NodeHelper = require("node_helper");
var { WebClient, LogLevel } = require("@slack/web-api");
var client;
var messages = [];
module.exports = NodeHelper.create({
start: function() {
console.log('Starting node helper for: ' + this.name);
},
socketNotificationReceived: function(notification, payload) {
if (notification === 'START_CONNECTION') {
this.initializeSlackConnection(payload.config);
}
if (notification === 'GET_SLACK_MESSAGES') {
this.getSlackMessages(payload.config);
}
},
initializeSlackConnection: function(config) {
var self = this;
var token = config.slackToken;
if(config.debug) {
client = new WebClient(token, {
logLevel: LogLevel.DEBUG
});
}
else {
client = new WebClient(token, {
logLevel: LogLevel.INFO
});
}
this.getSlackMessages(config);
},
getSlackMessages: async function(config) {
var self = this;
var channelId = config.slackChannel;
var limit = config.maxMessages;
var slackMessages;
var result;
try {
result = await client.conversations.history({
channel: channelId,
limit: limit
});
}
catch (error) {
console.error(error);
}
console.log("MMM-Slack2: " + result.messages.length + " messages received.");
var slackMessages = [];
result.messages.forEach(function(message) {
if(!message.subtype) {
var slackMessage = {
'messageId': message.ts,
'user': message.user,
'message': message.text
};
slackMessages.push(slackMessage);
}
});
this.messages = slackMessages;
this.prepareDataForSending(config);
},
prepareDataForSending: async function(config) {
if (config.showUserName) {
for(var i = 0; i < this.messages.length; i++) {
var userName;
try {
const userData = await client.users.info({ user: this.messages[i].user });
userName = userData.user.real_name
}
catch (error) {
console.error(error);
}
this.messages[i].user = userName;
}
}
this.broadcastMessage();
},
broadcastMessage: function() {
this.sendSocketNotification('SLACK_DATA', this.messages);
}
});