Skip to content

feat(Guild): add message search#11459

Open
kshitijanurag wants to merge 1 commit intodiscordjs:mainfrom
kshitijanurag:patch-1
Open

feat(Guild): add message search#11459
kshitijanurag wants to merge 1 commit intodiscordjs:mainfrom
kshitijanurag:patch-1

Conversation

@kshitijanurag
Copy link
Copy Markdown

Add guild messages search functionality.

@vercel
Copy link
Copy Markdown

vercel bot commented Mar 20, 2026

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

2 Skipped Deployments
Project Deployment Actions Updated (UTC)
discord-js-guide Ignored Ignored Preview Mar 26, 2026 5:21pm
discord-js Skipped Skipped Mar 26, 2026 5:21pm

Request Review

@vercel vercel bot temporarily deployed to Preview – discord-js March 20, 2026 06:38 Inactive
@vercel vercel bot temporarily deployed to Preview – discord-js-guide March 20, 2026 06:38 Inactive
@coderabbitai
Copy link
Copy Markdown

coderabbitai bot commented Mar 20, 2026

📝 Walkthrough

Walkthrough

Added a new public Guild#searchMessages() async method to Discord.js that accepts filter options (content, author type, embeds, etc.) and pagination controls. The method validates input parameters, constructs a REST query, fetches messages from the Discord API, caches results, and returns total count with a collection of messages.

Changes

Cohort / File(s) Summary
Guild Message Search
packages/discord.js/src/structures/Guild.js
Added message search type imports (MessageSearchAuthorType, MessageSearchEmbedType, MessageSearchHasType, MessageSearchSortMode) and implemented new searchMessages(options) method with parameter validation, REST API integration, and message caching.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant Guild
    participant Validation
    participant REST as REST Client
    participant API as Discord API
    participant Cache as Message Cache

    User->>Guild: searchMessages(options)
    Guild->>Validation: validate options (content, authorType, has, etc.)
    alt Invalid Input
        Validation-->>Guild: throw DiscordjsTypeError
        Guild-->>User: error
    end
    Validation-->>Guild: options valid
    Guild->>REST: buildQuery & GET /channels/{id}/messages/search
    REST->>API: HTTP GET request
    API-->>REST: { messages, total_results }
    REST-->>Guild: response data
    
    loop For each message in response
        Guild->>Cache: check cached message
        alt Message cached
            Cache-->>Guild: return cached Message
        else Message not cached
            Guild->>Guild: create new Message instance
        end
    end
    
    Guild->>Guild: build Collection from messages
    Guild-->>User: { totalResults, messages: Collection }
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

🚥 Pre-merge checks | ✅ 3
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title 'feat(Guild): add message search' clearly and specifically summarizes the main change—adding message search functionality to the Guild class.
Description check ✅ Passed The description is directly related to the changeset, explaining the purpose of adding guild messages search functionality with relevant references to dependencies.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.

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

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
📝 Coding Plan
  • Generate coding plan for human review comments

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.

Tip

You can disable the changed files summary in the walkthrough.

Disable the reviews.changed_files_summary setting to disable the changed files summary in the walkthrough.

Copy link
Copy Markdown

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 5

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@packages/discord.js/src/structures/Guild.js`:
- Around line 1184-1197: The numeric validations in Guild.js for limit, offset
and slop only check type and range but not integer-ness; update the validation
in the block that handles limit, offset and slop (the checks around the
variables limit, offset, slop in the Guild class) to also require integers by
using Number.isInteger(value) (or equivalent) after the typeof check and before
the range check, and throw the same DiscordjsTypeError(ErrorCodes.InvalidType,
'<name>', 'integer') (or a matching error code/message) when the value is not an
integer so fractional values like 1.5 are rejected.
- Around line 1219-1249: Add client-side length validation for the search array
parameters in the same function that currently validates element values (where
variables like channelId, authorId, mentions, mentionsRoleId, repliedToUserId,
repliedToMessageId, embedProvider, linkHostname, attachmentFilename,
attachmentExtension are handled): create an object mapping each param to its
documented max (e.g., channelId:500, authorId:100, mentions:100,
mentionsRoleId:100, repliedToUserId:100, repliedToMessageId:100,
embedProvider:100, linkHostname:100, attachmentFilename:100,
attachmentExtension:100) and iterate it, checking if the corresponding
variable's length exceeds the max and throwing new
DiscordjsTypeError(ErrorCodes.ClientInvalidOption, param, `at most ${max}
elements`) when it does; place these checks alongside the existing validations
for authorType/has/embedType so they run before the API call.
- Around line 1090-1091: Fix the JSDoc indentation for the block whose
description is "Options used to search messages in a guild." by removing the
extra leading spaces before the opening /** so it lines up with other JSDoc
blocks in the file (the comment immediately preceding the guild message search
options definition in the Guild class). Ensure the opening /** indentation
matches adjacent JSDoc blocks to keep formatting consistent.
- Around line 1280-1283: The code in Guild.js uses the Message constructor as a
fallback in the messages reduction (new Message(this.client, message)) but
Message is not imported, causing a runtime ReferenceError; add an import for the
Message class alongside the other structure imports near the top of the file so
that Message is available when computing messages (the reduction referencing
this.client.channels.cache.get, channel?.messages._add, and new Message(...)).

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: ASSERTIVE

Plan: Pro

Run ID: e28e2b08-78ff-4d1a-9309-0a4d8ffbf056

📥 Commits

Reviewing files that changed from the base of the PR and between 2a06721 and 0a6687c.

📒 Files selected for processing (1)
  • packages/discord.js/src/structures/Guild.js
📜 Review details
🔇 Additional comments (3)
packages/discord.js/src/structures/Guild.js (3)

6-15: LGTM!

The new imports for message search types are correctly added and align with the validation logic in searchMessages.


1153-1179: LGTM on the method signature and parameter destructuring.

The destructuring pattern with default values for cache = true is consistent with other methods in the codebase. The parameter list comprehensively covers the Discord API's search options.


1199-1217: LGTM on enum and boolean validations.

The validation for sortBy, sortOrder, and boolean parameters (mentionEveryone, pinned, includeNsfw) is correct and provides clear error messages.

@vercel vercel bot temporarily deployed to Preview – discord-js-guide March 20, 2026 06:50 Inactive
@vercel vercel bot temporarily deployed to Preview – discord-js March 20, 2026 06:50 Inactive
@vercel vercel bot temporarily deployed to Preview – discord-js-guide March 20, 2026 08:05 Inactive
@vercel vercel bot temporarily deployed to Preview – discord-js March 20, 2026 08:05 Inactive
@vercel vercel bot temporarily deployed to Preview – discord-js March 20, 2026 12:38 Inactive
@vercel vercel bot temporarily deployed to Preview – discord-js-guide March 20, 2026 12:38 Inactive
@vercel vercel bot temporarily deployed to Preview – discord-js March 20, 2026 12:40 Inactive
@vercel vercel bot temporarily deployed to Preview – discord-js-guide March 20, 2026 12:40 Inactive
}
}

const data = await this.client.rest.get(Routes.guildMessagesSearch(this.id), { query });
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is not handling the 202 Accepted response.
TBD if we want to handle retries automatically here or just throw

@github-project-automation github-project-automation bot moved this from Todo to Review in Progress in discord.js Mar 26, 2026
offset,
slop,
} = {}) {
if (content !== undefined && typeof content !== 'string') {
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Do we really need all these checks here? personally, I think this should just be left to the api to return the error, unless the error is too broad (i have not checked).

Perhaps we can even delegate most of these to a MessagsSearchParamBuilder, which I think makes sense to have for this.

Ig it depends on what others will say 🤷

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Removed validation. Not sure about the builder though, will wait for input from other reviewers.

@vercel vercel bot temporarily deployed to Preview – discord-js March 26, 2026 17:20 Inactive
@vercel vercel bot temporarily deployed to Preview – discord-js-guide March 26, 2026 17:20 Inactive
embedProvider?: readonly string[];
embedType?: readonly MessageSearchEmbedType[];
has?: readonly MessageSearchHasType[];
includeNsfw?: boolean;
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

includeNSFW? @almeidx @vladfrangu

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I brought up this topic here #11393 (comment) but didn't get a response. I also voiced my opinion there

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@discordjs/core thoughts? I lean more towards includeNSFW

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

Status: Review in Progress

Development

Successfully merging this pull request may close these issues.

5 participants