Xem chi tiết về tin nhắn

Hướng dẫn này giải thích cách sử dụng get() phương thức trên tài nguyên Message của API Google Chat để trả về thông tin chi tiết về tin nhắn văn bản hoặc tin nhắn thẻ.

Trong API Chat, tin nhắn Chat được biểu thị bằng tài nguyên Message. Mặc dù người dùng Chat chỉ có thể gửi tin nhắn có chứa văn bản, nhưng ứng dụng Chat có thể sử dụng nhiều tính năng nhắn tin khác, bao gồm hiển thị giao diện người dùng tĩnh hoặc tương tác, thu thập thông tin từ người dùng và gửi tin nhắn riêng tư. Để tìm hiểu thêm về các tính năng nhắn tin có sẵn cho API Chat, hãy xem bài viết Tổng quan về tin nhắn Google Chat.

Điều kiện tiên quyết

Node.js

Python

Java

Apps Script

Lấy tin nhắn bằng tính năng xác thực người dùng

Để biết thông tin chi tiết về một tin nhắn có tính năng xác thực người dùng, hãy truyền các thông tin sau trong yêu cầu:

  • Chỉ định phạm vi uỷ quyền chat.messages.readonly hoặc chat.messages.
  • Gọi phương thức GetMessage().
  • Đặt name thành tên tài nguyên của tin nhắn cần lấy.

Ví dụ sau đây lấy một tin nhắn có tính năng xác thực người dùng:

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);
}

await main();

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);
}

Để chạy mẫu này, hãy thay thế các thông tin sau:

  • SPACE_NAME: mã nhận dạng từ name của không gian. Bạn có thể lấy mã nhận dạng bằng cách gọi phương thức ListSpaces() hoặc từ URL của không gian.
  • MESSAGE_NAME: mã nhận dạng từ name của tin nhắn. Bạn có thể lấy mã nhận dạng từ phần nội dung phản hồi được trả về sau khi tạo tin nhắn không đồng bộ bằng API Chat hoặc bằng tên tuỳ chỉnh được chỉ định cho tin nhắn khi tạo.

API Chat trả về một thực thể của Message nêu chi tiết tin nhắn đã chỉ định.

Lấy tin nhắn bằng tính năng xác thực ứng dụng

Để biết thông tin chi tiết về một tin nhắn có tính năng xác thực ứng dụng, hãy truyền các thông tin sau trong yêu cầu:

Ví dụ sau đây lấy một tin nhắn có tính năng xác thực ứng dụng:

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);
}

await main();

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);
}

Để chạy mẫu này, hãy thay thế các thông tin sau:

  • SPACE_NAME: mã nhận dạng từ name của không gian. Bạn có thể lấy mã nhận dạng bằng cách gọi phương thức ListSpaces() hoặc từ URL của không gian.
  • MESSAGE_NAME: mã nhận dạng từ name của tin nhắn. Bạn có thể lấy mã nhận dạng từ phần nội dung phản hồi được trả về sau khi tạo tin nhắn không đồng bộ bằng API Chat hoặc bằng tên tuỳ chỉnh được chỉ định cho tin nhắn khi tạo.

API Chat trả về một thực thể của Message nêu chi tiết tin nhắn đã chỉ định.

Lấy tin nhắn với tư cách là ứng dụng Chat có quản trị viên phê duyệt

Tính năng xác thực ứng dụng có phạm vi uỷ quyền chat.app.* yêu cầu quản trị viên phê duyệt một lần .

Để biết thông tin chi tiết về một tin nhắn có tính năng xác thực ứng dụng bằng API REST Chat, hãy truyền các thông tin sau trong yêu cầu:

  • Gọi phương thức GetMessage().
  • Chỉ định phạm vi uỷ quyền chat.app.messages.readonly.
  • Đặt name thành tên tài nguyên của tin nhắn cần lấy.

Viết tập lệnh gọi API Chat

Sau đây là cách lấy thông tin chi tiết về một tin nhắn có tính năng xác thực ứng dụng và quản trị viên phê duyệt cũng như API REST Chat:

Python

  1. Trong thư mục làm việc, hãy tạo một tệp có tên là chat_messages_get_admin_app.py.
  2. Đưa mã sau vào 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)
    
        # 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. Trong mã, hãy thay thế các thông tin sau:

  4. Trong thư mục làm việc, hãy tạo và chạy mẫu:

    python3 chat_messages_get_admin_app.py

API Chat trả về một thực thể của Message nêu chi tiết tin nhắn đã chỉ định.