搜尋訊息

本文說明如何使用 Google Chat API Message 資源的 search 方法,搜尋已驗證使用者有權存取訊息。

透過使用者驗證,您可以搜尋使用者加入的所有對話,或特定對話中的訊息。舉例來說,您可以搜尋含有特定關鍵字、提及使用者、未讀或含有附件的郵件。

在 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 Script

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

使用搜尋篩選器和運算子

您可以在 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()