Skip to content

fix(bot): fix automod spam tracking and link filter false positives - #399

Merged
LucasSantana-Dev merged 2 commits into
mainfrom
fix/automod-link-false-positives
Mar 31, 2026
Merged

LucasSantana-Dev merged 2 commits into
mainfrom
fix/automod-link-false-positives

Conversation

@LucasSantana-Dev

@LucasSantana-Dev LucasSantana-Dev commented Mar 31, 2026 •

Copy link
Copy Markdown
Owner

Summary

  • Spam detection was broken: messageHandler always passed [Date.now()] (single timestamp) to checkSpam, so spam count never reached any threshold. Replaced with trackMessageAndCheckSpam() using a Redis sliding window list — spam detection now actually works
  • Link false positives: vercel.app, netlify.app, github.com, github.io, render.com added to balanced and light template allowedDomains — project showcases in #divulgue-se and similar channels no longer get deleted
  • New linkExemptChannels field: Channels can be excluded from the link filter specifically without disabling all automod checks. Prisma migration included

Root Causes

  1. messageHandler.ts:48-50 — checkSpam(guildId, userId, [Date.now()]) always passed a 1-element array. checkSpam counts timestamps within the time window — 1 never reaches threshold of 4/5/6/8. Spam detection has never triggered since initial implementation.
  2. AutoModSettings.allowedDomains in all templates only included YouTube/Twitch/Discord. Any vercel.app or github.com link would fail the whitelist check and get deleted.

Changes

  • packages/shared/src/services/AutoModService.ts — new trackMessageAndCheckSpam(), updated checkLinks() signature, expanded template domains, added linkExemptChannels to interface
  • packages/bot/src/handlers/messageHandler.ts — uses trackMessageAndCheckSpam(), passes message.channelId to checkLinks()
  • prisma/schema.prisma + migration — linkExemptChannels TEXT[] NOT NULL DEFAULT ARRAY[]::TEXT[]
  • packages/backend/tests/unit/services/AutoModService.test.ts — 9 new tests (5 for trackMessageAndCheckSpam, 4 for checkLinks channel exemption and allowed domain coverage)

Test plan

  • npm run test --workspace=packages/backend — 661 tests passing
  • npm run type:check — no errors
  • Apply Prisma migration on server: npx prisma migrate deploy

🤖 Generated with Claude Code

Summary by CodeRabbit

  • Bug Fixes

    • Fixed AutoMod spam detection to use a sliding window approach for more accurate threshold evaluation
    • Adjusted AutoMod link filter to reduce false positives by expanding trusted domains (GitHub, Vercel, Netlify, Render)
  • New Features

    • Added ability to exempt specific channels from link filtering while maintaining other AutoMod protections

- Replace broken checkSpam(guildId, userId, [Date.now()]) call in
  messageHandler with trackMessageAndCheckSpam() using Redis sliding
  window — spam detection was completely non-functional before this
- Add linkExemptChannels field to AutoModSettings schema so channels
  can be excluded from link checks without disabling all automod
- Pass message.channelId to checkLinks() to respect exempt channels
- Add vercel.app, netlify.app, github.com, github.io, render.com to
  balanced and light template allowedDomains (false positive fix)
- Add Prisma migration for linkExemptChannels column
@vercel

vercel Bot commented Mar 31, 2026 •

Copy link
Copy Markdown
Contributor

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated (UTC)
lucky Ready Ready Preview, Comment Mar 31, 2026 0:20am

Request Review

@coderabbitai

coderabbitai Bot commented Mar 31, 2026 •

Copy link
Copy Markdown

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 63599a75-1924-4555-bdce-3bfd72258159

📥 Commits

Reviewing files that changed from the base of the PR and between dec7466 and f417e80.

📒 Files selected for processing (6)
  • CHANGELOG.md
  • packages/backend/tests/unit/services/AutoModService.test.ts
  • packages/bot/src/handlers/messageHandler.ts
  • packages/shared/src/services/AutoModService.ts
  • prisma/migrations/20260330000000_add_automod_link_exempt_channels/migration.sql
  • prisma/schema.prisma
📜 Recent review details
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (2)
  • GitHub Check: Quality Gates
  • GitHub Check: SonarCloud Scan
🧰 Additional context used
📓 Path-based instructions (27)
prisma/migrations/**/*

📄 CodeRabbit inference engine (.cursor/rules/subagent-data.mdc)

Database migrations must be located in prisma/migrations/

Files:

  • prisma/migrations/20260330000000_add_automod_link_exempt_channels/migration.sql
prisma/schema.prisma

📄 CodeRabbit inference engine (.cursor/rules/subagent-data.mdc)

Schema definitions must be located in prisma/schema.prisma

Files:

  • prisma/schema.prisma
{CHANGELOG.md,README.md}

📄 CodeRabbit inference engine (.cursor/rules/agent-rules.mdc)

ALWAYS update CHANGELOG.md and README.md as changes are made.

Files:

  • CHANGELOG.md
CHANGELOG.md

📄 CodeRabbit inference engine (.cursor/rules/templates-examples.mdc)

CHANGELOG.md must be updated with all changes in pull requests

Always update CHANGELOG.md with all code changes

Update CHANGELOG.md with all changes, include breaking changes documentation, and reference issues and PRs

Files:

  • CHANGELOG.md
{CHANGELOG.md,docs/**}

📄 CodeRabbit inference engine (.cursor/rules/lucky-project.mdc)

Update CHANGELOG.md and relevant docs/ files when behavior or setup changes

Files:

  • CHANGELOG.md
**/*.{js,jsx,ts,tsx,vue,html}

📄 CodeRabbit inference engine (.cursor/rules/accessibility-openness.mdc)

Provide accessible UI components using semantic HTML and ARIA attributes where necessary

Files:

  • packages/bot/src/handlers/messageHandler.ts
  • packages/backend/tests/unit/services/AutoModService.test.ts
  • packages/shared/src/services/AutoModService.ts
**/*.{ts,tsx,js,jsx}

📄 CodeRabbit inference engine (.cursor/rules/dependency-injection.mdc)

**/*.{ts,tsx,js,jsx}: Prefer constructor injection for classes that require dependencies
Avoid global mutable singletons unless necessary
Use explicit interfaces for external dependencies to make testing easier

**/*.{ts,tsx,js,jsx}: Include required references in PRs/code for non-trivial logic: TypeScript (official docs), MDN (JavaScript reference), and official docs for any runtime/framework/libraries used (e.g., Node.js, React) as applicable.
Before assuming behavior of an API, include the doc link and a ≤25-word quote when the change relies on it.

**/*.{ts,tsx,js,jsx}: Prefer named exports for clear usage and easier refactors in TypeScript/JavaScript
Keep import order consistent: external first, then internal modules
Remove dead code and unused imports

**/*.{ts,tsx,js,jsx}: Use PascalCase naming convention for React/UI components
Use camelCase naming convention for variables and functions
Use UPPER_SNAKE_CASE naming convention for constants
Maintain consistent import grouping and ordering within the project, keeping third-party imports separate from local imports
For external data sources (HTTP, database), always validate and sanitize input using type guards or schema validators

**/*.{ts,tsx,js,jsx}: Use Prettier with no semicolons, single quotes, 4-space indent, 80 character width
Files must not exceed 250 lines and this is enforced

Implement TypeScript typecheck and linter in CI quality checks

**/*.{ts,tsx,js,jsx}: Use TypeScript for enhanced type safety
Implement error handling and error logging
Avoid commenting code unless extremely necessary - code should explain itself with descriptive names
Leave NO todos, placeholders or missing pieces in the code
Variables and functions must use camelCase
Constants must use UPPER_SNAKE_CASE
Use arrow functions for methods and computed properties
Avoid unnecessary curly braces in conditionals; use concise syntax for simple statements
Maintain consistent import grouping/order: external imports first, then...

Files:

  • packages/bot/src/handlers/messageHandler.ts
  • packages/backend/tests/unit/services/AutoModService.test.ts
  • packages/shared/src/services/AutoModService.ts
**/*.{js,jsx,ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/error-handling.mdc)

**/*.{js,jsx,ts,tsx}: Never throw strings. Throw Error (or typed subclasses) with descriptive messages
Include causal error as cause when available for better debugging
Define clear, stable error codes (e.g., ERR_AUTH_EXPIRED, ERR_NETWORK_TIMEOUT)
Provide optional metadata (e.g., details, retryable, status, correlationId) in error objects
Use domain error classes per area (e.g., AuthenticationError, ValidationError, NetworkError)
Log errors with structure (message, code, stack, cause, correlationId, user context where appropriate)
Mark retryable vs nonRetryable errors where helpful for operations
Set timeouts and handle aborts/cancellations; avoid dangling requests in API/network code
Implement backoff for transient failures; avoid infinite retries
Map HTTP status → domain errors; 4xx vs 5xx behave differently (e.g., retry for 5xx/network)

**/*.{js,jsx,ts,tsx}: Use functional components with hooks in React/React Native. Avoid class components.
Keep components focused on a single responsibility; extract complex logic into custom hooks.
Keep state local when possible. Use Context/Zustand/Redux only when necessary for state management.
If props or state traverse more than 3 levels, consider using context or a feature-scoped store instead of prop drilling.
Use performance optimization techniques: React.memo, useMemo, useCallback, Suspense (web), and virtualization for long lists; avoid unnecessary re-renders.
Web accessibility: use semantic HTML, labels, focus management, keyboard navigation, and aria-* attributes as needed.
React Native accessibility: use accessibility props (accessible, accessibilityLabel), proper roles and labels.
Identify and extract repetitive UI components proactively to components/ with clear props and minimal coupling.
Web styles: prefer co-located styles or design system tokens; avoid global style leakage.
React Native styles: prefer StyleSheet.create, design tokens, and theme providers; avoid in...

Files:

  • packages/bot/src/handlers/messageHandler.ts
  • packages/backend/tests/unit/services/AutoModService.test.ts
  • packages/shared/src/services/AutoModService.ts
**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/pattern.mdc)

Introduce interfaces at module boundaries to enable testing and substitutions

**/*.{ts,tsx}: Avoid using any type in TypeScript. If unavoidable, use unknown with type guards and justify with a code comment
Prefer interface for defining public object shapes in TypeScript, use type for unions and utility types
Use TypeScript utility types such as Partial, Pick, Omit, Readonly, and Record when appropriate
Use I{Name} naming convention for interfaces in TypeScript
Use T{Name} naming convention for type aliases and utility types in TypeScript

**/*.{ts,tsx}: Functions must be less than 50 lines with cyclomatic complexity less than 10
Do not use any types - ESLint enforces this at error level

**/*.{ts,tsx}: Prefer types over interfaces for most cases
Don't ever use any - type safety always
Avoid enums; use const objects instead
For complex types, create a separate file to declare them and import them
Avoid using any type; if unavoidable, use unknown with type guards and justify with code comment
Prefer interface for public API shapes; use type for unions and utility types
Use TypeScript utility types (Partial, Pick, Omit, Readonly, Record)

Files:

  • packages/bot/src/handlers/messageHandler.ts
  • packages/backend/tests/unit/services/AutoModService.test.ts
  • packages/shared/src/services/AutoModService.ts
**/*.{js,ts,tsx,jsx}

📄 CodeRabbit inference engine (.cursor/rules/documentation.mdc)

**/*.{js,ts,tsx,jsx}: Minimize comments in code; explain the 'why' when non-obvious, let code express the 'what' through clear naming
Document trade-offs briefly when deviating from ideal patterns

**/*.{js,ts,tsx,jsx}: Store secrets, ports, and hosts in environment variables (.env, .env.example) and never hardcode them
Avoid redundant or decorative AI comments; code should be self-explanatory and only commented when logic is non-obvious; prefer refactoring over lengthy comments

Never hardcode secrets, IPs, or ports; use .env and docs/ for required configuration variables

Files:

  • packages/bot/src/handlers/messageHandler.ts
  • packages/backend/tests/unit/services/AutoModService.test.ts
  • packages/shared/src/services/AutoModService.ts
packages/bot/**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/lucky-discord-bot.mdc)

packages/bot/**/*.{ts,tsx}: Use useMainPlayer() from discord-player to access the player instance; do not instantiate player directly
Do not duplicate queue or player state outside Discord Player; use shared services from @lucky/shared for persistent data like track history and session information
Use errorLog and debugLog from @lucky/shared/utils for logging throughout the bot package
Use embed and reply utilities from @lucky/shared for consistent message formatting and error sanitization across the bot
Use services from @lucky/shared (DatabaseService, Redis client) for database and cache access; do not instantiate Prisma or Redis directly in the bot package

Files:

  • packages/bot/src/handlers/messageHandler.ts
packages/bot/**

📄 CodeRabbit inference engine (.cursor/rules/lucky-project.mdc)

The bot package depends on shared and contains Discord bot commands and player handlers using Discord.js and Discord Player

Files:

  • packages/bot/src/handlers/messageHandler.ts
**/*.{js,mjs,ts,mts}

📄 CodeRabbit inference engine (.cursor/rules/lucky-project.mdc)

Use Node.js version ≥22 with ESM (ECMAScript modules) only; no CommonJS

Files:

  • packages/bot/src/handlers/messageHandler.ts
  • packages/backend/tests/unit/services/AutoModService.test.ts
  • packages/shared/src/services/AutoModService.ts
packages/bot/src/**/*.ts

📄 CodeRabbit inference engine (.cursor/rules/subagent-discord.mdc)

Use @lucky/shared for database, Redis, logging, and embed utilities instead of implementing them locally

Files:

  • packages/bot/src/handlers/messageHandler.ts
**/*.{test,spec}.{js,jsx,ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/frontend.mdc)

**/*.{test,spec}.{js,jsx,ts,tsx}: Test behavior, not implementation. Prefer Testing Library utilities for testing React/React Native components.
For React Native tests: mock native modules and test component interactions and accessibility labels.

Files:

  • packages/backend/tests/unit/services/AutoModService.test.ts
**/*.{test,spec}.{ts,tsx,js,jsx}

📄 CodeRabbit inference engine (.cursor/rules/pattern.mdc)

**/*.{test,spec}.{ts,tsx,js,jsx}: Test behavior, not implementation details
Prefer unit tests for core logic; add integration tests at meaningful boundaries

Files:

  • packages/backend/tests/unit/services/AutoModService.test.ts
**/*.{test,spec}.{js,ts,jsx,tsx}

📄 CodeRabbit inference engine (.cursor/rules/testing-quality.mdc)

**/*.{test,spec}.{js,ts,jsx,tsx}: Use Jest + a React testing library for unit and component tests as applicable
Test behavior, not implementation details

Files:

  • packages/backend/tests/unit/services/AutoModService.test.ts
packages/backend/tests/**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/lucky-backend-api.mdc)

Organize tests in packages/backend/tests/ with unit tests under unit/ and integration tests under integration/, following existing patterns with fixtures and setup

Files:

  • packages/backend/tests/unit/services/AutoModService.test.ts
packages/backend/**

📄 CodeRabbit inference engine (.cursor/rules/lucky-project.mdc)

The backend package depends on shared and contains Express API with auth and guild routes

Files:

  • packages/backend/tests/unit/services/AutoModService.test.ts
{packages/*/tests/**/*.test.{js,ts},tests/**/*.test.{js,ts}}

📄 CodeRabbit inference engine (.cursor/rules/lucky-project.mdc)

Add or adjust unit and integration tests when changing behavior; follow existing patterns in packages/*/tests and root tests/ directories

Files:

  • packages/backend/tests/unit/services/AutoModService.test.ts
**/*.{spec,test}.{ts,tsx,js,jsx}

📄 CodeRabbit inference engine (.cursor/rules/quality.mdc)

**/*.{spec,test}.{ts,tsx,js,jsx}: Use Jest for unit and integration tests
Test behavior, not implementation details
Run unit, integration tests, and coverage report in CI quality checks

Files:

  • packages/backend/tests/unit/services/AutoModService.test.ts
packages/backend/**/*.ts

📄 CodeRabbit inference engine (.cursor/rules/subagent-backend.mdc)

packages/backend/**/*.ts: Apply .cursor/rules/lucky-backend-api.mdc for structure and conventions when acting as backend specialist
Use .cursor/skills/backend-express/SKILL.md for Express routes, middleware, and services when acting as backend specialist
Use @lucky/shared for config and DB/Redis when needed in backend code

Files:

  • packages/backend/tests/unit/services/AutoModService.test.ts
packages/backend/tests/**/*.ts

📄 CodeRabbit inference engine (.cursor/rules/subagent-backend.mdc)

Follow existing patterns for unit and integration tests in packages/backend/tests/

Files:

  • packages/backend/tests/unit/services/AutoModService.test.ts
**/[A-Z]*.{ts,tsx,jsx}

📄 CodeRabbit inference engine (.cursor/rules/typescript.mdc)

Components must use PascalCase naming

Files:

  • packages/backend/tests/unit/services/AutoModService.test.ts
  • packages/shared/src/services/AutoModService.ts
{packages/shared/**,prisma/**}/**/*.{ts,js}

📄 CodeRabbit inference engine (.cursor/rules/lucky-project.mdc)

Use Prisma for PostgreSQL database and Redis for caching with shared client configuration

Files:

  • packages/shared/src/services/AutoModService.ts
packages/shared/**/*.ts

📄 CodeRabbit inference engine (.cursor/rules/lucky-shared.mdc)

packages/shared/**/*.ts: Organize the Lucky Shared Package with the following directory structure: Config in packages/shared/src/config/ (environment, constants, feature toggles, YouTube config); Services in packages/shared/src/services/ (DatabaseService, Redis client/operations, FeatureToggleService, ReactionRoles, RoleManagement); Types in packages/shared/src/types/ (errors, commands, common, discord, music); Utils in packages/shared/src/utils/ (error handling, retry, embeds, log, monitoring, composables, prismaClient)
Do not add dependencies on bot or backend packages; shared is the foundational package used by both
Use the single Prisma client located at packages/shared/src/utils/database/prismaClient.ts; maintain schema in repo root at prisma/schema.prisma; run migrations from root using npm run db:migrate
Use Redis client and operations located in packages/shared/src/services/redis/; use for cache, sessions, and rate limits as defined by existing keys and types
Use typed errors from packages/shared/src/types/errors/ for domain failures; avoid using generic Error for application-specific failures
Use shared log and monitoring utils for logging and monitoring in production code paths; do not use direct console statements for production logging

Files:

  • packages/shared/src/services/AutoModService.ts
packages/shared/**/*

📄 CodeRabbit inference engine (.cursor/rules/subagent-data.mdc)

Shared client and services must be located in packages/shared

Files:

  • packages/shared/src/services/AutoModService.ts
🧠 Learnings (12)
📚 Learning: 2026-03-09T20:20:47.877Z
Learnt from: CR
Repo: LucasSantana-Dev/Lucky PR: 0
File: .cursor/rules/lucky-discord-bot.mdc:0-0
Timestamp: 2026-03-09T20:20:47.877Z
Learning: Applies to packages/bot/src/handlers/player/**/*.{ts,tsx} : Track handling, errors, and lifecycle must be managed through dedicated handlers in `packages/bot/src/handlers/player/` (trackHandlers, errorHandlers, lifecycleHandlers)

Applied to files:

  • packages/bot/src/handlers/messageHandler.ts
📚 Learning: 2026-03-15T21:57:49.951Z
Learnt from: CR
Repo: LucasSantana-Dev/Lucky PR: 0
File: AGENTS.md:0-0
Timestamp: 2026-03-15T21:57:49.951Z
Learning: When working on unit tests, Jest ESM mocks, or fixing disabled tests, use the `testing-lucky` skill

Applied to files:

  • packages/backend/tests/unit/services/AutoModService.test.ts
📚 Learning: 2026-03-09T20:20:47.877Z
Learnt from: CR
Repo: LucasSantana-Dev/Lucky PR: 0
File: .cursor/rules/lucky-discord-bot.mdc:0-0
Timestamp: 2026-03-09T20:20:47.877Z
Learning: Applies to packages/bot/**/*.{ts,tsx} : Use services from `lucky/shared` (DatabaseService, Redis client) for database and cache access; do not instantiate Prisma or Redis directly in the bot package

Applied to files:

  • packages/backend/tests/unit/services/AutoModService.test.ts
📚 Learning: 2026-03-09T20:21:08.612Z
Learnt from: CR
Repo: LucasSantana-Dev/Lucky PR: 0
File: .cursor/rules/lucky-project.mdc:0-0
Timestamp: 2026-03-09T20:21:08.612Z
Learning: Applies to {packages/*/tests/**/*.test.{js,ts},tests/**/*.test.{js,ts}} : Add or adjust unit and integration tests when changing behavior; follow existing patterns in `packages/*/tests` and root `tests/` directories

Applied to files:

  • packages/backend/tests/unit/services/AutoModService.test.ts
📚 Learning: 2026-03-09T20:21:38.098Z
Learnt from: CR
Repo: LucasSantana-Dev/Lucky PR: 0
File: .cursor/rules/subagent-backend.mdc:0-0
Timestamp: 2026-03-09T20:21:38.098Z
Learning: Applies to packages/backend/tests/**/*.ts : Follow existing patterns for unit and integration tests in `packages/backend/tests/`

Applied to files:

  • packages/backend/tests/unit/services/AutoModService.test.ts
📚 Learning: 2026-03-15T21:57:49.951Z
Learnt from: CR
Repo: LucasSantana-Dev/Lucky PR: 0
File: AGENTS.md:0-0
Timestamp: 2026-03-15T21:57:49.951Z
Learning: When working with Prisma schema, migrations, DB/Redis in shared packages, use the `prisma-redis-lucky` skill

Applied to files:

  • packages/backend/tests/unit/services/AutoModService.test.ts
📚 Learning: 2026-03-09T20:21:08.612Z
Learnt from: CR
Repo: LucasSantana-Dev/Lucky PR: 0
File: .cursor/rules/lucky-project.mdc:0-0
Timestamp: 2026-03-09T20:21:08.612Z
Learning: Applies to {packages/shared/**,prisma/**}/**/*.{ts,js} : Use Prisma for PostgreSQL database and Redis for caching with shared client configuration

Applied to files:

  • packages/backend/tests/unit/services/AutoModService.test.ts
📚 Learning: 2026-03-09T20:21:38.098Z
Learnt from: CR
Repo: LucasSantana-Dev/Lucky PR: 0
File: .cursor/rules/subagent-backend.mdc:0-0
Timestamp: 2026-03-09T20:21:38.098Z
Learning: Applies to packages/backend/**/*.ts : Use `lucky/shared` for config and DB/Redis when needed in backend code

Applied to files:

  • packages/backend/tests/unit/services/AutoModService.test.ts
📚 Learning: 2026-03-09T20:21:52.065Z
Learnt from: CR
Repo: LucasSantana-Dev/Lucky PR: 0
File: .cursor/rules/subagent-discord.mdc:0-0
Timestamp: 2026-03-09T20:21:52.065Z
Learning: Applies to packages/bot/src/**/*.ts : Use `lucky/shared` for database, Redis, logging, and embed utilities instead of implementing them locally

Applied to files:

  • packages/backend/tests/unit/services/AutoModService.test.ts
📚 Learning: 2026-03-09T20:21:15.595Z
Learnt from: CR
Repo: LucasSantana-Dev/Lucky PR: 0
File: .cursor/rules/lucky-shared.mdc:0-0
Timestamp: 2026-03-09T20:21:15.595Z
Learning: Applies to packages/shared/**/*.ts : Use Redis client and operations located in `packages/shared/src/services/redis/`; use for cache, sessions, and rate limits as defined by existing keys and types

Applied to files:

  • packages/backend/tests/unit/services/AutoModService.test.ts
📚 Learning: 2026-03-09T20:21:15.595Z
Learnt from: CR
Repo: LucasSantana-Dev/Lucky PR: 0
File: .cursor/rules/lucky-shared.mdc:0-0
Timestamp: 2026-03-09T20:21:15.595Z
Learning: Applies to packages/shared/**/*.ts : Organize the Lucky Shared Package with the following directory structure: Config in `packages/shared/src/config/` (environment, constants, feature toggles, YouTube config); Services in `packages/shared/src/services/` (DatabaseService, Redis client/operations, FeatureToggleService, ReactionRoles, RoleManagement); Types in `packages/shared/src/types/` (errors, commands, common, discord, music); Utils in `packages/shared/src/utils/` (error handling, retry, embeds, log, monitoring, composables, prismaClient)

Applied to files:

  • packages/backend/tests/unit/services/AutoModService.test.ts
📚 Learning: 2026-03-15T21:57:49.951Z
Learnt from: CR
Repo: LucasSantana-Dev/Lucky PR: 0
File: AGENTS.md:0-0
Timestamp: 2026-03-15T21:57:49.951Z
Learning: When working on moderation commands and AutoModService, use the `moderation-automod` skill

Applied to files:

  • packages/shared/src/services/AutoModService.ts
🔇 Additional comments (14)
prisma/migrations/20260330000000_add_automod_link_exempt_channels/migration.sql (1)

1-2: LGTM!

The migration safely adds the linkExemptChannels column with a NOT NULL constraint and an empty array default, which is appropriate for existing rows and aligns with the Prisma schema addition.

CHANGELOG.md (1)

10-16: LGTM!

The changelog entry accurately documents all three fixes in this PR: spam detection using Redis sliding window, expanded allowed domains for link filtering, and the new linkExemptChannels field. Proper PR reference included.

prisma/schema.prisma (1)

455-461: LGTM!

The linkExemptChannels field is correctly defined as String[] with an empty array default, matching the migration and consistent with similar fields like exemptChannels.

packages/bot/src/handlers/messageHandler.ts (3)

47-59: Correct fix for spam detection.

The change from checkSpam(guildId, userId, [Date.now()]) to trackMessageAndCheckSpam(guildId, userId) properly fixes the non-functional spam detection. The old approach always passed a single-element array, which could never reach thresholds; the new method uses Redis sliding-window tracking.


75-88: Correct integration for link exemption.

Passing message.channelId to checkLinks enables the new linkExemptChannels feature, allowing specific channels to bypass link filtering without disabling other automod checks.


278-302: LGTM — formatting only.

These are minor formatting/reflow changes in handleXP with no behavioral impact.

packages/backend/tests/unit/services/AutoModService.test.ts (3)

15-28: LGTM — centralized mock setup.

Good refactoring to use a shared mockRedis object with all required Redis operations pre-mocked. This makes the test setup cleaner and easier to maintain.


215-312: Comprehensive test coverage for trackMessageAndCheckSpam.

The tests properly cover the key scenarios:

  • Spam disabled → returns false
  • Missing settings → returns false
  • Redis unhealthy → returns false (graceful degradation)
  • Threshold exceeded → returns true with Redis key verification
  • Below threshold → returns false

443-491: Good coverage for link exemption feature.

Tests verify:

  • vercel.app links pass when in allowedDomains
  • Links allowed when channel is in linkExemptChannels
  • Links still blocked in non-exempt channels

This matches the implementation behavior correctly.

packages/shared/src/services/AutoModService.ts (5)

20-20: LGTM!

The linkExemptChannels field is correctly added to the AutoModSettings interface, matching the Prisma schema.


65-75: Good expansion of allowed domains.

Adding github.com, github.io, vercel.app, netlify.app, and render.com to the balanced template reduces false positives for legitimate project showcase links.


296-319: Redis sliding-window spam detection implementation looks correct.

The method properly:

  1. Checks settings and Redis health first
  2. Pushes timestamp to list, trims to threshold entries, sets expiry
  3. Retrieves all timestamps and filters within time window
  4. Returns true only when recent count meets/exceeds threshold

One minor note: ltrim(key, 0, settings.spamThreshold) keeps spamThreshold + 1 entries (indices 0 through spamThreshold inclusive), which provides a small buffer for the window check — this is acceptable.


352-365: Channel exemption logic is correct.

Early return for exempt channels avoids unnecessary processing. The optional channelId parameter maintains backward compatibility.


364-365: No action needed. Empty allowedDomains returning false is intentional behavior, documented via the regression test checkLinks returns false when allowedDomains is empty. This design treats an empty whitelist as "allow all links," which is appropriate when the feature is disabled at configuration level.


📝 Walkthrough

Walkthrough

This PR enhances AutoMod spam detection and link filtering by introducing a Redis-backed sliding window for spam tracking, expanding allowed domains to reduce false positives, and adding support for channel-specific link filter exemptions via a new linkExemptChannels field across service, database, and handler layers.

Changes

Cohort / File(s) Summary
Database Schema & Migrations
prisma/schema.prisma, prisma/migrations/20260330000000_add_automod_link_exempt_channels/migration.sql
Added linkExemptChannels field to AutoModSettings model as a TEXT[] array with empty default. Migration creates the new column with non-null constraint.
Service Layer
packages/shared/src/services/AutoModService.ts
Introduced trackMessageAndCheckSpam() method for Redis-based spam tracking with sliding window. Extended allowedDomains with github.com, github.io, vercel.app, netlify.app, and render.com. Updated checkLinks() to accept optional channelId and skip filtering for exempt channels. Added linkExemptChannels: string[] to AutoModSettings interface.
Test Coverage
packages/backend/tests/unit/services/AutoModService.test.ts
Added comprehensive test suite for trackMessageAndCheckSpam() covering disabled spam, missing settings, Redis health checks, and threshold validation. Extended checkLinks tests for new allowed domains and linkExemptChannels exemption logic. Updated mock Redis with list operation methods (lpush, ltrim, expire, lrange).
Handler Integration
packages/bot/src/handlers/messageHandler.ts
Replaced checkSpam(guildId, userId, [Date.now()]) call with trackMessageAndCheckSpam(guildId, userId). Updated checkLinks() invocation to pass message.channelId as third argument for channel exemption evaluation.
Changelog
CHANGELOG.md
Added version 2.6.44 entry documenting spam tracking Redis improvement, link filter domain allowlist expansion, and new linkExemptChannels feature.

Sequence Diagram

sequenceDiagram
    actor Client
    participant Handler as messageHandler
    participant Service as AutoModService
    participant Redis
    
    Client->>Handler: sends message
    Handler->>Service: trackMessageAndCheckSpam(guildId, userId)
    Service->>Redis: lpush(`spam:{guildId}:{userId}`, timestamp)
    Redis-->>Service: ✓
    Service->>Redis: lrange(`spam:{guildId}:{userId}`, 0, -1)
    Redis-->>Service: [timestamps...]
    Service->>Service: evaluate count vs threshold
    Service-->>Handler: boolean (spam detected?)
    Handler->>Service: checkLinks(guildId, content, channelId)
    Service->>Service: check if channelId in linkExemptChannels
    alt Channel is exempt
        Service-->>Handler: false (skip link check)
    else Channel not exempt
        Service->>Service: validate links against allowedDomains
        Service-->>Handler: boolean (links blocked?)
    end
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

  • LuckasSantana-Dev/Lucky#358: Modifies AutoModService's link-checking behavior and domain handling with overlapping test coverage for checkLinks functionality.
🚥 Pre-merge checks | ✅ 2 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately summarizes the main changes: fixing automod spam tracking (by switching to Redis sliding-window) and reducing link filter false positives (by adding allowed domains and channel exemption).

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/automod-link-false-positives

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@sonarqubecloud

Copy link
Copy Markdown

@sonarqubecloud

Copy link
Copy Markdown

@LucasSantana-Dev
LucasSantana-Dev merged commit f0bb571 into main Mar 31, 2026
12 checks passed
@LucasSantana-Dev
LucasSantana-Dev deleted the fix/automod-link-false-positives branch March 31, 2026 22:15
LucasSantana-Dev added a commit that referenced this pull request May 13, 2026
…399)

- Replace broken checkSpam(guildId, userId, [Date.now()]) call in
  messageHandler with trackMessageAndCheckSpam() using Redis sliding
  window — spam detection was completely non-functional before this
- Add linkExemptChannels field to AutoModSettings schema so channels
  can be excluded from link checks without disabling all automod
- Pass message.channelId to checkLinks() to respect exempt channels
- Add vercel.app, netlify.app, github.com, github.io, render.com to
  balanced and light template allowedDomains (false positive fix)
- Add Prisma migration for linkExemptChannels column

This branch was successfully deployed

1 active deployment
Preview — f417e801 Deployed Mar 31, 2026 by vercel[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant