forked from MeetMangrove/digest-slack-bot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
job.js
58 lines (50 loc) · 2.14 KB
/
job.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
var model = require('./model');
var config = require('./config');
var request = require('request');
var LIMIT = 20;
setTimeout(() => process.exit(), 10000); // the process quits after 10 seconds
function fetchMessageContent(msgs, callback) {
var url = 'https://slack.com/api/channels.list?token=' + config.SLACK_TOKEN;
//console.log(url);
request.get(url, { json: true }, (err, res, body) => {
//console.log(err, typeof body, body);
var channels = {};
body.channels.forEach(c => {
channels[c.id] = c;
});
callback(err, msgs.map(m => Object.assign(m, {
channelName: channels[m.channel].name
})));
});
}
console.log('find...');
model.Message.find({ broadcasted: { $ne: true } }).sort({ votes: -1 }).limit(LIMIT).exec(function(err, msgs){
console.log('find=>', err || msgs);
fetchMessageContent(msgs, function(err, messages){
if (messages.length === 0) {
config.bot.postMessageToChannel(config.DIGEST_CHANNEL, 'Sorry, no new messages with ' + config.REACTION_NAME + ' this time... :\'-(', {
unfurl_links: true
});
} else {
messages.forEach(function(msg){
// syntax: <nb_votes> :balloon: <URL>
var url = 'https://' + config.SLACK_NAME + '.slack.com/archives/' + msg.channelName + '/p' + msg.id.replace('.', '');
var digestLine = msg.votes + ' :' + config.REACTION_NAME + ': ' + url;
console.log(digestLine); // TODO
// display in the #gen-bot channel
config.bot.postMessageToChannel(config.DIGEST_CHANNEL, digestLine, {
unfurl_links: true
});
});
// TODO: send digest to admin, then allow admin to edit it before sharing it publicly
// config.bot.postMessageToUser(config.ADMIN_USERNAME, digest, { 'slackbot': true, icon_emoji: ':cat:' });
// will post the user, from "Gem Bot" (instead of slack's slackbot channel)
// mark messages
const ids = messages.map(m => m.id);
// prevent a message from being digested twice
model.Message.update({ id: { $in : ids } }, { $set: { broadcasted: true } }, { multi: true }, (err, res) => {
err && console.error(err);
});
}
});
});