메시지 나열

이 가이드에서는 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에서 스페이스를 만들려면 고객센터 문서를 참고하세요.

자바

  • Google Chat 스페이스입니다. Google Chat API를 사용하여 스페이스를 만들려면 스페이스 만들기를 참고하세요. Chat에서 스페이스를 만들려면 고객센터 문서를 참고하세요.

Apps Script

  • Google Chat 스페이스입니다. Google Chat API를 사용하여 스페이스를 만들려면 스페이스 만들기를 참고하세요. Chat에서 스페이스를 만들려면 고객센터 문서를 참고하세요.

사용자로 메시지 나열

사용자 인증으로 메시지를 나열하려면 요청에 다음을 전달하세요.

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

자바

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() 메서드를 호출하거나 스페이스의 URL에서 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: Chat API의 서비스 엔드포인트를 빌드하기 위해 만든 API 키입니다.

    • SPACE_NAME: 스페이스 이름입니다. Chat API의 spaces.list 메서드 또는 스페이스의 URL에서 가져올 수 있습니다.

  4. 작업 디렉터리에서 샘플을 빌드하고 실행합니다.

    python3 chat_messages_list_app.py

Chat API는 지정된 스페이스에서 전송된 메시지 목록을 반환합니다. 요청에 메시지가 없으면 Chat API 응답은 빈 객체를 반환합니다. REST/HTTP 인터페이스를 사용하는 경우 응답에 빈 JSON 객체 {}가 포함됩니다.