-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
233 lines (198 loc) · 8.03 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
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
require('dotenv').config();
const { Client, Collection, Events, REST, Routes, GatewayIntentBits } = require('discord.js');
const fs = require('node:fs');
const path = require('node:path');
const wait = require('node:timers/promises').setTimeout;
const DiscordClient = new Client({
intents: GatewayIntentBits.Guilds,
messageCacheMaxSize: 0,
disableMentions: 'everyone',
});
DiscordClient.commands = new Collection();
const commands = [];
// Grab all the command files from the commands directory you created earlier
const commandsPath = path.join(__dirname, 'commands');
const commandFiles = fs.readdirSync(commandsPath).filter((file) => file.endsWith('.js'));
// Loop through the command files and add them to the commands collection and
// discord.commands
for (const file of commandFiles) {
const filePath = path.join(commandsPath, file);
const fileCommands = require(filePath);
const command = require(`./commands/${file}`);
DiscordClient.commands.set(fileCommands.data.name, fileCommands);
commands.push(command.data.toJSON());
}
// REST
const rest = new REST({ version: '10' }).setToken(process.env.TOKEN);
(async () => {
try {
console.log('Started refreshing application (/) commands.');
// Make commands global
await rest.put(Routes.applicationCommands(process.env.CLIENTID), { body: commands });
console.log('Successfully reloaded application (/) commands.');
} catch (error) {
console.error(error);
}
})();
const eventsPath = path.join(__dirname, 'events');
const eventFiles = fs.readdirSync(eventsPath).filter((file) => file.endsWith('.js'));
for (const file of eventFiles) {
const filePath = path.join(eventsPath, file);
const event = require(filePath);
if (event.once) {
DiscordClient.once(event.name, (...args) => event.execute(...args));
} else {
DiscordClient.on(event.name, (...args) => event.execute(...args));
}
}
const DelayBetween = 60 * 1000;
const DayMs = 24 * 60 * 60 * 1000;
const InitialSpread = 60 * 60 * 1000;
const RecurringSpread = 30 * 60 * 1000;
const IntervalExtension = DayMs / 2;
const MinInterval = 10 * 60 * 1000; //(+RecurringSpread)
const TwoWeekOffset = 14 * 24 * 60 * 60 * 1000;
const ChannelConfigs = new Map();
function ChannelName(channel) {
return channel.guild != null ? channel.guild.name + ' #' + channel.name : '#' + channel.name;
}
function Log(msg) {
console.log(new Date().toTimeString().substring(0, 9) + msg);
}
async function Wipe(channelConfig, reWipe) {
let interval = channelConfig.int;
let channel = channelConfig.channel;
try {
let now = Date.now();
let wipeSnowstamp = (BigInt(now - 14200704e5 /*DISCORD_EPOCH*/ - channelConfig.ttl) << 22n).toString();
let twoWeeksAgo = now - TwoWeekOffset;
let messages = await channel.messages.fetch({ limit: 100, before: wipeSnowstamp }, false);
messages = messages.filter((message) => message.createdTimestamp > twoWeeksAgo); // because before and after are mutually
// exclusive in the query
let fetchSize = messages.size;
messages = messages.filter((message) => !message.pinned);
if (messages.size !== 0) {
Log(`Deleting ${messages.size} messages in ${ChannelName(channel)}`);
await channel.bulkDelete(messages);
if (interval > DayMs) channelConfig.int = interval = DayMs; // in case it was extended before
if (fetchSize === 100) {
channelConfig.t = setTimeout(Wipe, DelayBetween, channelConfig, true);
if (interval > MinInterval) channelConfig.int = Math.min(interval / 2, MinInterval);
return;
}
if (interval < DayMs) channelConfig.int = interval = Math.max(interval * 2, DayMs);
} else if (!reWipe) {
if (channelConfig.ttl < /*6 days*/ 518400000) {
if (interval < /*6 days*/ 518400000) {
channelConfig.int = interval += IntervalExtension;
}
} else if (interval >= DayMs) {
let messages = await channel.messages.fetch({ limit: 1, after: wipeSnowstamp }, false);
if (messages.size !== 0) interval = Math.max(messages.first().createdTimestamp + channelConfig.tll - now, DayMs);
else interval = channelConfig.ttl + DayMs;
}
}
} catch (err) {
// If we lack acccess or permissions, we'll log it.
if (err.code === 50013 || err.code === 50001) {
DeleteChannel(channel.id);
Log(`${ChannelName(channel)}: ${err.message}`);
// Post to channel that the bot is lacking required permissions.
channel.send(`${ChannelName(channel)}: ${err.message}`);
return;
} else console.error(err);
}
channelConfig.t = setTimeout(Wipe, interval + Math.random * RecurringSpread, channelConfig);
}
let MyId;
async function DeleteOldAnnounce(channel) {
try {
let pins = await channel.messages.fetchPinned(false);
let announcePin = pins.find((message) => message.author != null && message.author.id === MyId);
if (announcePin != null) await announcePin.delete();
} catch (err) {}
}
function AddChannel(matches, channel, announce) {
let param = matches.length === 1 ? matches[0].substring(9).trimStart() : matches.map((x) => x.substring(9).trimStart()).sort((a, b) => b.length - a.length)[0];
param = param === '' ? 7 : Math.min(12, Math.max(param, 1));
let channelConfig = { ttl: param * DayMs, int: DayMs, channel };
ChannelConfigs.set(channel.id, channelConfig);
channelConfig.t = setTimeout(Wipe, Math.random * InitialSpread, channelConfig, true);
Log(`Adding ${ChannelName(channel)} with a ${param} day wipe`);
if (announce) {
DeleteOldAnnounce(channel).then(() =>
channel
.send('The messages will be deleted after ' + (param === 1 ? 'one day' : param + ' days'))
.then((message) => message.pin().catch())
.catch()
);
}
}
function DeleteChannel(channelId) {
let channelConfig = ChannelConfigs.get(channelId);
if (channelConfig !== undefined) {
clearTimeout(channelConfig.t);
ChannelConfigs.delete(channelId);
Log('Deleting ' + ChannelName(channelConfig.channel));
return true;
}
return false;
}
const DeletebotRegex = /DeleteBot\s*(\d{1,3})?/gi;
function ProcessGuild(guild) {
for (let channel of guild.channels.cache.values()) {
let topic = channel.topic;
if (topic != null && topic.length >= 9) {
let matches = topic.match(DeletebotRegex);
if (matches !== null) {
AddChannel(matches, channel);
}
}
}
}
DiscordClient.on('ready', () => {
Log(`Logged in as ${DiscordClient.user.tag}!`);
DiscordClient.user.setActivity('Deleting messages', { type: 'WATCHING' });
MyId = DiscordClient.user.id;
DiscordClient.on('error', console.error);
for (let guild of DiscordClient.guilds.cache.values()) {
ProcessGuild(guild);
}
});
DiscordClient.on('channelDelete', (channel) => {
if (channel.type !== 'voice' && channel.type !== 'category') DeleteChannel(channel.id);
});
DiscordClient.on('guildDelete', (guild) => {
for (let channel of guild.channels.cache.values()) {
if (channel.type !== 'voice' && channel.type !== 'category') DeleteChannel(channel.id);
}
});
DiscordClient.on('guildCreate', ProcessGuild);
DiscordClient.on('channelUpdate', async (oldChannel, newChannel) => {
if (newChannel.type === 'voice' || newChannel.type === 'category' || oldChannel.topic === newChannel.topic) return;
let announceDelete = DeleteChannel(newChannel.id);
let topic = newChannel.topic;
if (topic != null && topic.length >= 9) {
let matches = topic.match(DeletebotRegex);
if (matches !== null) {
AddChannel(matches, newChannel, true);
announceDelete = false;
}
}
if (announceDelete) {
newChannel.send('The messages will not be automatically deleted').catch(console.error);
await DeleteOldAnnounce(newChannel);
}
});
DiscordClient.on('rateLimit', (rateLimitInfo) => {
if (rateLimitInfo.global) {
let time = rateLimitInfo.reset * 1000;
Log(`Rate limit exceeded. Reset at ${new Date(time).toLocaleString()}`);
setTimeout(() => {
Log('Rate limit cleared, resuming.');
}, time - Date.now());
}
});
const dbl = require('dblapi.js');
new dbl(process.env.DBLTOKEN, DiscordClient);
DiscordClient.login(process.env.TOKEN);