-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
358 lines (301 loc) · 12.3 KB
/
Copy pathindex.js
File metadata and controls
358 lines (301 loc) · 12.3 KB
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
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
"use strict";
const { EmbedBuilder, PermissionFlagsBits } = require("discord.js");
const automodCommand = require("./commands/automod");
const ruleSchema = require("./models/rule");
const whitelistSchema = require("./models/whitelist");
const { parseDuration } = require("./lib/parseDuration");
// In-memory spam history tracker
// Key: `${guildId}-${userId}` -> { timestamps: Array, lastContent: String, contentCount: Number }
const spamHistory = new Map();
async function load(ctx) {
// --- Register Models ----------------------------------------------------
const AutoModRule = ctx.defineModel("AutoModRule", ruleSchema);
const Whitelist = ctx.defineModel("Whitelist", whitelistSchema);
ctx.models = { AutoModRule, Whitelist };
// --- Register Commands --------------------------------------------------
ctx.registerCommand({
data: automodCommand.data,
execute: (interaction) => automodCommand.execute(interaction, ctx),
});
// --- Register Events ----------------------------------------------------
ctx.registerEvent("messageCreate", async (message, client) => {
try {
// Skip bot messages
if (message.author.bot) return;
// Skip DMs
if (!message.guild) return;
// Skip empty messages
if (!message.content) return;
// Bypass administrators and manage guild permission holders
if (message.member) {
const isBypass = message.member.permissions.has(PermissionFlagsBits.Administrator) ||
message.member.permissions.has(PermissionFlagsBits.ManageGuild);
if (isBypass) return;
}
// Respect the dashboard on/off toggle (settings.enabled). Defaults to
// on when unset so existing rule-based setups keep working.
const settings = (await ctx.db.getPluginConfig(message.guild.id, "adb-plugin-automod"))?.data || {};
if (settings.enabled === false) return;
// Retrieve active rules for this guild
const rules = await AutoModRule.find({ guildId: message.guild.id, enabled: true });
if (rules.length === 0) return;
// Priority order for checks: invite -> link -> caps -> mention -> emoji -> word -> spam
const typePriority = ["invite", "link", "caps", "mention", "emoji", "word", "spam"];
const activeRules = rules.sort((a, b) => typePriority.indexOf(a.type) - typePriority.indexOf(b.type));
for (const rule of activeRules) {
const ruleType = rule.type;
// Check if this channel or the user's roles are whitelisted for this rule type
const isExcluded = await isWhitelisted(message, ruleType, Whitelist);
if (isExcluded) continue;
let triggered = false;
let details = "";
if (ruleType === "invite") {
triggered = checkInvite(message);
if (triggered) details = "Message contained a Discord invite link";
} else if (ruleType === "link") {
triggered = checkLink(message, rule);
if (triggered) details = "Message contained a blocked link";
} else if (ruleType === "caps") {
triggered = checkCaps(message, rule);
if (triggered) details = `Caps percentage exceeded threshold (${rule.config?.threshold || 70}%)`;
} else if (ruleType === "mention") {
triggered = checkMention(message, rule);
if (triggered) details = `Mention count exceeded threshold (${rule.config?.threshold || 5})`;
} else if (ruleType === "emoji") {
triggered = checkEmoji(message, rule);
if (triggered) details = `Emoji count exceeded threshold (${rule.config?.threshold || 5})`;
} else if (ruleType === "word") {
triggered = checkWord(message, rule);
if (triggered) details = "Message contained a blocked word";
} else if (ruleType === "spam") {
triggered = checkSpam(message, rule);
if (triggered) details = "Spam detected (rapid/repeated messages or consecutive duplicate characters)";
}
if (triggered) {
await handleAction(ctx, message, rule, details);
break; // Stop running other filters after the first match
}
}
} catch (err) {
ctx.logger.error("Error in AutoMod messageCreate handler:", err);
}
});
ctx.logger.info("AutoMod plugin loaded successfully");
}
// --- Whitelist Checker -------------------------------------------------------
async function isWhitelisted(message, filterType, WhitelistModel) {
// Check channel whitelist
const channelWl = await WhitelistModel.findOne({
guildId: message.guild.id,
targetId: message.channel.id,
targetType: "channel",
filterType: { $in: [filterType, "all"] },
});
if (channelWl) return true;
// Check role whitelist
if (message.member && message.member.roles) {
const roleIds = Array.from(message.member.roles.cache.keys());
if (roleIds.length > 0) {
const roleWl = await WhitelistModel.findOne({
guildId: message.guild.id,
targetId: { $in: roleIds },
targetType: "role",
filterType: { $in: [filterType, "all"] },
});
if (roleWl) return true;
}
}
return false;
}
// --- Filter Functions --------------------------------------------------------
function checkInvite(message) {
const inviteRegex = /(discord\.(gg|io|me|li)\b)|(discord(?:app)?\.com\/invite\b)/i;
return inviteRegex.test(message.content);
}
function checkLink(message, rule) {
const content = message.content;
const urlRegex = /https?:\/\/(?:www\.)?([a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)+)/gi;
let match;
const links = [];
while ((match = urlRegex.exec(content)) !== null) {
links.push(match[1].toLowerCase());
}
if (links.length === 0) return false;
// Exclude Discord invites from link check (let invite filter handle them)
const inviteRegex = /(discord\.(gg|io|me|li)\b)|(discord(?:app)?\.com\/invite\b)/i;
const nonInviteLinks = links.filter((link) => {
return !inviteRegex.test("https://" + link);
});
if (nonInviteLinks.length === 0) return false;
const allowedDomains = rule.config?.words || [];
const hasBlockedLink = nonInviteLinks.some((domain) => {
return !allowedDomains.some((allowed) => {
const lowerAllowed = allowed.toLowerCase();
return domain === lowerAllowed || domain.endsWith("." + lowerAllowed);
});
});
return hasBlockedLink;
}
function checkCaps(message, rule) {
const content = message.content;
if (content.length < 10) return false;
const letters = content.replace(/[^a-zA-Z]/g, "");
if (letters.length < 5) return false;
const uppers = letters.replace(/[^A-Z]/g, "");
const ratio = (uppers.length / letters.length) * 100;
const threshold = rule.config?.threshold || 70;
return ratio > threshold;
}
function checkMention(message, rule) {
const threshold = rule.config?.threshold || 5;
return message.mentions.users.size > threshold;
}
function checkEmoji(message, rule) {
const threshold = rule.config?.threshold || 5;
const customEmojis = message.content.match(/<a?:\w+:\d+>/g) || [];
const unicodeEmojis = message.content.match(/\p{Emoji_Presentation}/gu) || [];
const total = customEmojis.length + unicodeEmojis.length;
return total > threshold;
}
function checkWord(message, rule) {
const words = rule.config?.words || [];
if (words.length === 0) return false;
const content = message.content.toLowerCase();
return words.some((word) => {
const lowerWord = word.toLowerCase();
const startsWithWildcard = lowerWord.startsWith("*");
const endsWithWildcard = lowerWord.endsWith("*");
let cleanWord = lowerWord;
if (startsWithWildcard) cleanWord = cleanWord.slice(1);
if (endsWithWildcard) cleanWord = cleanWord.slice(0, -1);
let escaped = cleanWord.replace(/[-\/\\^$*+?.()|[\]{}]/g, "\\$&");
escaped = escaped.replace(/\\\*/g, ".*");
let pattern = "";
if (!startsWithWildcard) {
pattern += "\\b";
}
pattern += escaped;
if (!endsWithWildcard) {
pattern += "\\b";
}
const regex = new RegExp(pattern, "i");
return regex.test(content);
});
}
function checkSpam(message, rule) {
const guildId = message.guild.id;
const userId = message.author.id;
const now = Date.now();
const config = rule.config || {};
const limit = config.threshold || 5;
const windowMs = (config.seconds || 5) * 1000;
const key = `${guildId}-${userId}`;
if (!spamHistory.has(key)) {
spamHistory.set(key, { timestamps: [], lastContent: "", contentCount: 0 });
}
const record = spamHistory.get(key);
// 1. Rapid messages check
record.timestamps.push(now);
record.timestamps = record.timestamps.filter((t) => now - t < windowMs);
if (record.timestamps.length > limit) {
return true;
}
// 2. Duplicate consecutive messages check
if (message.content === record.lastContent) {
record.contentCount++;
if (record.contentCount >= 3) {
return true;
}
} else {
record.lastContent = message.content;
record.contentCount = 1;
}
// 3. Repeated consecutive characters check
if (/(.)\1{14,}/.test(message.content)) {
return true;
}
return false;
}
// --- Action Handlers ---------------------------------------------------------
async function getLogChannel(guild, ctx) {
const automodConfig = (await ctx.db.getPluginConfig(guild.id, "adb-plugin-automod"))?.data || {};
if (automodConfig.logChannelId) {
const channel = await guild.channels.fetch(automodConfig.logChannelId).catch(() => null);
if (channel) return channel;
}
const modConfig = (await ctx.db.getPluginConfig(guild.id, "adb-plugin-moderation"))?.data || {};
if (modConfig.log_channel_id) {
const channel = await guild.channels.fetch(modConfig.log_channel_id).catch(() => null);
if (channel) return channel;
}
// Fallback lookup by name
if (guild.channels.cache) {
const channel = guild.channels.cache.find(
(c) => c.name === "mod-logs" || c.name === "automod-logs" || c.name === "logs",
);
if (channel) return channel;
}
return null;
}
async function logIncident(ctx, message, ruleType, action, details) {
const logChannel = await getLogChannel(message.guild, ctx);
if (!logChannel) return;
const embed = new EmbedBuilder()
.setColor(0xe74c3c)
.setTitle("AutoMod Violation")
.addFields(
{ name: "User", value: `${message.author.tag} (${message.author.id})`, inline: true },
{ name: "Channel", value: `<#${message.channel.id}>`, inline: true },
{ name: "Filter", value: `\`${ruleType}\``, inline: true },
{ name: "Action Taken", value: `\`${action}\``, inline: true },
)
.setTimestamp();
if (message.content) {
embed.addFields({ name: "Content", value: message.content.slice(0, 1024) });
}
if (details) {
embed.addFields({ name: "Details", value: details });
}
await logChannel.send({ embeds: [embed] }).catch(() => {});
}
async function handleAction(ctx, message, rule, details) {
const action = rule.action;
const ruleType = rule.type;
const guild = message.guild;
// Always delete the offending message
await message.delete().catch(() => {});
if (action === "warn") {
const profile = await ctx.db.getUserProfile(message.author.id, guild.id);
const newWarnings = (profile.warnings || 0) + 1;
await ctx.db.updateUserProfile(message.author.id, guild.id, { warnings: newWarnings });
const dmEmbed = new EmbedBuilder()
.setColor(0xf1c40f)
.setTitle("AutoMod Warning")
.setDescription(`You have been warned in **${guild.name}** for triggering the **${ruleType}** filter.`)
.addFields({ name: "Reason", value: details })
.setTimestamp();
await message.author.send({ embeds: [dmEmbed] }).catch(() => {});
await logIncident(ctx, message, ruleType, action, `Total Warnings: ${newWarnings} | ${details}`);
} else if (action === "mute" || action === "timeout") {
const member = message.member || await guild.members.fetch(message.author.id).catch(() => null);
if (member && member.moderatable) {
const durationStr = rule.config?.duration || (action === "mute" ? "10m" : "1h");
const durationMs = parseDuration(durationStr) || (10 * 60 * 1000);
await member.timeout(durationMs, `[AutoMod] Triggered ${ruleType} filter`).catch(() => {});
const dmEmbed = new EmbedBuilder()
.setColor(0xe74c3c)
.setTitle("AutoMod Timeout")
.setDescription(`You have been timed out in **${guild.name}** for **${durationStr}** for triggering the **${ruleType}** filter.`)
.addFields({ name: "Reason", value: details })
.setTimestamp();
await message.author.send({ embeds: [dmEmbed] }).catch(() => {});
await logIncident(ctx, message, ruleType, `${action} (${durationStr})`, details);
} else {
await logIncident(ctx, message, ruleType, `${action} (failed - not moderatable)`, `Could not timeout user: ${details}`);
}
} else {
// Log action (or delete)
await logIncident(ctx, message, ruleType, action, details);
}
}
module.exports = { load };