搜索信息

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

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

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

前提条件

Node.js

  • Google Chat 聊天室。如需使用 Google Chat API 创建聊天室,请参阅 创建聊天室。如需在 Chat 中创建聊天室, 请访问 帮助中心文档

Python

  • Google Chat 聊天室。如需使用 Google Chat API 创建聊天室,请参阅 创建聊天室。如需在 Chat 中创建聊天室, 请访问 帮助中心文档

Java

  • Google Chat 聊天室。如需使用 Google Chat API 创建聊天室,请参阅 创建聊天室。如需在 Chat 中创建聊天室, 请访问 帮助中心文档

Apps 脚本

  • Google Chat 聊天室。如需使用 Google Chat API 创建聊天室,请参阅 创建聊天室。如需在 Chat 中创建聊天室, 请访问 帮助中心文档

搜索消息

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

  • 指定 chat.messages.readonlychat.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 脚本

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); } }

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

您可以在 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:根据聊天室显示名称的部分匹配项过滤聊天室。结果仅限于前 5 个匹配的聊天室。 示例: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()