-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.js
295 lines (260 loc) · 9.7 KB
/
main.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
285
286
287
288
289
290
291
292
293
294
295
var Slack = require("slack-client");
var sqlite3 = require('sqlite3').verbose();
var db = new sqlite3.Database("./digebot.sqlite3");
var fs = require("fs");
var Log = require("log");
var config = require("./config.js");
var DM = require("./node_modules/slack-client/src/dm.js");
var bodyParser = require('body-parser');
var multer = require('multer');
var schedule = require('node-schedule');
logger = new Log("info");
var express = require("express");
var webapp = express();
autoReconnect = true;
autoMark = true;
var DIGEST_PATTERN = /<?(https:\/\/([a-zA-Z\-0-9]+)\.slack\.com\/archives\/([a-zA-Z0-9]+)\/([a-z0-9A-Z\-]+))>? (.*)/
var URL_PATTERN = /<(https?:\/\/[^\s]*)>/;
var slack = new Slack(config.api_token, autoReconnect, autoMark);
var digestChannel = null;
fs.readFile("schema.sql", "utf-8", function(err, data) {
if (err) {
console.log(err);
return;
}
db.run(data);
});
db.serialize(function() {
//db.each("SELECT * FROM digests", function (err, row) {
// console.log(row);
//});
});
slack.on("error", function(err) {
logger.critical(err);
});
slack.on("open", function () {
logger.info("Connected");
digestChannel = slack.getChannelByName(config.digest_channel);
});
function addDigestFromMessage(message, reportedChannel, summary, user) {
if (message.ok) {
if (message.messages.length == 1) {
var reportedMessage = message.messages[0];
addDigest(reportedChannel, summary, user, reportedMessage);
}
}
}
function addDigestWithMatch(match, user) {
console.log(match);
var reportedChannel = slack.getChannelByName(match[3]);
if (!reportedChannel || reportedChannel instanceof DM) {
return {ok: false, message: "You can't digest private messages."};
}
console.log("Channel ID " + reportedChannel.id);
var ts = match[4].substr(1);
ts = ts.replace(/([0-9]{6})$/, ".$1");
var options = {
oldest: ts,
latest: ts,
inclusive: 1,
count: 1,
channel: reportedChannel.id
};
var summary = match[5];
var message_url = match[1];
slack._apiCall("channels.history", options, function (data) {
console.log(data);
addDigestFromMessage(data, reportedChannel, summary, user, message_url);
});
return {ok: true, message: "Thanks"};
}
slack.on("message", function(message) {
var user = slack.getUserByID(message.user);
var dm = slack.getDMByID(message.channel);
if (dm && user) {
logger.info("@" + user.name + " [DM]: " + message.text);
var text = message.text;
if (config.greeting.indexOf(text.toLowerCase()) >= 0) {
dm.send(applySentenceCase(
config.greeting[nextRandomInt(config.greeting.length)]));
} else if (text == ":eggplant:") {
dm.send("( ͡° ͜ʖ ͡°)");
} else {
var match = DIGEST_PATTERN.exec(text);
if (match) {
dm.send(addDigestWithMatch(match, user).message);
} else if (text == "send") {
dm.send("Ok, I'll send this.");
sendDigests();
}
}
}
});
function applySentenceCase(str) {
var sentences = str.split(/[\.!\?/]/);
var text = "";
sentences.forEach(function(sentence) {
text += sentence.charAt(0).toUpperCase() + sentence.substr(1).toLowerCase() + ".";
});
return text;
}
function addDigest(channel, summary, reportingUser, message) {
var url = generateArchivesLink(slack.team.domain, channel.name, message.ts);
db.run("INSERT INTO digests (summary, user, message_url, channel, created, message) VALUES (?, ?, ?, ?, ?, ?)",
summary, reportingUser.id, url, channel.id, new Date().getTime(), message.text);
console.info("Added digest for " + url + " '" + message + "' from " + reportingUser.name + " with summary '" + summary + "'");
}
function nextRandomInt(max) {
return Math.floor(Math.random() * (max - 1));
}
var messageQueue = [];
var sendingMessage = null;
function invokeMessageQueue(data) {
if (data && !data.ok) {
logger.critical("Error for message");
logger.critical(sendingMessage);
logger.critical(data);
}
if (messageQueue.length == 0) {
return;
}
sendingMessage = messageQueue.shift();
slack._apiCall("chat.postMessage", sendingMessage, invokeMessageQueue);
}
function emptyDigest() {
return {
suggestingUsers: [],
message_url: null,
summaries: [],
text: ""
};
}
function sendDigest(digest) {
var users = "";
for (var i = 0; i < digest.suggestingUsers.length; i ++) {
users += digest.suggestingUsers[i].name.replace(/([a-z])/, "$1\u200B");
if (i < digest.suggestingUsers.length - 2) {
users += ", ";
} else if (i == digest.suggestingUsers.length - 2) {
users += " and ";
}
}
var titles = "";
for (i = 0; i < digest.summaries.length; i++) {
titles += '“' + digest.summaries[i] + '”';
if (i < digest.summaries.length - 1) {
titles += "\n";
}
}
var msg = {
channel: digestChannel.id,
unfurl_links: true,
as_user: true,
text: digest.text,
attachments: JSON.stringify([{
title: titles,
text: "_suggested by " + users + "_",
color: "#733AA9",
title_link: digest.message_url,
mrkdwn_in: ["text", "title"]
}])
};
messageQueue.push(msg);
}
function sendDigests() {
db.serialize(function () {
db.each("SELECT COUNT(*) FROM digests WHERE status = 0", function(err, row) {
var count = row["COUNT(*)"];
if (count > 0) {
digestChannel.send("*Here's what you might have missed in the last 6h*");
var lastChannel = null;
var i = 0;
var lastDigest = emptyDigest();
db.each("SELECT * FROM digests WHERE status = 0 ORDER BY channel ASC, message_url ASC, created DESC", function (err, row) {
if (err) {
logger.critical("Error while accessing db for digests");
logger.critical(err);
return;
}
if (lastDigest && lastDigest.message_url != row["message_url"]) {
if (lastDigest.message_url) {
sendDigest(lastDigest);
}
lastDigest = emptyDigest();
var urlMatch = URL_PATTERN.exec(row["message"]);
lastDigest.text = urlMatch ? urlMatch[1] : "";
lastDigest.message_url = row["message_url"];
}
var currentChannel = slack.getChannelByID(row["channel"]);
if (!lastChannel || lastChannel.id != currentChannel.id) {
var channelMsg = {
channel: digestChannel.id,
text: "#"+currentChannel.name,
as_user: true
};
messageQueue.push(channelMsg);
}
var suggestingUser = slack.getUserByID(row["user"]);
if (lastDigest.suggestingUsers.indexOf(suggestingUser) < 0) {
lastDigest.suggestingUsers.push(suggestingUser);
}
lastDigest.summaries.push(row["summary"]);
lastChannel = currentChannel;
i++;
if (i == count) {
sendDigest(lastDigest);
invokeMessageQueue();
db.run("UPDATE digests SET status = 1 WHERE status = 0");
}
});
}
});
});
}
function generateArchivesLink(team, channel, ts) {
return "https://" + team + ".slack.com/archives/" + channel + "/p" + ts.replace(/\./, "");
}
webapp.use(bodyParser.json()); // for parsing application/json
webapp.use(bodyParser.urlencoded({ extended: true })); // for parsing application/x-www-form-urlencoded
webapp.post("/slackslash", function(req, res) {
logger.info("Incoming slackslash");
if (req.body.token == config.slash_command_token) {
if (req.body.command == "/digest") {
console.log(req.body);
var channel = slack.getChannelByID(req.body.channel_id);
var user = slack.getUserByID(req.body.user_id);
var text = req.body.text;
var match = DIGEST_PATTERN.exec(text);
if (text == "") {
res.status(400).send("You have to summarize what happened.");
return;
}
if (match) {
var result = addDigestWithMatch(match, user);
if (!result.ok) {
res.status(400);
}
res.send(result.message);
} else if (channel) {
slack._apiCall("channels.history", {channel: channel.id, count: 1}, function(message) {
addDigestFromMessage(message, channel, text, user);
res.send("Thanks!");
});
} else {
res.status(400).send("You can't digest private messages");
logger.info("Tried to digest private message");
}
} else {
res.status(404, "Command not found");
logger.info("Command wrong")
}
} else {
res.status(401, "Wrong token");
logger.info("Wrong token");
}
});
var server = webapp.listen(config.port);
slack.login();
config.schedule.forEach(function(s) {
schedule.scheduleJob(s, sendDigests);
});