메시지에 대한 세부정보 보기

이 가이드에서는 Google Chat API의 Message 리소스에서 get() 메서드를 사용하여 텍스트 또는 카드 메시지에 관한 세부정보를 반환하는 방법을 설명합니다.

Chat API에서 Chat 메시지는 Message 리소스로 표시됩니다. Chat 사용자는 텍스트가 포함된 메시지만 보낼 수 있지만 Chat 앱은 정적 또는 대화형 사용자 인터페이스 표시, 사용자로부터 정보 수집, 비공개로 메시지 전송 등 다양한 메시지 기능을 사용할 수 있습니다. Chat API에서 사용할 수 있는 메시지 기능에 대해 자세히 알아보려면 Google Chat 메시지 개요를 참고하세요.

기본 요건

Node.js

Python

자바

Apps Script

사용자 인증으로 메시지 가져오기

사용자 인증을 사용하여 메시지에 관한 세부정보를 가져오려면 요청에 다음을 전달하세요.

  • chat.messages.readonly 또는 chat.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()

자바

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: 스페이스의 name에서 가져온 ID입니다. ListSpaces() 메서드를 호출하거나 스페이스의 URL에서 ID를 가져올 수 있습니다.
  • MESSAGE_NAME: 메시지의 name에서 가져온 ID입니다. Chat API를 사용하여 비동기적으로 메시지를 만든 후 반환되는 응답 본문에서 ID를 가져오거나 생성 시 메시지에 할당된 맞춤 이름을 사용하여 ID를 가져올 수 있습니다.

Chat API는 지정된 메시지를 자세히 설명하는 Message 인스턴스를 반환합니다.

앱 인증이 포함된 메시지 가져오기

앱 인증을 사용하는 메시지에 대한 세부정보를 가져오려면 요청에 다음을 전달하세요.

  • 승인 범위를 지정합니다. 이 섹션의 예에서는 일반적으로 사용할 수 있으며 관리자 승인이 필요하지 않은 chat.bot 범위를 사용합니다. 또는 개발자 프리뷰에서 사용할 수 있는 관리자 승인을 통해 Chat 앱으로 승인할 수 있습니다.
  • GetMessage() 메서드를 호출합니다.
  • name을 가져올 메시지의 리소스 이름으로 설정합니다.

다음 예에서는 앱 인증을 사용하여 메시지를 가져옵니다.

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()

자바

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: 스페이스의 name에서 가져온 ID입니다. ListSpaces() 메서드를 호출하거나 스페이스의 URL에서 ID를 가져올 수 있습니다.
  • MESSAGE_NAME: 메시지의 name에서 가져온 ID입니다. Chat API를 사용하여 비동기적으로 메시지를 만든 후 반환되는 응답 본문에서 ID를 가져오거나 생성 시 메시지에 할당된 맞춤 이름을 사용하여 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: Chat API의 서비스 엔드포인트를 빌드하기 위해 만든 API 키입니다.
    • SPACE_NAME: 스페이스의 name에서 가져온 ID입니다. ListSpaces() 메서드를 호출하거나 스페이스의 URL에서 ID를 가져올 수 있습니다.
    • MESSAGE_NAME: 메시지의 name에서 가져온 ID입니다. Chat API를 사용하여 비동기식으로 메시지를 만든 후 반환되는 응답 본문에서 ID를 가져오거나, 생성 시 메시지에 할당된 맞춤 이름을 사용하여 ID를 가져올 수 있습니다.
  4. 작업 디렉터리에서 샘플을 빌드하고 실행합니다.

    python3 chat_messages_get_admin_app.py

Chat API는 지정된 메시지를 자세히 설명하는 Message 인스턴스를 반환합니다.