-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
214 lines (204 loc) · 7.71 KB
/
index.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
const fs = require('fs');
const Discord = require('discord.js');
const bot = new Discord.Client();
const user = new Discord.Client();
const tokens = JSON.parse(fs.readFileSync('./tokens.json').toString());
user.login(tokens.user);
let sddMessages = {};
let fetchedCount = 0;
bot.on('ready', () => {
console.log('Connected');
if (fs.existsSync('./sddMessages.json')) {
console.log('loading existing messages from sddMessages.json');
sddMessages = JSON.parse(fs.readFileSync('./sddMessages.json'));
}
/** @type {Discord.Guild} */
const sdd = bot.guilds.filter(e => e.name === 'Salon des développeurs').first();
/* @type {Discord.Collection} */
const chans = sdd.channels.filter(e => e instanceof Discord.TextChannel && e.name !== 'bots' && e.id !== '214888058862960651');
chans.map(chan => fetchAfter(chan, sddMessages[chan.name], messages => {
sddMessages[chan.name] = messages;
fetchedCount++;
console.log('\r\x1b[32m#' + chan.name, '\x1b[0mfetched');
process.stdout.write(fetchedCount + '/' + chans.size);
if (fetchedCount === chans.size) {
console.log('\nRemoving duplicate messages');
const noDupesMessages = Object.assign(
...Object.entries(sddMessages).map(([key, value]) => ({
[key]: [...value.reduce((map, value) => map.set(value.id, value), new Map()).values()]
}))
);
process.stdout.write('Writing \x1b[32m./sddMessages.json\x1b[0m\t');
fs.writeFileSync('./sddMessages.json', JSON.stringify(noDupesMessages));
console.log('DONE');
doStats(noDupesMessages);
process.exit(0);
}
}));
});
/**
* Callback for fetching functions
*
* @callback fetchResultCallback
* @param {Object[]} messages
*/
/**
* Fetch every msg after a given one
*
* @param {Discord.TextChannel} channel the channel to fetch the messages on
* @param {Object[]} knownMessages list of known messages, as objects
* @param {fetchResultCallback} callback
*/
const fetchAfter = (channel, knownMessages, callback) => {
if (!knownMessages || !knownMessages.length) {
console.log(channel.name, 'has never been fetched before. Doing a complete fetch');
fetchAllMessages(channel, callback);
return;
}
let allMessages = knownMessages;
const fetchCallback = messages => {
allMessages = allMessages.concat(messages.map(m => {
return {
id: m.id,
content: m.content,
author: m.author.id,
date: m.createdTimestamp
};
}));
// console.log(messages.size, allMessages.length);
if (messages.size === 100) channel.fetchMessages({
limit: 100,
after: messages.first().id
}).then(fetchCallback).catch(err => console.trace(err));
else callback(allMessages);
};
channel.fetchMessages({
limit: 100,
after: allMessages[0].id
}).then(fetchCallback).catch(err => console.trace(err));
};
/**
* Fetches all the messages from a given channel
*
* @param {Discord.TextChannel} channel
* @param {fetchResultCallback} callback
*/
const fetchAllMessages = (channel, callback) => {
/* @type {Discord.Collection} */
let fullList = new Discord.Collection();
const fetchCallback = messages => {
fullList = fullList.concat(messages);
if (messages.size === 100) channel.fetchMessages({
limit: 100,
before: messages.last().id
}).then(fetchCallback).catch(err => console.trace(err));
// If size is less than 100, we fetched all the messages
else callback(fullList.array().map(m => {
return {
id: m.id,
content: m.content,
author: m.author.id,
date: m.createdTimestamp
};
}));
};
channel.fetchMessages({
limit: 100
}).then(fetchCallback);
};
/**
* Generate statistics about the messages fetched
*
* @param {Object} channels
*/
const doStats = (channels) => {
const now = Date.now();
const messages = Object.keys(channels).map(channel => channels[channel]).reduce((acc, val) => acc.concat(val), []);
const lastWeekMessages = messages.filter(({
date
}) => now - date < 7 * 24 * 60 * 60 * 1000);
const authorActivity = lastWeekMessages.reduce((acc, msg) => ({ ...acc,
[msg.author]: (acc[msg.author] || 0) + 1
}), {});
const authorActivityArray = Object.keys(authorActivity).map(author => ({
author,
messages: authorActivity[author]
}));
const ranking = authorActivityArray.sort(({
messages: a
}, {
messages: b
}) => b - a).slice(0, 10);
// Add author name, avatar, nickname and other
const sddMembers = bot.guilds.get('186941943941562369').members;
const rankingWithAuthorInfo = ranking.map(({
author,
messages
}) => ({
author,
messages,
id: sddMembers.get(author).user.username,
nickname: sddMembers.get(author).displayName,
avatar: sddMembers.get(author).user.avatarURL
}));
process.stdout.write('Writing \x1b[32m./lastWeekStats.json\x1b[0m\t');
fs.writeFileSync('./lastWeekStats.json', JSON.stringify(rankingWithAuthorInfo));
console.log('DONE');
displayRanking(ranking);
};
/**
* Display the ranking on the command line
*
* @param {Object[]} ranking the ranking as an ordered array of authors and their amount of messages
*/
const displayRanking = ranking => {
const sddMembers = bot.guilds.get('186941943941562369').members;
const rankingWithUsername = ranking.reduce((acc, {
author,
messages
}) => {
const member = sddMembers.get(author);
return [...acc, [member.nickname || member.user.username, messages]];
}, []);
const maxLength = Math.max(...rankingWithUsername.map(el => el[0].length)) + 2;
const maxAmount = Math.max(...rankingWithUsername.map(el => el[1]));
console.log('┌' + '─'.repeat(maxLength) + '┬' + '─'.repeat(maxAmount.toString().length + 2) + '┐');
const verticalDelimiter = '│';
rankingWithUsername.forEach(([username, messages]) => {
console.log(verticalDelimiter +
' '.repeat(Math.floor((maxLength - username.length) / 2)) +
username +
' '.repeat(Math.ceil((maxLength - username.length) / 2)) +
verticalDelimiter + ' ' +
messages +
' '.repeat(maxAmount.toString().length - messages.toString().length + 1) +
verticalDelimiter);
});
console.log('└' + '─'.repeat(maxLength) + '┴' + '─'.repeat(maxAmount.toString().length + 2) + '┘');
};
user.on('ready', () => {
user.guilds.first().fetchMembers().then(guild => doMembers(guild));
});
/**
* Saves a list of members and some informations about them
*
* @param {Discord.Guild} guild the guild with members fetched.
*/
const doMembers = (guild) => {
const membersInfoPromise = guild.members.filter(member => !member.user.bot).map(member =>
member.user.fetchProfile().then(results => ({
joined: member.joinedTimestamp,
highestRoleName: member.highestRole.name,
id: member.id,
name: member.user.username,
nickname: member.displayName,
connections: results.connections.map(({type, name}) => ({type, name}))
})).catch(error => console.log(error))
);
Promise.all(membersInfoPromise).then(results => {
process.stdout.write('Writing \x1b[32m./membersInfos.json\x1b[0m\t');
fs.writeFileSync('./membersInfos.json', JSON.stringify(results));
console.log('DONE');
bot.login(tokens.bot);
});
};