列出訊息

本指南說明如何在 Google Chat API 的 Message 資源上使用 list() 方法,查看聊天室中分頁式且可篩選的訊息清單。

在 Chat API 中,Chat 訊息會以 Message 資源表示。雖然 Chat 使用者只能傳送含有文字的訊息,但 Chat 應用程式可以使用許多其他訊息功能,包括顯示靜態或互動式使用者介面、向使用者收集資訊,以及私下傳送訊息。如要進一步瞭解 Chat API 提供的訊息功能,請參閱 Google Chat 訊息總覽

必要條件

Node.js

Python

Java

Apps Script

列出訊息

如要列出含有使用者驗證的訊息,請在要求中傳遞以下資訊:

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

即時通訊/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。您可以呼叫 ListSpaces() 方法,或從空間的網址取得 ID。

Chat API 會傳回在指定聊天室中傳送的訊息清單。如果要求沒有任何訊息,Chat API 回應會傳回空物件。使用 REST/HTTP 介面時,回應會包含空白的 JSON 物件 {}