This document explains how to use the
[`search`](https://developers.google.com/workspace/chat/api/reference/rpc/google.chat.v1#google.chat.v1.ChatService.SearchMessages)
method on the `Message` resource of the Google Chat API to search for messages that
the authenticated user has access to.

With [user authentication](https://developers.google.com/workspace/chat/authenticate-authorize-chat-user),
you can search for messages across all conversations the user has joined, or
within a specific conversation. For example, you can search for messages that
contain specific keywords, mention the user, are unread, or have attachments.

In the Chat API, a Chat message is represented by the
[`Message` resource](https://developers.google.com/workspace/chat/api/reference/rest/v1/spaces.messages).
While Chat users can only send messages that contain text,
Chat apps can use many other messaging features, including
displaying static or interactive user interfaces, collecting information from
users, and delivering messages privately. To learn more about messaging
features available for the Chat API, see the
[Google Chat messages overview](https://developers.google.com/workspace/chat/messages-overview).

## Prerequisites


### Node.js

- A Business or Enterprise [Google Workspace](https://support.google.com/a/answer/6043576) account with access to [Google Chat](https://workspace.google.com/products/chat/).

<!-- -->

- Set up your environment:
  - [Create a Google Cloud project](https://developers.google.com/workspace/guides/create-project).
  - [Configure the OAuth consent screen](https://developers.google.com/workspace/guides/configure-oauth-consent).
  - [Enable and configure the Google Chat API](https://developers.google.com/workspace/chat/configure-chat-api) with a name, icon, and description for your Chat app.
  - Install the Node.js [Cloud Client Library](https://developers.google.com/workspace/chat/libraries?tab=nodejs#cloud-client-libraries).
- [Choose an authorization scope](https://developers.google.com/workspace/chat/authenticate-authorize#asynchronous-chat-calls).

<!-- -->

- A Google Chat space. To create one using the Google Chat API, see [Create a space](https://developers.google.com/workspace/chat/create-spaces). To create one in Chat, visit the [Help Center documentation](https://support.google.com/chat/answer/12176488).

### Python

- A Business or Enterprise [Google Workspace](https://support.google.com/a/answer/6043576) account with access to [Google Chat](https://workspace.google.com/products/chat/).

<!-- -->

- Set up your environment:
  - [Create a Google Cloud project](https://developers.google.com/workspace/guides/create-project).
  - [Configure the OAuth consent screen](https://developers.google.com/workspace/guides/configure-oauth-consent).
  - [Enable and configure the Google Chat API](https://developers.google.com/workspace/chat/configure-chat-api) with a name, icon, and description for your Chat app.
  - Install the Python [Cloud Client Library](https://developers.google.com/workspace/chat/libraries?tab=python#cloud-client-libraries).
- [Choose an authorization scope](https://developers.google.com/workspace/chat/authenticate-authorize#asynchronous-chat-calls).

<!-- -->

- A Google Chat space. To create one using the Google Chat API, see [Create a space](https://developers.google.com/workspace/chat/create-spaces). To create one in Chat, visit the [Help Center documentation](https://support.google.com/chat/answer/12176488).

### Java

- A Business or Enterprise [Google Workspace](https://support.google.com/a/answer/6043576) account with access to [Google Chat](https://workspace.google.com/products/chat/).

<!-- -->

- Set up your environment:
  - [Create a Google Cloud project](https://developers.google.com/workspace/guides/create-project).
  - [Configure the OAuth consent screen](https://developers.google.com/workspace/guides/configure-oauth-consent).
  - [Enable and configure the Google Chat API](https://developers.google.com/workspace/chat/configure-chat-api) with a name, icon, and description for your Chat app.
  - Install the Java [Cloud Client Library](https://developers.google.com/workspace/chat/libraries?tab=java#cloud-client-libraries).
- [Choose an authorization scope](https://developers.google.com/workspace/chat/authenticate-authorize#asynchronous-chat-calls).

<!-- -->

- A Google Chat space. To create one using the Google Chat API, see [Create a space](https://developers.google.com/workspace/chat/create-spaces). To create one in Chat, visit the [Help Center documentation](https://support.google.com/chat/answer/12176488).

### Apps Script

- A Business or Enterprise [Google Workspace](https://support.google.com/a/answer/6043576) account with access to [Google Chat](https://workspace.google.com/products/chat/).

<!-- -->

- Set up your environment:
  - [Create a Google Cloud project](https://developers.google.com/workspace/guides/create-project).
  - [Configure the OAuth consent screen](https://developers.google.com/workspace/guides/configure-oauth-consent).
  - [Enable and configure the Google Chat API](https://developers.google.com/workspace/chat/configure-chat-api) with a name, icon, and description for your Chat app.
  - [Create a standalone Apps Script project](https://developers.google.com/apps-script/guides/projects), and turn on the [Advanced Chat Service](https://developers.google.com/apps-script/advanced/chat).
- [Choose an authorization scope](https://developers.google.com/workspace/chat/authenticate-authorize#asynchronous-chat-calls).

<!-- -->

- A Google Chat space. To create one using the Google Chat API, see [Create a space](https://developers.google.com/workspace/chat/create-spaces). To create one in Chat, visit the [Help Center documentation](https://support.google.com/chat/answer/12176488).


> [!NOTE]
> The code samples in this page use the gRPC API interface with the Google Cloud client libraries. Alternatively, you can use the REST API interface. For more information about the gRPC and REST interfaces, see [Google Chat API overview](https://developers.google.com/workspace/chat/api/reference).

<br />

## Search for messages

To search for messages with [user
authentication](https://developers.google.com/workspace/chat/authenticate-authorize-chat-user), pass the
following in your request:

- Specify the `chat.messages.readonly` or `chat.messages` authorization scope.

- Call the
  [`SearchMessages`](https://developers.google.com/workspace/chat/api/reference/rpc/google.chat.v1#google.chat.v1.ChatService.SearchMessages)
  method.

- Set `parent` to `spaces/-` to search within all spaces the user is a member
  of. Using any other value results in an error.

- In the `filter` field, specify a search query string. The query can include
  keywords and filters.

The following code sample searches for unread messages that contain the keyword
"tasks":

### Node.js

    /**
     * Searches for messages in Google Chat.
     * @param {string} filter The search query.
     */
    async function searchMessages(filter) {
      const {ChatServiceClient} = require('@google-apps/chat').v1;

      // Instantiates a client
      const chatClient = new ChatServiceClient();

      // See https://github.com/googleworkspace/node-samples/blob/main/chat/client-libraries/cloud/authentication-utils.js
      // for an example of how to authenticate the request.

      // Construct request
      const request = {
        // Parent must be "spaces/-" to search across all spaces.
        parent: 'spaces/-',
        filter: filter,
      };

      // Run request
      const iterable = await chatClient.searchMessagesAsync(request);
      for await (const response of iterable) {
        console.log(response);
      }
    }

    searchMessages('tasks AND is_unread()');

### Python

    from google.apps import chat_v1

    def search_messages(filter_str: str):
        """
        Searches for messages in Google Chat.
        Args:
            filter_str: The search query.
        """
        # Create a client
        client = chat_v1.ChatServiceClient()

        # See https://github.com/googleworkspace/python-samples/blob/main/chat/client-libraries/cloud/authentication_utils.py
        # for an example of how to authenticate the request.

        # Initialize request argument
        request = chat_v1.SearchMessagesRequest(
            # Parent must be "spaces/-" to search across all spaces.
            parent="spaces/-",
            filter=filter_str
        )

        # Make the request
        page_result = client.search_messages(request=request)

        # Handle the response
        for response in page_result:
            print(response)

    search_messages('tasks AND is_unread()')

### Java

    import com.google.chat.v1.ChatServiceClient;
    import com.google.chat.v1.SearchMessageResult;
    import com.google.chat.v1.SearchMessagesRequest;

    public class SearchMessages {
      public static void main(String[] args) throws Exception {
        searchMessages("tasks AND is_unread()");
      }

      /**
       * Searches for messages in Google Chat.
       *
       * @param filter The search query.
       */
      public static void searchMessages(String filter) throws Exception {
        // See https://github.com/googleworkspace/java-samples/blob/main/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/AuthenticationUtils.java
        // for an example of how to authenticate the request.
        try (ChatServiceClient chatServiceClient = ChatServiceClient.create()) {
          SearchMessagesRequest request =
              SearchMessagesRequest.newBuilder()
                  .setParent("spaces/-")
                  .setFilter(filter)
                  .build();
          for (SearchMessageResult result : chatServiceClient.searchMessages(request).iterateAll()) {
            System.out.println(result.getMessage().getText());
          }
        }
      }
    }

### Apps Script


`javascript
/**
* Searches for messages in Google Chat.
*/
function searchMessages() {
const filter = 'tasks AND is_unread()';
const url = 'https://chat.googleapis.com/v1/spaces/-/messages:search';
const request_payload = {
filter: filter
};
try {
const response = UrlFetchApp.fetch(url, {
method: 'post',
headers: {
'Authorization': 'Bearer ' + ScriptApp.getOAuthToken()
},
contentType: 'application/json',
payload: JSON.stringify(request_payload)
});
if (response.results) {
for (const result of response.results) {
console.log('Message text: %s', result.message.text);
}
} else {
console.log('No messages found.');
}
} catch (err) {
console.log('Failed to search messages with error: %s', err.message);
}
}`

### Use search filters and operators

You can refine your search results by using keywords, fields, and functions in
the `filter` field. For more information, see
[`SearchMessagesRequest`](https://developers.google.com/workspace/chat/api/reference/rpc/google.chat.v1#google.chat.v1.SearchMessagesRequest).

#### Search by keyword

To search for messages that contain specific text, enter the keywords. For
example, to search for pending reports, use `pending reports`.

#### Search by field

You can filter results by specific message or space fields. For example:

- **`create_time`** : Filter by the time the message was created. Example: `create_time > "2023-01-01T00:00:00Z"`
- **`sender.name`** : Filter by the resource name of the sender. Example: `sender.name = "users/1234567890"`
- **`space.name`** : Limit the search to a specific space. Example: `space.name = "spaces/ABCDEFGH"`
- **`space.display_name`** : Filter spaces based on a partial match of their display name. Results are limited to the top five space matches. Example: `space.display_name:Project`
- **`attachment`** : Check for the presence of attachments. Example: `attachment:*`
- **`annotations.user_mentions.user.name`** : Filter by mentions. Example: `annotations.user_mentions.user.name:"users/me"`

#### Search using functions

Advanced filtering is available through the following functions:

- **`has_link`**: Returns messages that contain at least one hyperlink.
- **`is_unread`**: Returns messages that haven't been read by the user.

Across different fields, only `AND` operators are supported. For example:
`sender.name = "users/me" AND is_unread()`.

## Related topics

- [Format a message](https://developers.google.com/workspace/chat/format-messages).
- [Delete a message](https://developers.google.com/workspace/chat/delete-messages).
- [Get details about a message](https://developers.google.com/workspace/chat/get-messages).
- [List messages in a space](https://developers.google.com/workspace/chat/list-messages).
- [Update a message](https://developers.google.com/workspace/chat/update-messages).
- [Send a message](https://developers.google.com/workspace/chat/create-messages).