取得訊息的詳細資料

本指南說明如何使用 Google Chat API 的 Message 資源中的 get() 方法,傳回文字或訊息的詳細資料。

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

必要條件

Node.js

Python

Java

Apps Script

取得含有使用者驗證資訊的訊息

如要取得通過使用者驗證的郵件詳細資料,請在要求中傳遞下列項目:

  • 指定 chat.messages.readonlychat.messages 授權範圍。
  • 呼叫 GetMessage() 方法。
  • name 設為要取得的訊息資源名稱。

以下範例會透過使用者驗證取得訊息:

Node.js

chat/client-libraries/cloud/get-message-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 get message 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 and MESSAGE_NAME here
    name: 'spaces/SPACE_NAME/messages/MESSAGE_NAME'
  };

  // Make the request
  const response = await chatClient.getMessage(request);

  // Handle the response
  console.log(response);
}

main().catch(console.error);

Python

chat/client-libraries/cloud/get_message_user_cred.py
from authentication_utils import create_client_with_user_credentials
import google.oauth2.credentials

from google.apps import chat_v1 as google_chat

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

# This sample shows how to get message with user credential
def get_message_with_user_cred():
    # Create a client
    client = create_client_with_user_credentials(SCOPES)

    # Initialize request argument(s)
    request = google_chat.GetMessageRequest(
        # Replace SPACE_NAME and MESSAGE_NAME here
        name = "spaces/SPACE_NAME/messages/MESSAGE_NAME",
    )

    # Make the request
    response = client.get_message(request)

    # Handle the response
    print(response)

get_message_with_user_cred()

Java

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

// This sample shows how to get message with user credential.
public class GetMessageUserCred {

  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))) {
      GetMessageRequest.Builder request = GetMessageRequest.newBuilder()
        // replace SPACE_NAME and MESSAGE_NAME here
        .setName("spaces/SPACE_NAME/members/MESSAGE_NAME");
      Message response = chatServiceClient.getMessage(request.build());

      System.out.println(JsonFormat.printer().print(response));
    }
  }
}

Apps Script

chat/advanced-service/Main.gs
/**
 * This sample shows how to get message 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 getMessageUserCred() {
  // Initialize request argument(s)
  // TODO(developer): Replace SPACE_NAME and MESSAGE_NAME here
  const name = 'spaces/SPACE_NAME/messages/MESSAGE_NAME';

  // Make the request
  const response = Chat.Spaces.Messages.get(name);

  // Handle the response
  console.log(response);
}

如要執行這個範例,請替換下列項目:

  • SPACE_NAME:來自聊天室的 ID name。 您可以呼叫 ListSpaces() 方法,或從空間的網址取得 ID。
  • MESSAGE_NAME:訊息 name 中的 ID。您可以透過 Chat API 建立訊息,並從非同步傳回的回應主體中取得 ID,也可以使用建立訊息時指派的自訂名稱

Chat API 會傳回 Message 執行個體,其中詳列指定訊息。

取得含有應用程式驗證的訊息

如要取得訊息的詳細資料 (須驗證應用程式),請在要求中傳遞下列項目:

以下範例會取得含有應用程式驗證的訊息:

Node.js

chat/client-libraries/cloud/get-message-app-cred.js
import {createClientWithAppCredentials} from './authentication-utils.js';

// This sample shows how to get message with app credential
async function main() {
  // Create a client
  const chatClient = createClientWithAppCredentials();

  // Initialize request argument(s)
  const request = {
    // Replace SPACE_NAME and MESSAGE_NAME here
    name: 'spaces/SPACE_NAME/messages/MESSAGE_NAME'
  };

  // Make the request
  const response = await chatClient.getMessage(request);

  // Handle the response
  console.log(response);
}

main().catch(console.error);

Python

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

# This sample shows how to get message with app credential
def get_message_with_app_cred():
    # Create a client
    client = create_client_with_app_credentials()

    # Initialize request argument(s)
    request = google_chat.GetMessageRequest(
        # Replace SPACE_NAME and MESSAGE_NAME here
        name = 'spaces/SPACE_NAME/messages/MESSAGE_NAME',
    )

    # Make the request
    response = client.get_message(request=request)

    # Handle the response
    print(response)

get_message_with_app_cred()

Java

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

// This sample shows how to get message with app credential.
public class GetMessageAppCred {

  public static void main(String[] args) throws Exception {
    try (ChatServiceClient chatServiceClient =
        AuthenticationUtils.createClientWithAppCredentials()) {
      GetMessageRequest.Builder request = GetMessageRequest.newBuilder()
        // replace SPACE_NAME and MESSAGE_NAME here
        .setName("spaces/SPACE_NAME/members/MESSAGE_NAME");
      Message response = chatServiceClient.getMessage(request.build());

      System.out.println(JsonFormat.printer().print(response));
    }
  }
}

Apps Script

chat/advanced-service/Main.gs
/**
 * This sample shows how to get message with app credential
 * 
 * It relies on the OAuth2 scope 'https://www.googleapis.com/auth/chat.bot'
 * used by service accounts.
 */
function getMessageAppCred() {
  // Initialize request argument(s)
  // TODO(developer): Replace SPACE_NAME and MESSAGE_NAME here
  const name = 'spaces/SPACE_NAME/messages/MESSAGE_NAME';
  const parameters = {};

  // Make the request
  const response = Chat.Spaces.Messages.get(name, parameters, getHeaderWithAppCredentials());

  // Handle the response
  console.log(response);
}

如要執行這個範例,請替換下列項目:

  • SPACE_NAME:來自聊天室的 ID name。 您可以呼叫 ListSpaces() 方法,或從空間的網址取得 ID。
  • MESSAGE_NAME:訊息 name 中的 ID。您可以從使用 Chat API 建立非同步訊息後傳回的回應本文中取得 ID,也可以使用建立訊息時指派的自訂名稱

Chat API 會傳回 Message 執行個體,其中詳列指定訊息。

取得訊息 (以 Chat 應用程式身分,須經管理員核准)

使用 chat.app.* 授權範圍進行應用程式驗證時,需要管理員核准一次。

如要使用 Chat REST API,透過應用程式驗證取得訊息詳細資料,請在要求中傳遞下列項目:

  • 呼叫 GetMessage() 方法。
  • 指定 chat.app.messages.readonly 授權範圍。
  • 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_get_admin_app.py 的檔案。
  2. chat_messages_get_admin_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 gets details about a message.
        '''
    
        # 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().get(
    
            # The message to get details about.
            #
            # Replace SPACE_NAME with a space name.
            # Obtain the space name from the spaces resource of Chat API,
            # or from a space's URL.
            name='spaces/SPACE_NAME/messages/MESSAGE_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:來自聊天室的 ID。name。您可以呼叫 ListSpaces() 方法或從空間的網址取得 ID。
    • MESSAGE_NAME:訊息 name 中的 ID。您可以透過使用 Chat API 非同步建立訊息後傳回的回應本文,或透過建立訊息時指派給訊息的自訂名稱,取得 ID。
  4. 在工作目錄中,建構並執行範例:

    python3 chat_messages_get_admin_app.py

Chat API 會傳回 Message 執行個體,其中詳列指定訊息。