メッセージを検索

このドキュメントでは、Google Chat API の Message リソースで search メソッドを使用して、 認証済みユーザーがアクセスできるメッセージを検索する方法について説明します。

ユーザー認証を使用すると、ユーザーが参加しているすべての会話または 特定の会話でメッセージを検索できます。たとえば、特定のキーワードを含むメッセージ、ユーザーにメンションしているメッセージ、未読のメッセージ、添付ファイルがあるメッセージなどを検索できます。

Chat API では、Chat メッセージは Message リソースで表されます。 Chat ユーザーはテキストを含むメッセージのみを送信できますが、Chat アプリでは、静的またはインタラクティブなユーザー インターフェースの表示、ユーザーからの情報の収集、メッセージの非公開配信など、他の多くのメッセージング機能を使用できます。Chat API で使用できるメッセージング 機能の詳細については、 Google Chat メッセージの概要をご覧ください

前提条件

Node.js

  • Google Chat へのアクセス権を持つ Business または Enterprise Google Workspace アカウント

Python

  • Google Chat へのアクセス権を持つ Business または Enterprise Google Workspace アカウント

Java

  • Google Chat へのアクセス権を持つ Business または Enterprise Google Workspace アカウント

Apps Script

  • Google Chat へのアクセス権を持つ Business または Enterprise Google Workspace アカウント

メールを検索

ユーザー認証を使用してメッセージを検索するには、リクエストで次の情報を渡します。

  • chat.messages.readonly または chat.messages 承認スコープを指定します。

  • SearchMessages メソッドを呼び出します。

  • ユーザーがメンバーになっているすべてのスペース内を検索するには、parentspaces/- に設定します。他の値を使用するとエラーになります。

  • 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: 表示名の一部が一致するスペースでフィルタします。結果は、上位 5 件のスペースの一致に限定されます。 例: space.display_name:Project
  • attachment: 添付ファイルの有無を確認します。 例: attachment:*
  • annotations.user_mentions.user.name: メンションでフィルタします。 例: annotations.user_mentions.user.name:"users/me"

関数を使用して検索する

高度なフィルタリングは、次の関数を使用して行えます。

  • has_link: 1 つ以上のハイパーリンクを含むメッセージを返します。
  • is_unread: ユーザーが読んでいないメッセージを返します。

異なるフィールドでは、AND 演算子のみがサポートされています。例: sender.name = "users/me" AND is_unread()