搜索信息

本文档介绍了如何对 Google Chat API 的 Message 资源使用 search 方法,以搜索经过身份验证的用户有权访问的消息。

通过用户身份验证,您可以在用户加入的所有对话中或在特定对话中搜索消息。例如,您可以搜索包含特定关键字、提及用户、未读或包含附件的消息。

在 Chat API 中,聊天消息由 Message 资源表示。虽然 Chat 用户只能发送包含文本的消息,但 Chat 应用可以使用许多其他消息传递功能,包括显示静态或交互式界面、从用户收集信息以及私下传递消息。如需详细了解 Chat API 提供的消息功能,请参阅 Google Chat 消息概览。

前提条件

Node.js

Python

Java

Apps 脚本

搜索邮件

如需通过用户身份验证搜索邮件,请在请求中传递以下内容:

  • 指定 chat.messages.readonly 或 chat.messages 授权范围。

  • 调用 SearchMessages 方法。

  • 将 parent 设置为 spaces/-,以在用户所属的所有聊天室中进行搜索。使用任何其他值都会导致错误。

  • 在 filter 字段中,指定搜索查询字符串。查询可以包含关键字和过滤条件。

以下代码示例会搜索包含关键字“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 脚本

/**
 * Searches for messages in Google Chat.
 */
function searchMessages() {
  const parent = 'spaces/-';
  const request = {
    filter: 'tasks AND is_unread()',
  };
  try {
    const response = Chat.Spaces.Messages.search(request, parent);
    if (response.results && response.results.length > 0) {
      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);
  }
}

使用搜索过滤条件和运算符

您可以使用 filter 字段中的关键字、字段和函数来优化搜索结果。如需了解详情,请参阅 SearchMessagesRequest。

如需搜索包含特定文本的消息,请输入关键字。例如,如需搜索待处理报告,请使用 pending reports。

按字段搜索

您可以按特定消息或聊天室字段过滤结果。例如:

  • create_time:按消息创建时间过滤。示例:create_time > "2023-01-01T00:00:00Z"
  • sender.name:按发送者的资源名称过滤。示例:sender.name = "users/1234567890"
  • space.name:将搜索范围限制在特定空间。 示例:space.name = "spaces/ABCDEFGH"
  • space.display_name:根据聊天室显示名称的部分匹配项过滤聊天室。结果仅限于前五个匹配的聊天室。 示例:space.display_name:Project
  • attachment:检查是否存在附件。 示例:attachment:*
  • annotations.user_mentions.user.name:按提及内容过滤。 示例:annotations.user_mentions.user.name:"users/me"

使用函数进行搜索

您可以通过以下函数使用高级过滤功能:

  • has_link:返回包含至少一个超链接的消息。
  • is_unread:返回用户尚未阅读的消息。

在不同字段之间,仅支持 AND 运算符。例如:sender.name = "users/me" AND is_unread()。