diff --git a/modules/ping-protection/commands/ping-protection.js b/modules/ping-protection/commands/ping-protection.js index bcb8e3c6..09798a8e 100644 --- a/modules/ping-protection/commands/ping-protection.js +++ b/modules/ping-protection/commands/ping-protection.js @@ -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 @@ -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 @@ -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 diff --git a/modules/ping-protection/commands/view-moderation-history.js b/modules/ping-protection/commands/view-moderation-history.js index 600eb19e..6fbf2df6 100644 --- a/modules/ping-protection/commands/view-moderation-history.js +++ b/modules/ping-protection/commands/view-moderation-history.js @@ -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 diff --git a/modules/ping-protection/commands/view-ping-history.js b/modules/ping-protection/commands/view-ping-history.js index d9384ef0..fb100fce 100644 --- a/modules/ping-protection/commands/view-ping-history.js +++ b/modules/ping-protection/commands/view-ping-history.js @@ -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 diff --git a/modules/ping-protection/configs/configuration.json b/modules/ping-protection/configs/configuration.json index cbae2498..0df1d5c3 100644 --- a/modules/ping-protection/configs/configuration.json +++ b/modules/ping-protection/configs/configuration.json @@ -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", @@ -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 }, diff --git a/modules/ping-protection/core/localHelpers.js b/modules/ping-protection/core/localHelpers.js index 628a2570..d6b7f0ad 100644 --- a/modules/ping-protection/core/localHelpers.js +++ b/modules/ping-protection/core/localHelpers.js @@ -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]; } diff --git a/modules/ping-protection/core/moderation.js b/modules/ping-protection/core/moderation.js index 7f624f10..bd9c2e3d 100644 --- a/modules/ping-protection/core/moderation.js +++ b/modules/ping-protection/core/moderation.js @@ -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) { @@ -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 = []; @@ -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}` })); } } diff --git a/modules/ping-protection/core/toggle.js b/modules/ping-protection/core/toggle.js index 807d0de3..1b1db129 100644 --- a/modules/ping-protection/core/toggle.js +++ b/modules/ping-protection/core/toggle.js @@ -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; @@ -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(() => {}); } diff --git a/modules/ping-protection/events/botReady.js b/modules/ping-protection/events/botReady.js index b9468f11..b267e54a 100644 --- a/modules/ping-protection/events/botReady.js +++ b/modules/ping-protection/events/botReady.js @@ -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); diff --git a/modules/ping-protection/events/messageCreate.js b/modules/ping-protection/events/messageCreate.js index 35d1fef0..dd3b06a4 100644 --- a/modules/ping-protection/events/messageCreate.js +++ b/modules/ping-protection/events/messageCreate.js @@ -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))) || @@ -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'), @@ -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; diff --git a/tests/ping-protection/botReady.test.js b/tests/ping-protection/botReady.test.js index 598d9b4f..87e93d36 100644 --- a/tests/ping-protection/botReady.test.js +++ b/tests/ping-protection/botReady.test.js @@ -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); }); \ No newline at end of file diff --git a/tests/ping-protection/command.test.js b/tests/ping-protection/command.test.js index 6a8d5aa4..a9d37788 100644 --- a/tests/ping-protection/command.test.js +++ b/tests/ping-protection/command.test.js @@ -119,11 +119,12 @@ describe('user subcommands', () => { expect(mockPanel).toHaveBeenCalledWith(interaction.client, user); }); - test('triggers easter egg when checking the bot itself in user.history', async () => { + test('triggers easter egg when checking the bot itself in user.history with botHistoryEasterEgg enabled', async () => { const interaction = makeInteraction({ group: 'user', sub: 'history', - user: {id: 'botId'} + user: {id: 'botId'}, + config: {botHistoryEasterEgg: true} }); interaction.client.user = {id: 'botId'}; await runCommand(interaction); @@ -131,11 +132,24 @@ describe('user subcommands', () => { expect(interaction.reply.mock.calls[0][0].content).toContain('ping-protection.meme-bot-history'); }); - test('triggers easter egg when checking the bot itself in user.actions-history', async () => { + test('generates history when checking the bot itself in user.history with botHistoryEasterEgg disabled', async () => { + const interaction = makeInteraction({ + group: 'user', + sub: 'history', + user: {id: 'botId'}, + config: {botHistoryEasterEgg: false} + }); + interaction.client.user = {id: 'botId'}; + await runCommand(interaction); + expect(mockHistory).toHaveBeenCalledWith(interaction.client, 'botId', 1); + }); + + test('triggers easter egg when checking the bot itself in user.actions-history with botHistoryEasterEgg enabled', async () => { const interaction = makeInteraction({ group: 'user', sub: 'actions-history', - user: {id: 'botId'} + user: {id: 'botId'}, + config: {botHistoryEasterEgg: true} }); interaction.client.user = {id: 'botId'}; await runCommand(interaction); @@ -143,6 +157,18 @@ describe('user subcommands', () => { expect(interaction.reply.mock.calls[0][0].content).toContain('ping-protection.meme-bot-history'); }); + test('generates actions history when checking the bot itself in user.actions-history with botHistoryEasterEgg disabled', async () => { + const interaction = makeInteraction({ + group: 'user', + sub: 'actions-history', + user: {id: 'botId'}, + config: {botHistoryEasterEgg: false} + }); + interaction.client.user = {id: 'botId'}; + await runCommand(interaction); + expect(mockActions).toHaveBeenCalledWith(interaction.client, 'botId', 1); + }); + test('blocks user.panel for users without ManageGuild or Admin', async () => { const interaction = makeInteraction({ group: 'user', @@ -155,18 +181,33 @@ describe('user subcommands', () => { expect(interaction.reply.mock.calls[0][0].content).toContain('no-permission'); }); - test('triggers easter egg when checking the bot itself in user.panel', async () => { + test('triggers easter egg when checking the bot itself in user.panel with botHistoryEasterEgg enabled', async () => { const interaction = makeInteraction({ group: 'user', sub: 'panel', user: {id: 'botId'}, - permissions: ['Administrator'] + permissions: ['Administrator'], + config: {botHistoryEasterEgg: true} }); interaction.client.user = {id: 'botId'}; await runCommand(interaction); expect(mockPanel).not.toHaveBeenCalled(); expect(interaction.reply.mock.calls[0][0].content).toContain('ping-protection.meme-bot-history'); }); + + test('generates panel when checking the bot itself in user.panel with botHistoryEasterEgg disabled', async () => { + const user = {id: 'botId'}; + const interaction = makeInteraction({ + group: 'user', + sub: 'panel', + user, + permissions: ['Administrator'], + config: {botHistoryEasterEgg: false} + }); + interaction.client.user = {id: 'botId'}; + await runCommand(interaction); + expect(mockPanel).toHaveBeenCalledWith(interaction.client, user); + }); }); describe('toggle subcommand', () => { diff --git a/tests/ping-protection/messageCreate.test.js b/tests/ping-protection/messageCreate.test.js index 3746686b..8b7f6b6a 100644 --- a/tests/ping-protection/messageCreate.test.js +++ b/tests/ping-protection/messageCreate.test.js @@ -46,6 +46,8 @@ function makeConfig(over = {}) { protectAllUsersWithProtectedRole: false, allowReplyPings: false, selfPingConfiguration: 'Off', + selfPingEasterEgg: false, + botPingEasterEgg: false, ...over }; } @@ -59,15 +61,15 @@ function makeClient(config) { } function makeMessage({ - authorId = 'pinger', - bot = false, - users = [], - roles = [], - repliedUser = null, - members = [], - content = '', - memberRoles = [] - } = {}) { + authorId = 'pinger', + bot = false, + users = [], + roles = [], + repliedUser = null, + members = [], + content = '', + memberRoles = [] +} = {}) { const memberCollection = makeCollection(members); return { guild: { @@ -106,7 +108,7 @@ beforeEach(() => { describe('guards', () => { test('ignores messages before botReady', async () => { const client = makeClient(makeConfig()); - client.botReadyAt = undefined; + delete client.botReadyAt; await handler.run(client, makeMessage()); expect(mockProcessPing).not.toHaveBeenCalled(); }); @@ -221,10 +223,11 @@ describe('protected ping dispatch', () => { }); describe('self-ping', () => { - test('does nothing when selfPingConfiguration is Ignored', async () => { + test('does nothing when selfPingConfiguration is Ignored and easter egg is disabled', async () => { const client = makeClient(makeConfig({ protectedUsers: ['pinger'], - selfPingConfiguration: 'Ignored' + selfPingConfiguration: 'Ignored', + selfPingEasterEgg: false })); const msg = makeMessage({ authorId: 'pinger', @@ -234,14 +237,52 @@ describe('self-ping', () => { }] }); await handler.run(client, msg); + expect(msg.reply).not.toHaveBeenCalled(); + expect(mockSendWarning).not.toHaveBeenCalled(); + expect(mockProcessPing).not.toHaveBeenCalled(); + }); + + test('punishes when selfPingConfiguration is "Get punished like normal members" and easter egg is disabled', async () => { + const client = makeClient(makeConfig({ + protectedUsers: ['pinger'], + selfPingConfiguration: 'Get punished like normal members', + selfPingEasterEgg: false + })); + const msg = makeMessage({ + authorId: 'pinger', + users: [{ + id: 'pinger', + username: 'Me' + }] + }); + await handler.run(client, msg); + expect(mockSendWarning).toHaveBeenCalled(); + expect(mockProcessPing).toHaveBeenCalled(); + }); + + test('replies with an easter egg when selfPingEasterEgg is true regardless of selfPingConfiguration', async () => { + const client = makeClient(makeConfig({ + protectedUsers: ['pinger'], + selfPingConfiguration: 'Get punished like normal members', + selfPingEasterEgg: true + })); + const msg = makeMessage({ + authorId: 'pinger', + users: [{ + id: 'pinger', + username: 'Me' + }] + }); + await handler.run(client, msg); + expect(msg.reply).toHaveBeenCalled(); expect(mockSendWarning).not.toHaveBeenCalled(); expect(mockProcessPing).not.toHaveBeenCalled(); }); }); describe('bot ping easter egg', () => { - test('replies with an easter egg when a user pings the bot', async () => { - const client = makeClient(makeConfig()); + test('replies with an easter egg when a user pings the bot and botPingEasterEgg is true', async () => { + const client = makeClient(makeConfig({botPingEasterEgg: true})); client.user = {id: 'botId'}; const msg = makeMessage({ authorId: 'regularUser', @@ -263,8 +304,26 @@ describe('bot ping easter egg', () => { expect(mockSendWarning).not.toHaveBeenCalled(); }); + test('does not reply with an easter egg when botPingEasterEgg is false', async () => { + const client = makeClient(makeConfig({botPingEasterEgg: false})); + client.user = {id: 'botId'}; + const msg = makeMessage({ + authorId: 'regularUser', + users: [{ + id: 'botId', + username: 'SecurityBot' + }], + content: 'hello <@botId>' + }); + await handler.run(client, msg); + expect(msg.reply).not.toHaveBeenCalled(); + }); + test('ignores automatic reply without manual ping when allowReplyPings is true', async () => { - const client = makeClient(makeConfig({allowReplyPings: true})); + const client = makeClient(makeConfig({ + allowReplyPings: true, + botPingEasterEgg: true + })); client.user = {id: 'botId'}; const msg = makeMessage({ authorId: 'regularUser', @@ -282,6 +341,7 @@ describe('bot ping easter egg', () => { test('processes manual protected ping when replying to the bot with allowReplyPings enabled', async () => { const client = makeClient(makeConfig({ allowReplyPings: true, + botPingEasterEgg: true, protectedUsers: ['victim'] })); client.user = {id: 'botId'}; diff --git a/tests/ping-protection/pingProtectionLogic.test.js b/tests/ping-protection/pingProtectionLogic.test.js index aae594fc..8aa97c51 100644 --- a/tests/ping-protection/pingProtectionLogic.test.js +++ b/tests/ping-protection/pingProtectionLogic.test.js @@ -38,6 +38,14 @@ describe('isWhitelistedChannel', () => { })).toBe(true); }); + test('matches thread by grandparent (category) id', () => { + expect(pp.isWhitelistedChannel(cfg, { + id: '999', + parentId: '888', + parent: {parentId: '200'} + })).toBe(true); + }); + test('numeric ids in config still match string channel ids', () => { expect(pp.isWhitelistedChannel({ignoredChannels: [100]}, {id: '100'})).toBe(true); }); diff --git a/tests/ping-protection/render.test.js b/tests/ping-protection/render.test.js index 9a0f478b..88dac879 100644 --- a/tests/ping-protection/render.test.js +++ b/tests/ping-protection/render.test.js @@ -322,4 +322,134 @@ describe('syncNativeAutoMod', () => { await pp.syncNativeAutoMod(client); expect(guild.autoModerationRules.edit).toHaveBeenCalledWith('r1', expect.any(Object)); }); + + test('includes category channels (type 4) in exemptChannels and omits missing channels', async () => { + const channelCache = new Map([ + ['text1', {id: 'text1', type: 0}], + ['cat1', {id: 'cat1', type: 4}] + ]); + const guild = guildWith({existingRule: null}); + guild.channels.cache = channelCache; + const client = baseClient({}); + client.guildID = 'g1'; + client.guilds = {fetch: jest.fn().mockResolvedValue(guild)}; + client.configurations['ping-protection'].configuration = { + enableAutomod: true, + protectedRoles: [], + protectedUsers: ['user1'], + ignoredChannels: ['text1', 'cat1', 'deleted1'], + ignoredRoles: [] + }; + await pp.syncNativeAutoMod(client); + expect(guild.autoModerationRules.create).toHaveBeenCalled(); + const data = guild.autoModerationRules.create.mock.calls[0][0]; + expect(data.exemptChannels).toEqual(['text1', 'cat1']); + }); + + test('falls back to expanding category child channels if Discord rejects category IDs with 50035', async () => { + const channelCache = new Map([ + ['text1', {id: 'text1', type: 0}], + ['cat1', {id: 'cat1', type: 4}], + ['catChild1', {id: 'catChild1', type: 0, parentId: 'cat1'}], + ['catChild2', {id: 'catChild2', type: 2, parentId: 'cat1'}] + ]); + const apiError = Object.assign(new Error('Invalid Form Body'), {code: 50035}); + const guild = guildWith({ + existingRule: null, + ruleOps: { + create: jest.fn() + .mockRejectedValueOnce(apiError) + .mockResolvedValueOnce({}) + } + }); + guild.channels.cache = channelCache; + const client = baseClient({}); + client.guildID = 'g1'; + client.guilds = {fetch: jest.fn().mockResolvedValue(guild)}; + client.configurations['ping-protection'].configuration = { + enableAutomod: true, + protectedRoles: [], + protectedUsers: ['user1'], + ignoredChannels: ['text1', 'cat1'], + ignoredRoles: [] + }; + await pp.syncNativeAutoMod(client); + expect(guild.autoModerationRules.create).toHaveBeenCalledTimes(2); + expect(guild.autoModerationRules.create.mock.calls[0][0].exemptChannels).toEqual(['text1', 'cat1']); + expect(guild.autoModerationRules.create.mock.calls[1][0].exemptChannels).toEqual(['text1', 'catChild1', 'catChild2']); + }); + + test('does not deadlock when a protected user has an expired toggle pause row during sync', async () => { + const guild = guildWith({existingRule: null}); + const destroy = jest.fn().mockResolvedValue(); + const client = baseClient({ + models: { + UserPingPreference: { + findOne: jest.fn().mockResolvedValue({ + userId: 'user1', + disabledUntil: new Date(Date.now() - 10000) + }), + destroy + } + } + }); + client.guildID = 'g1'; + client.guilds = {fetch: jest.fn().mockResolvedValue(guild)}; + client.configurations['ping-protection'].configuration = { + enableAutomod: true, + allowProtectionToggle: true, + protectedRoles: [], + protectedUsers: ['user1'], + ignoredChannels: [], + ignoredRoles: [] + }; + await pp.syncNativeAutoMod(client); + expect(destroy).toHaveBeenCalledWith({where: {userId: 'user1'}}); + expect(guild.autoModerationRules.create).toHaveBeenCalled(); + const data = guild.autoModerationRules.create.mock.calls[0][0]; + expect(data.triggerMetadata.keywordFilter).toEqual(['<@user1>', '<@!user1>']); + }); + + test('adaptively caps <@!id> variants so all primary <@id> mentions fit up to 1000 entries', async () => { + const guild = guildWith({existingRule: null}); + const client = baseClient({}); + client.guildID = 'g1'; + client.guilds = {fetch: jest.fn().mockResolvedValue(guild)}; + const users = Array.from({length: 700}, (_, i) => `u${i}`); + client.configurations['ping-protection'].configuration = { + enableAutomod: true, + protectedRoles: [], + protectedUsers: users, + ignoredChannels: [], + ignoredRoles: [] + }; + await pp.syncNativeAutoMod(client); + expect(guild.autoModerationRules.create).toHaveBeenCalled(); + const keywords = guild.autoModerationRules.create.mock.calls[0][0].triggerMetadata.keywordFilter; + expect(keywords).toHaveLength(1000); + expect(keywords.slice(0, 700)).toEqual(users.map(u => `<@${u}>`)); + expect(keywords.slice(700)).toEqual(users.slice(0, 300).map(u => `<@!${u}>`)); + expect(client.logger.warn).not.toHaveBeenCalledWith(expect.stringContaining('log-automod-keyword-limit')); + }); + + test('warns and truncates when primary entries alone exceed 1000, omitting all <@!id> variants', async () => { + const guild = guildWith({existingRule: null}); + const client = baseClient({}); + client.guildID = 'g1'; + client.guilds = {fetch: jest.fn().mockResolvedValue(guild)}; + const users = Array.from({length: 1005}, (_, i) => `u${i}`); + client.configurations['ping-protection'].configuration = { + enableAutomod: true, + protectedRoles: [], + protectedUsers: users, + ignoredChannels: [], + ignoredRoles: [] + }; + await pp.syncNativeAutoMod(client); + expect(guild.autoModerationRules.create).toHaveBeenCalled(); + const keywords = guild.autoModerationRules.create.mock.calls[0][0].triggerMetadata.keywordFilter; + expect(keywords).toHaveLength(1000); + expect(keywords.every(k => !k.startsWith('<@!'))).toBe(true); + expect(client.logger.warn).toHaveBeenCalledWith(expect.stringContaining('log-automod-keyword-limit')); + }); }); \ No newline at end of file diff --git a/tests/ping-protection/viewModerationHistory.test.js b/tests/ping-protection/viewModerationHistory.test.js index 06c1d829..d16ad3c2 100644 --- a/tests/ping-protection/viewModerationHistory.test.js +++ b/tests/ping-protection/viewModerationHistory.test.js @@ -41,12 +41,17 @@ describe('View Moderation History context command', () => { }); }); - test('returns easter egg when targeting the bot itself', async () => { + test('returns easter egg when targeting the bot itself with botHistoryEasterEgg enabled', async () => { const reply = jest.fn().mockResolvedValue('ok'); const interaction = { client: { id: 'client', - user: {id: 'botId'} + user: {id: 'botId'}, + configurations: { + 'ping-protection': { + configuration: {botHistoryEasterEgg: true} + } + } }, targetUser: {id: 'botId'}, reply @@ -55,4 +60,23 @@ describe('View Moderation History context command', () => { expect(mockGenerateActionsResponse).not.toHaveBeenCalled(); expect(reply.mock.calls[0][0].content).toContain('ping-protection.meme-bot-history'); }); + + test('generates actions history when targeting the bot itself with botHistoryEasterEgg disabled', async () => { + const reply = jest.fn().mockResolvedValue('ok'); + const interaction = { + client: { + id: 'client', + user: {id: 'botId'}, + configurations: { + 'ping-protection': { + configuration: {botHistoryEasterEgg: false} + } + } + }, + targetUser: {id: 'botId'}, + reply + }; + await command.run(interaction); + expect(mockGenerateActionsResponse).toHaveBeenCalledWith(interaction.client, 'botId', 1); + }); }); \ No newline at end of file diff --git a/tests/ping-protection/viewPingHistory.test.js b/tests/ping-protection/viewPingHistory.test.js index 262c5728..dbec982e 100644 --- a/tests/ping-protection/viewPingHistory.test.js +++ b/tests/ping-protection/viewPingHistory.test.js @@ -41,12 +41,17 @@ describe('View Ping History context command', () => { }); }); - test('returns easter egg when targeting the bot itself', async () => { + test('returns easter egg when targeting the bot itself with botHistoryEasterEgg enabled', async () => { const reply = jest.fn().mockResolvedValue('ok'); const interaction = { client: { id: 'client', - user: {id: 'botId'} + user: {id: 'botId'}, + configurations: { + 'ping-protection': { + configuration: {botHistoryEasterEgg: true} + } + } }, targetUser: {id: 'botId'}, reply @@ -55,4 +60,23 @@ describe('View Ping History context command', () => { expect(mockGenerateHistoryResponse).not.toHaveBeenCalled(); expect(reply.mock.calls[0][0].content).toContain('ping-protection.meme-bot-history'); }); + + test('generates history when targeting the bot itself with botHistoryEasterEgg disabled', async () => { + const reply = jest.fn().mockResolvedValue('ok'); + const interaction = { + client: { + id: 'client', + user: {id: 'botId'}, + configurations: { + 'ping-protection': { + configuration: {botHistoryEasterEgg: false} + } + } + }, + targetUser: {id: 'botId'}, + reply + }; + await command.run(interaction); + expect(mockGenerateHistoryResponse).toHaveBeenCalledWith(interaction.client, 'botId', 1); + }); }); \ No newline at end of file