-
Notifications
You must be signed in to change notification settings - Fork 7
/
history.bot.js
164 lines (137 loc) · 4.57 KB
/
history.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
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
const config = require('pico-conf');
const Slack = require('../../utils/pico-slack');
const datefns = require('date-fns');
const request = require('superagent');
const S3 = require('../../utils/s3.js');
const MIN = 60 * 1000;
const isProd = config.get('production', true);
const BucketName = config.get('historybot.bucket_name');
const IgnoredChannels = (config.get('historybot.ignored_channels', true) || '').split(',');
const DatabaseToken = config.get('historybot.db_token', true);
const DatabaseApiHost = config.get('historybot.db_host', true);
const wait = async (n,val)=>new Promise((r)=>setTimeout(()=>r(val), n));
let HistoryStorage = {};
const getDate = (ts)=>datefns.format(new Date(ts*1000), 'YYYY-MM-DD H:mm:ss');
const uploadToDatabase = async (endpoint, payload)=>{
if (!DatabaseToken) return;
if (!DatabaseApiHost) {
const msg = '[HistoryBot] Database token has been set but host is still blank!';
if (isProd) return console.error(msg);
return console.warn(msg);
}
return await request.post(`https://${DatabaseApiHost}/${endpoint}`)
.set('X-Verification-Token', DatabaseToken)
.send(payload)
.catch(console.error);
};
const fetchHistory = async (channel)=>{
let channelData;
try{
channelData = JSON.parse(await S3.fetch(BucketName, `${channel}.json`));
}catch(err){ channelData = [] }
if(!HistoryStorage[channel]) return channelData
return channelData.concat(HistoryStorage[channel]);
}
const saveChannel = async (channel)=>{
console.log(`Saving ${channel}...`);
const channelData = await fetchHistory(channel);
await S3.upload(BucketName, `${channel}.json`, JSON.stringify(channelData));
delete HistoryStorage[channel];
console.log(`Finished ${channel}`);
};
const backupAll = async ()=>{
const channels = Object.keys(HistoryStorage);
if(!channels.length){
return;
}
await channels.reduce((seq, channel)=>{
return seq.then(()=>saveChannel(channel)).then(()=>wait(500));
}, Promise.resolve());
};
const parseMessage = (msgObj)=>{
return {
ts : msgObj.ts,
user : msgObj.user,
text : msgObj.text,
thread : msgObj.thread_ts,
//date : datefns.format(new Date(), 'dd/MMM/yyy - H:mm:ss'), //for v2 of datefns
//date : datefns.format(new Date(), 'DD/MMM/YYYY - H:mm:ss'),
//date : datefns.format(new Date(), 'YYYY-MM-DD H:mm:ss'),
}
}
const storeMessage = (msg)=>{
const payload = parseMessage(msg);
HistoryStorage[msg.channel] = (HistoryStorage[msg.channel] || []).concat(payload);
// Sideload messages into the history database, without blocking.
uploadToDatabase('messages', Object.assign({}, payload, {
channel : {
id : msg.channel_id,
name : msg.channel,
},
user : {
id : msg.user_id,
name : msg.user,
},
}));
};
const uploadHistoryToSlack = async (channel, dest)=>{
const content = await fetchHistory(channel);
const filename = `coolsville-${channel}-history.txt`
const file = content.map((entry)=>`[${entry.user} ${getDate(entry.ts)}]:${entry.text}`).join('\n');
await request.post('https://slack.com/api/files.upload')
.field('token', Slack.token)
.field('channels', dest)
.field('filename', filename)
.field('filetype', 'txt')
.field('title', filename)
.attach('file', Buffer.from(file), {filename})
};
const uploadJSONToSlack = async (channel, dest)=>{
const content = await fetchHistory(channel);
const filename = `coolsville-${channel}-history.json`
const file = JSON.stringify(content, null, ' ');
await request.post('https://slack.com/api/files.upload')
.field('token', Slack.token)
.field('channels', dest)
.field('filename', filename)
.field('filetype', 'json')
.field('title', filename)
.attach('file', Buffer.from(file), {filename})
}
setInterval(backupAll, config.get('historybot:backup_rate'))
Slack.onMessage(async (msg)=>{
if(Slack.has(msg.text, 'higgins', 'history', ['please', 'plz', 'channel'])){
Slack.send(msg.channel, 'Yup, 1 sec...');
let channel = msg.channel;
if (msg.isDirect) {
const matches = /<#[A-Z0-9]+\|([^>]+)>/.exec(msg.text);
channel = matches[1];
}
if(Slack.msgHas(msg.text, 'json')){
return await uploadJSONToSlack(channel, msg.channel);
}
return await uploadHistoryToSlack(channel, msg.channel);
}
if(msg.text && !msg.isDirect && !IgnoredChannels.includes(msg.channel)){
storeMessage(msg);
}
});
Slack.onReact(async (msg)=>{
if (msg.item.type != 'message') return;
return await uploadToDatabase('reactions', {
ts : msg.ts,
emoji : msg.reaction,
user : {
id : msg.user_id,
name : msg.user,
},
channel : {
id : msg.channel_id,
name : msg.channel,
},
msg : {
channel_id : msg.item.channel,
ts : msg.item.ts,
},
});
});