Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 6 additions & 3 deletions modules/ping-protection/commands/ping-protection.js
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,8 @@ module.exports.subcommands = {
});
}
const user = interaction.options.getUser('user');
if (user.id === interaction.client.user?.id) {
const config = interaction.client.configurations['ping-protection']?.['configuration'] || {};
if (config.botHistoryEasterEgg && user.id === interaction.client.user?.id) {
return interaction.reply({
content: localize('ping-protection', 'meme-bot-history'),
flags: MessageFlags.Ephemeral
Expand All @@ -54,7 +55,8 @@ module.exports.subcommands = {
});
}
const user = interaction.options.getUser('user');
if (user.id === interaction.client.user?.id) {
const config = interaction.client.configurations['ping-protection']?.['configuration'] || {};
if (config.botHistoryEasterEgg && user.id === interaction.client.user?.id) {
return interaction.reply({
content: localize('ping-protection', 'meme-bot-history'),
flags: MessageFlags.Ephemeral
Expand All @@ -75,7 +77,8 @@ module.exports.subcommands = {
});
}
const user = interaction.options.getUser('user');
if (user.id === interaction.client.user?.id) {
const config = interaction.client.configurations['ping-protection']?.['configuration'] || {};
if (config.botHistoryEasterEgg && user.id === interaction.client.user?.id) {
return interaction.reply({
content: localize('ping-protection', 'meme-bot-history'),
flags: MessageFlags.Ephemeral
Expand Down
3 changes: 2 additions & 1 deletion modules/ping-protection/commands/view-moderation-history.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,8 @@ module.exports.config = {
* the output (embed + pagination buttons) is identical for the targeted user.
*/
module.exports.run = async function (interaction) {
if (interaction.targetUser.id === interaction.client.user?.id) {
const config = interaction.client.configurations?.['ping-protection']?.['configuration'] || {};
if (config.botHistoryEasterEgg && interaction.targetUser.id === interaction.client.user?.id) {
return interaction.reply({
content: localize('ping-protection', 'meme-bot-history'),
flags: MessageFlags.Ephemeral
Expand Down
3 changes: 2 additions & 1 deletion modules/ping-protection/commands/view-ping-history.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,8 @@ module.exports.config = {
* (embed + pagination buttons) is identical for the targeted user.
*/
module.exports.run = async function (interaction) {
if (interaction.targetUser.id === interaction.client.user?.id) {
const config = interaction.client.configurations?.['ping-protection']?.['configuration'] || {};
if (config.botHistoryEasterEgg && interaction.targetUser.id === interaction.client.user?.id) {
return interaction.reply({
content: localize('ping-protection', 'meme-bot-history'),
flags: MessageFlags.Ephemeral
Expand Down
34 changes: 31 additions & 3 deletions modules/ping-protection/configs/configuration.json
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,11 @@
"icon": "fas fa-gears",
"displayName": "Ping rules"
},
{
"id": "easterEggs",
"icon": "fa-solid fa-egg",
"displayName": "Easter eggs"
},
{
"id": "automod",
"icon": "far fa-robot",
Expand Down Expand Up @@ -107,16 +112,39 @@
"type": "select",
"content": [
"Get punished like normal members",
"Ignored",
"Get fun easter eggs when pinging themselves"
"Ignored"
],
"default": "Ignored"
},
{
"name": "selfPingEasterEgg",
"category": "easterEggs",
"humanName": "Enable self-ping easter egg",
"description": "Adds a fun twist to protected users. When enabled, protected users pinging themselves see a fun easter egg. Overrides self-ping configuration setting - if enabled, no logging is done.",
"type": "boolean",
"default": false
},
{
"name": "botPingEasterEgg",
"category": "easterEggs",
"humanName": "Enable bot-ping easter egg",
"description": "When enabled, users pinging the bot will see a fun easter egg.",
"type": "boolean",
"default": false
},
{
"name": "botHistoryEasterEgg",
"category": "easterEggs",
"humanName": "Enable bot-history easter egg",
"description": "When enabled, checking the ping or moderation history of the bot will show a fun easter egg instead of an empty history.",
"type": "boolean",
"default": false
},
{
"name": "enableAutomod",
"category": "automod",
"humanName": "Enable AutoMod",
"description": "If enabled, the bot will utilise Discord's native AutoMod to block the message with a ping of a protected user/role. Warning: AutoMod does not support whitelisted categories due to limitations in Discord's AutoMod system - instead, it will still block the message but not log it in the history.",
"description": "If enabled, the bot will utilise Discord's native AutoMod to block the message with a ping of a protected user/role.",
"type": "boolean",
"default": true
},
Expand Down
1 change: 1 addition & 0 deletions modules/ping-protection/core/localHelpers.js
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,7 @@ function getWhitelistedChannelIds(channel) {
const ids = new Set();
if (channel.id) ids.add(channel.id);
if (channel.parentId) ids.add(channel.parentId);
if (channel.parent?.parentId) ids.add(channel.parent.parentId);
return [...ids];
}

Expand Down
81 changes: 62 additions & 19 deletions modules/ping-protection/core/moderation.js
Original file line number Diff line number Diff line change
Expand Up @@ -130,13 +130,14 @@ async function executeSyncNativeAutoMod(client) {
}

// Exclude users who currently have their protection paused
const activeUserIds = [];
for (const id of protectedIdsSet) {
if (config.allowProtectionToggle) {
const isToggledOff = await isProtectionToggledOff(client, id);
const isToggledOff = await isProtectionToggledOff(client, id, {syncAutoMod: false});
if (isToggledOff) continue;
}
activeUserIds.push(id);
keywords.push(`<@${id}>`);
keywords.push(`<@!${id}>`);
}

if (keywords.length === 0) {
Expand All @@ -149,6 +150,12 @@ async function executeSyncNativeAutoMod(client) {
if (keywords.length > 1000) {
client.logger.warn(localize('ping-protection', 'log-automod-keyword-limit'));
keywords.splice(1000);
} else {
// Add legacy <@!id> nickname mention variants only while within Discord's 1000-entry limit
for (const id of activeUserIds) {
if (keywords.length >= 1000) break;
keywords.push(`<@!${id}>`);
}
}

const actions = [];
Expand All @@ -163,30 +170,66 @@ async function executeSyncNativeAutoMod(client) {
actions.push({type: 2, metadata: {channel: alertChannelId}});
}

const exactIgnoredChannels = (config.ignoredChannels || []).filter(channelId => {
function resolveExemptChannels(expandCategories = false) {
const result = new Set();
for (const channelId of config.ignoredChannels || []) {
const channel = guild.channels.cache.get(channelId);
if (!channel) continue;
if (expandCategories && channel.type === 4) {
if (typeof guild.channels.cache.forEach === 'function') {
guild.channels.cache.forEach(child => {
if (child.parentId === channelId && child.type !== 4) {
result.add(child.id);
}
});
}
} else {
result.add(channelId);
}
}
return [...result];
}

const hasCategoryExemption = (config.ignoredChannels || []).some(channelId => {
const channel = guild.channels.cache.get(channelId);
return channel && channel.type !== 4;
return channel && channel.type === 4;
});

const ruleData = {
name: 'Ping Protection System',
eventType: 1,
triggerType: 1,
triggerMetadata: {keywordFilter: keywords},
actions,
enabled: true,
exemptRoles: config.ignoredRoles || [],
exemptChannels: exactIgnoredChannels
};
function buildRuleData(exemptChannels) {
return {
name: 'Ping Protection System',
eventType: 1,
triggerType: 1,
triggerMetadata: {keywordFilter: keywords},
actions,
enabled: true,
exemptRoles: config.ignoredRoles || [],
exemptChannels
};
}

if (existingRule) {
await guild.autoModerationRules.edit(existingRule.id, ruleData);
} else {
await guild.autoModerationRules.create(ruleData);
async function saveRule(ruleData) {
if (existingRule) {
await guild.autoModerationRules.edit(existingRule.id, ruleData);
} else {
await guild.autoModerationRules.create(ruleData);
}
}

try {
await saveRule(buildRuleData(resolveExemptChannels(false)));
} catch (saveError) {
// Fall back to expanding category channels if Discord rejects category IDs directly in exempt_channels
if (saveError.code === 50035 && hasCategoryExemption) {
await saveRule(buildRuleData(resolveExemptChannels(true).slice(0, 50)));
} else {
throw saveError;
}
}
} catch (error) {
const details = error.rawError?.errors ? ` (${JSON.stringify(error.rawError.errors)})` : '';
client.logger.error(localize('ping-protection', 'log-automod-sync-failed', {
e: error.message
e: `${error.message}${details}`
}));
}
}
Expand Down
4 changes: 2 additions & 2 deletions modules/ping-protection/core/toggle.js
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ function clearPauseExpiryTimer(userId) {
}

// Checks if a target user has currently paused their ping protection
async function isProtectionToggledOff(client, userId) {
async function isProtectionToggledOff(client, userId, {syncAutoMod = true} = {}) {
if (!userId) return false;
const model = client.models['ping-protection']?.['UserPingPreference'];
if (!model) return false;
Expand All @@ -78,7 +78,7 @@ async function isProtectionToggledOff(client, userId) {
clearPauseExpiryTimer(rawUserId);
await model.destroy({where: {userId: rawUserId}}).catch(() => {});
const config = client.configurations['ping-protection']?.['configuration'] || {};
if (config.enableAutomod) {
if (syncAutoMod && config.enableAutomod) {
const {syncNativeAutoMod} = require('./moderation');
await syncNativeAutoMod(client).catch(() => {});
}
Expand Down
18 changes: 15 additions & 3 deletions modules/ping-protection/events/botReady.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,13 +10,25 @@ const {
const schedule = require('node-schedule');

module.exports.run = async function (client) {
await enforceRetention(client);
try {
await enforceRetention(client);
} catch (error) {
client.logger?.warn?.(`[Ping Protection] Startup retention failed: ${error.message}`);
}
try {
await scheduleActiveToggleExpirations(client);
} catch (error) {
client.logger?.warn?.(`[Ping Protection] Startup toggle schedule failed: ${error.message}`);
}
await syncNativeAutoMod(client);
await scheduleActiveToggleExpirations(client);

// Daily job
const job = schedule.scheduleJob('0 3 * * *', async () => {
await enforceRetention(client);
try {
await enforceRetention(client);
} catch (error) {
client.logger?.warn?.(`[Ping Protection] Scheduled retention failed: ${error.message}`);
}
await syncNativeAutoMod(client);
});
client.jobs.push(job);
Expand Down
8 changes: 5 additions & 3 deletions modules/ping-protection/events/messageCreate.js
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,7 @@ module.exports.run = async function (client, message) {
// Easter egg when a user pings the bot
const botId = client.user?.id;
let shouldSendBotMeme = Boolean(
config.botPingEasterEgg &&
botId && (
(typeof message.mentions.users.has === 'function' && message.mentions.users.has(botId)) ||
(typeof message.mentions.users.get === 'function' && Boolean(message.mentions.users.get(botId))) ||
Expand Down Expand Up @@ -112,9 +113,8 @@ module.exports.run = async function (client, message) {

if (!target) return;

// Funny easter egg when they ping themselves
if (target.id === message.author.id && config.selfPingConfiguration === 'Ignored') return;
if (target.id === message.author.id && config.selfPingConfiguration === 'Get fun easter eggs when pinging themselves') {
// Self-ping handling: easter egg overrides self-ping configuration and does no logging
if (target.id === message.author.id && config.selfPingEasterEgg) {
const secretChance = 0.01; // Secret for a reason.. (1% chance)
const standardMemes = [
localize('ping-protection', 'meme-why'),
Expand Down Expand Up @@ -155,6 +155,8 @@ module.exports.run = async function (client, message) {
return;
}

if (target.id === message.author.id && config.selfPingConfiguration === 'Ignored') return;

await sendPingWarning(client, message, target, config);

const isRole = !target.username;
Expand Down
10 changes: 10 additions & 0 deletions tests/ping-protection/botReady.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -43,4 +43,14 @@ test('the scheduled job re-runs retention and automod sync', async () => {
await cron();
expect(mockEnforce).toHaveBeenCalledTimes(1);
expect(mockSync).toHaveBeenCalledTimes(1);
});

test('still runs automod sync on startup if enforceRetention throws', async () => {
mockEnforce.mockRejectedValueOnce(new Error('db fail'));
const client = {
jobs: [],
logger: {warn: jest.fn()}
};
await handler.run(client);
expect(mockSync).toHaveBeenCalledTimes(1);
});
Loading
Loading