forked from typeofweb-org/typeofweb-discord-bot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcount-messages.ts
128 lines (107 loc) · 3.42 KB
/
count-messages.ts
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
import Discord, { Intents } from 'discord.js';
import fetch from 'node-fetch';
import { getConfig } from './src/config';
import { getStatsCollection, initDb } from './src/db';
import { getWeekNumber } from './src/utils';
/* eslint-disable @typescript-eslint/no-unsafe-call */
/* eslint-disable @typescript-eslint/no-unsafe-member-access */
if (process.env.NODE_ENV !== 'test') {
require('dotenv').config();
}
const API_URL = `https://discord.com/api/v9`;
const GUILD_ID = `440163731704643589`;
const personalToken = getConfig('PERSONAL_TOKEN');
async function init() {
// Monday
if (new Date().getDay() !== 1) {
console.log('Not Monday – nothing to do here!');
process.exit(0);
}
const intents = new Intents([
Intents.NON_PRIVILEGED, // include all non-privileged intents, would be better to specify which ones you actually need
'GUILD_MEMBERS', // lets you request guild members (i.e. fixes the issue)
]);
const client = new Discord.Client({ ws: { intents } });
await client.login(getConfig('DISCORD_BOT_TOKEN'));
const guild = await client.guilds.fetch(GUILD_ID);
const members = await guild.members.fetch({});
const db = await initDb();
const statsCollection = getStatsCollection(db);
const [year, week] = getWeekNumber(new Date());
const yearWeek = `${year}-${week}`;
await members.reduce(async (acc, member) => {
await acc;
if (member.deleted) {
// console.log(`Skipping… member.deleted`);
return acc;
}
const existingMember = await statsCollection.findOne({
memberId: member.id,
});
if (existingMember && !existingMember.messagesCount) {
// console.log(`Skipping… existing`);
return acc;
}
const countedThisWeek = await statsCollection.count({
memberId: member.id,
yearWeek,
});
if (countedThisWeek) {
// console.log(`Skipping… countedThisWeek`);
return acc;
}
const messagesCount = await getMemberMessagesCount(member.id);
if (!messagesCount) {
// console.log(`Skipping… !messagesCount`);
return acc;
}
const result = await statsCollection.updateOne(
{
memberId: member.id,
yearWeek,
},
{
$set: {
memberId: member.id,
memberName: member.displayName,
messagesCount,
updatedAt: new Date(),
yearWeek,
},
},
{ upsert: true },
);
console.log({ memberId: member.id, memberName: member.displayName, messagesCount, result });
}, Promise.resolve());
}
init()
.then(() => {
process.exit(0);
})
.catch((err) => {
console.error(err);
process.exit(1);
});
type Response =
| { readonly total_results?: number; readonly retry_after?: undefined }
| { readonly total_results?: undefined; readonly retry_after: number };
export async function getMemberMessagesCount(memberId: string): Promise<number | undefined> {
const res = await fetch(`${API_URL}/guilds/${GUILD_ID}/messages/search?author_id=${memberId}`, {
headers: {
authorization: personalToken,
},
method: 'GET',
});
const json = (await res.json()) as Response;
if (json.retry_after) {
console.log(json);
await wait(json.retry_after * 1000);
return getMemberMessagesCount(memberId);
}
// try to overcome rate limiting
await wait(1000);
return json.total_results;
}
function wait(ms: number) {
return new Promise((resolve) => setTimeout(resolve, ms));
}