メッセージの一覧表示

このガイドでは、Google Chat API の Message リソースで list() メソッドを使用して、スペース内のメッセージのページネーションされたフィルタ可能なリストを表示する方法について説明します。

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

前提条件

Node.js

Python

Java

Apps Script

ユーザーとしてメッセージを一覧表示する

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

  • chat.messages.readonly または chat.messages 認証スコープを指定します。
  • ListMessages() メソッドを呼び出します。

次の例は、Chat スペース内のメッセージを一覧表示します。

Node.js

chat/client-libraries/cloud/list-messages-user-cred.js
import {createClientWithUserCredentials} from './authentication-utils.js';

const USER_AUTH_OAUTH_SCOPES = ['https://www.googleapis.com/auth/chat.messages.readonly'];

// This sample shows how to list messages with user credential
async function main() {
  // Create a client
  const chatClient = await createClientWithUserCredentials(USER_AUTH_OAUTH_SCOPES);

  // Initialize request argument(s)
  const request = {
    // Replace SPACE_NAME here
    parent: 'spaces/SPACE_NAME'
  };

  // Make the request
  const pageResult = chatClient.listMessagesAsync(request);

  // Handle the response. Iterating over pageResult will yield results and
  // resolve additional pages automatically.
  for await (const response of pageResult) {
    console.log(response);
  }
}

main().catch(console.error);

Python

chat/client-libraries/cloud/list_messages_user_cred.py
from authentication_utils import create_client_with_user_credentials
from google.apps import chat_v1 as google_chat

SCOPES = ["https://www.googleapis.com/auth/chat.messages.readonly"]

# This sample shows how to list messages with user credential
def list_messages_with_user_cred():
    # Create a client
    client = create_client_with_user_credentials(SCOPES)

    # Initialize request argument(s)
    request = google_chat.ListMessagesRequest(
        # Replace SPACE_NAME here
        parent = 'spaces/SPACE_NAME',
        # Number of results that will be returned at once
        page_size = 100
    )

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

    # Handle the response. Iterating over page_result will yield results and
    # resolve additional pages automatically.
    for response in page_result:
        print(response)

list_messages_with_user_cred()

Java

chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/ListMessagesUserCred.java
import com.google.chat.v1.ChatServiceClient;
import com.google.chat.v1.ListMessagesRequest;
import com.google.chat.v1.ListMessagesResponse;
import com.google.chat.v1.Message;

// This sample shows how to list messages with user credential.
public class ListMessagesUserCred {

  private static final String SCOPE =
    "https://www.googleapis.com/auth/chat.messages.readonly";

  public static void main(String[] args) throws Exception {
    try (ChatServiceClient chatServiceClient =
        AuthenticationUtils.createClientWithUserCredentials(
          ImmutableList.of(SCOPE))) {
      ListMessagesRequest.Builder request = ListMessagesRequest.newBuilder()
        // Replace SPACE_NAME here.
        .setParent("spaces/SPACE_NAME")
        // Number of results that will be returned at once.
        .setPageSize(10);

      // Iterate over results and resolve additional pages automatically.
      for (Message response :
          chatServiceClient.listMessages(request.build()).iterateAll()) {
        System.out.println(JsonFormat.printer().print(response));
      }
    }
  }
}

Apps Script

chat/advanced-service/Main.gs
/**
 * This sample shows how to list messages with user credential
 * 
 * It relies on the OAuth2 scope 'https://www.googleapis.com/auth/chat.messages.readonly'
 * referenced in the manifest file (appsscript.json).
 */
function listMessagesUserCred() {
  // Initialize request argument(s)
  // TODO(developer): Replace SPACE_NAME here
  const parent = 'spaces/SPACE_NAME';

  // Iterate through the response pages using page tokens
  let responsePage;
  let pageToken = null;
  do {
    // Request response pages
    responsePage = Chat.Spaces.Messages.list(parent, {
      pageSize: 10,
      pageToken: pageToken
    });
    // Handle response pages
    if (responsePage.messages) {
      responsePage.messages.forEach((message) => console.log(message));
    }
    // Update the page token to the next one
    pageToken = responsePage.nextPageToken;
  } while (pageToken);
}

このサンプルを実行するには、SPACE_NAME をスペースの name フィールドの ID に置き換えます。ID は、ListSpaces() メソッドを呼び出すか、スペースの URL から取得できます。

Chat API は、指定されたスペースで送信されたメッセージのリストを返します。リクエストにメッセージがない場合、Chat API レスポンスは空のオブジェクトを返します。REST/HTTP インターフェースを使用する場合、レスポンスには空の JSON オブジェクト {} が含まれます。

Chat 用アプリとしてメッセージを一覧表示する

アプリの認証には、1 回限りの管理者による承認が必要です。

Chat REST API を使用して、アプリ認証で Space のメッセージを一覧表示するには、リクエストで次の情報を渡します。

  • 次のいずれかの認可スコープを指定します。
    • https://www.googleapis.com/auth/chat.app.messages.readonly
  • messages リソースlist メソッドを呼び出します。
  • メッセージを一覧表示するスペースの name を渡します。

API キーを作成する

デベロッパー プレビュー API メソッドを呼び出すには、API 検出ドキュメントの非公開のデベロッパー プレビュー バージョンを使用する必要があります。リクエストを認証するには、API キーを渡す必要があります。

API キーを作成するには、アプリの Google Cloud プロジェクトを開いて次の操作を行います。

  1. Google Cloud コンソールで、メニュー > [API とサービス] > [認証情報] に移動します。

    [認証情報] に移動

  2. [認証情報を作成] > [API キー] をクリックします。
  3. 新しい API キーが表示されます。
    • [コピー] をクリックして、アプリのコードで使用する API キーをコピーします。API キーは、プロジェクトの認証情報の [API キー] セクションでも確認できます。
    • 不正使用を防ぐため、API キーを使用できる場所と対象の API を制限することをおすすめします。詳細については、API 制限を追加するをご覧ください。

Chat API を呼び出すスクリプトを作成する

アプリ認証Chat REST API を使用してメッセージを一覧表示する方法は次のとおりです。

Python

  1. 作業ディレクトリに chat_messages_list_app.py という名前のファイルを作成します。
  2. chat_messages_list_app.py に次のコードを含めます。

    from google.oauth2 import service_account
    from apiclient.discovery import build
    
    # Define your app's authorization scopes.
    # When modifying these scopes, delete the file token.json, if it exists.
    SCOPES = ["https://www.googleapis.com/auth/chat.app.messages.readonly"]
    
    def main():
        '''
        Authenticates with Chat API using app authentication,
        then lists messages from a specified space.
        '''
    
        # Specify service account details.
        creds = (
            service_account.Credentials.from_service_account_file('credentials.json')
            .with_scopes(SCOPES)
        )
    
        # Build a service endpoint for Chat API.
        chat = build('chat', 'v1', credentials=creds, discoveryServiceUrl='https://chat.googleapis.com/$discovery/rest?version=v1&labels=DEVELOPER_PREVIEW&key=API_KEY')
    
        # Use the service endpoint to call Chat API.
        result = chat.spaces().messages().list(
    
            # The space to list messages from.
            #
            # Replace SPACE_NAME with a space name.
            # Obtain the space name from the spaces resource of Chat API,
            # or from a space's URL.
            parent='spaces/SPACE_NAME'
    
        ).execute()
    
        # Print Chat API's response in your command line interface.
        print(result)
    
    if __name__ == '__main__':
        main()
    
  3. コードで、次のように置き換えます。

    • API_KEY: Chat API のサービス エンドポイントを構築するために作成した API キー。

    • SPACE_NAME: スペース名。Chat API の spaces.list メソッドまたはスペースの URL から取得できます。

  4. 作業ディレクトリで、サンプルをビルドして実行します。

    python3 chat_messages_list_app.py

Chat API は、指定されたスペースで送信されたメッセージのリストを返します。リクエストにメッセージがない場合、Chat API レスポンスは空のオブジェクトを返します。REST/HTTP インターフェースを使用する場合、レスポンスには空の JSON オブジェクト {} が含まれます。