列出訊息

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

在 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 授權範圍。
  • 呼叫 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。您可以呼叫 ListSpaces() 方法或從空間的網址取得 ID。

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

以 Chat 應用程式身分列出訊息

應用程式驗證需要管理員核准一次。

如要使用 Chat REST API,透過應用程式驗證列出空間中的訊息,請在要求中傳遞下列項目:

  • 指定下列其中一個授權範圍:
    • 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:您建立的 API 金鑰,用於建構 Chat API 的服務端點。

    • SPACE_NAME:聊天室名稱,可透過 Chat API 中的 spaces.list 方法或聊天室網址取得。

  4. 在工作目錄中,建構並執行範例:

    python3 chat_messages_list_app.py

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