Google Chat 앱으로 인증

이 가이드에서는 채팅 앱을 대신하여 서비스 계정을 설정하고 사용하여 Google Chat API에 액세스하는 방법을 설명합니다. 먼저 서비스 계정을 만드는 방법을 안내합니다. 그런 다음 서비스 계정을 사용하여 Chat API로 인증하고 Chat 스페이스에 메시지를 게시하는 스크립트를 작성하는 방법을 보여줍니다.

채팅 앱은 Google Chat API를 비동기식으로 호출할 때 서비스 계정을 사용하여 인증할 수 있으므로 다음을 수행할 수 있습니다.

  • spaces.messages.create을(를) 사용하여 Google Chat에 메시지를 보낼 때는 다음 작업을 수행합니다.
    • 장기 실행 백그라운드 작업 실행이 완료되면 사용자에게 알립니다.
    • 서버가 오프라인 상태가 되었음을 사용자에게 알립니다.
    • 고객 지원 담당자에게 새로 열린 고객 케이스를 관리해 달라고 요청합니다.
  • spaces.messages.update를 사용하여 이전에 보낸 메시지를 다음으로 업데이트합니다.
    • 진행 중인 작업의 상태를 변경합니다.
    • 할 일의 담당자 또는 마감일을 업데이트합니다.
  • spaces.members.list를 사용하여 스페이스의 사용자를 나열하여 다음을 실행합니다.
    • 스페이스에 있는 사용자를 확인합니다.
    • 스페이스 멤버십에 팀의 모든 사용자가 포함되는지 확인합니다.

서비스 계정으로 인증된 경우 Chat 스페이스에서 관련 데이터를 가져오거나 작업을 실행하려면 Chat 앱에 스페이스 멤버십이 있어야 합니다. 예를 들어 스페이스 멤버를 나열하거나 스페이스에서 메시지를 만들려면 채팅 앱 자체가 스페이스의 구성원이어야 합니다.

채팅 앱에서 사용자 데이터에 액세스하거나 사용자를 대신하여 작업을 실행해야 하는 경우 대신 사용자로 인증합니다.

도메인 관리자는 도메인 전체 권한 위임을 부여하여 각 사용자의 동의 없이 애플리케이션의 서비스 계정이 사용자 데이터에 액세스하도록 승인할 수 있습니다. 도메인 전체 위임을 구성한 후에는 서비스 계정을 사용하여 API를 호출하여 사용자 계정을 가장할 수 있습니다. 서비스 계정이 인증에 사용되더라도 도메인 전체 위임은 사용자를 가장하므로 사용자 인증으로 간주됩니다. 사용자 인증이 필요한 모든 기능에 도메인 전체 위임을 사용할 수 있습니다.

채팅 앱에 인증이 필요한 경우와 사용할 인증 종류에 대한 자세한 내용은 Chat API 인증 및 승인 개요에서 필수 인증 유형을 참조하세요.

기본 요건

이 가이드의 예를 실행하려면 다음과 같은 기본 요건이 필요합니다.

또한 다음과 같은 언어별 기본 요건이 필요합니다.

Java

  • JDK 1.7 이상
  • Maven 패키지 관리 도구
  • 초기화된 Maven 프로젝트입니다. 새 프로젝트를 초기화하려면 명령줄 인터페이스에서 다음 명령어를 실행하세요.

    mvn archetype:generate -DgroupId=com.google.chat.app.authsample -DartifactId=auth-sample-app -DarchetypeArtifactId=maven-archetype-quickstart -DarchetypeVersion=1.4 -DinteractiveMode=false
    

Python

  • Python 3.6 이상
  • pip 패키지 관리 도구

Node.js

  • Node.js
  • npm 패키지 관리 도구
  • 초기화된 Node.js 프로젝트입니다. 새 프로젝트를 초기화하려면 새 폴더를 만들고 새 폴더로 전환한 후 명령줄 인터페이스에서 다음 명령어를 실행합니다.

    npm init
    

Apps Script

1단계: Google Cloud 콘솔에서 서비스 계정 만들기

채팅 앱이 Google API에 액세스하는 데 사용할 수 있는 서비스 계정을 만듭니다.

서비스 계정 만들기

서비스 계정을 만드는 방법은 다음과 같습니다.

Google Cloud 콘솔

  1. Google Cloud 콘솔에서 메뉴 > IAM 및 관리자 > 서비스 계정으로 이동합니다.

    서비스 계정으로 이동

  2. 서비스 계정 만들기를 클릭합니다.
  3. 서비스 계정 세부정보를 입력한 다음 만들고 계속하기를 클릭합니다.
  4. 선택사항: 서비스 계정에 역할을 할당하여 Google Cloud 프로젝트의 리소스에 대한 액세스 권한을 부여합니다. 자세한 내용은 리소스에 대한 액세스 권한 부여, 변경, 취소를 참고하세요.
  5. 계속을 클릭합니다.
  6. 선택사항: 이 서비스 계정으로 작업을 관리하고 수행할 수 있는 사용자 또는 그룹을 입력합니다. 자세한 내용은 서비스 계정 명의 도용 관리를 참고하세요.
  7. 완료를 클릭합니다. 서비스 계정의 이메일 주소를 기록해 둡니다.

gcloud CLI

  1. 서비스 계정을 만듭니다.
    gcloud iam service-accounts create SERVICE_ACCOUNT_NAME \
      --display-name="SERVICE_ACCOUNT_NAME"
  2. 선택사항: 서비스 계정에 역할을 할당하여 Google Cloud 프로젝트의 리소스에 대한 액세스 권한을 부여합니다. 자세한 내용은 리소스에 대한 액세스 권한 부여, 변경, 취소를 참고하세요.

서비스 계정이 서비스 계정 페이지에 표시됩니다. 다음으로 서비스 계정의 비공개 키를 만듭니다.

비공개 키 만들기

서비스 계정의 비공개 키를 만들고 다운로드하려면 다음 단계를 따르세요.

  1. Google Cloud 콘솔에서 메뉴 > IAM 및 관리자 > 서비스 계정으로 이동합니다.

    서비스 계정으로 이동

  2. 서비스 계정을 선택합니다.
  3. > 키 추가 > 새 키 만들기를 클릭합니다.
  4. JSON을 선택한 다음 만들기를 클릭합니다.

    새 공개 키/비공개 키 쌍이 생성되어 새 파일로 머신에 다운로드됩니다. 다운로드한 JSON 파일을 작업 디렉터리에 credentials.json로 저장합니다. 이 파일은 이 키의 유일한 사본입니다. 키를 안전하게 저장하는 방법에 대한 자세한 내용은 서비스 계정 키 관리를 참조하세요.

  5. 닫기를 클릭합니다.

서비스 계정에 대한 자세한 내용은 Google Cloud IAM 문서의 서비스 계정을 참조하세요.

2단계: Google 클라이언트 라이브러리 및 기타 종속 항목 설치

Google 클라이언트 라이브러리와 프로젝트에 필요한 기타 종속 항목을 설치합니다.

Java

Google 클라이언트 라이브러리와 기타 필수 종속 항목을 Maven 프로젝트에 추가하려면 프로젝트 디렉터리에서 pom.xml 파일을 수정하고 다음 종속 항목을 추가합니다.

<dependencies>
  <!-- ... existing dependencies ... -->
  <dependency>
    <groupId>com.google.apis</groupId>
    <artifactId>google-api-services-chat</artifactId>
    <version>v1-rev20230905-2.0.0</version>
  </dependency>
  <dependency>
    <groupId>com.google.auth</groupId>
    <artifactId>google-auth-library-oauth2-http</artifactId>
    <version>1.19.0</version>
  </dependency>
  <dependency>
      <groupId>com.google.code.gson</groupId>
      <artifactId>gson</artifactId>
      <version>2.10.1</version>
  </dependency>
</dependencies>

Python

Python용 Google 클라이언트 라이브러리를 아직 설치하지 않았다면 명령줄 인터페이스에서 다음 명령어를 실행합니다.

pip3 install --upgrade google-api-python-client google-auth

Node.js

Node.js 프로젝트에 Google 클라이언트 라이브러리를 추가하려면 프로젝트 디렉터리로 전환하고 명령줄 인터페이스에서 다음 명령어를 실행합니다.

npm install "@googleapis/chat"

Apps Script

이 샘플은 Apps Script용 OAuth2 라이브러리를 사용하여 서비스 계정 인증을 위한 JWT 토큰을 생성합니다. 라이브러리를 Apps Script 프로젝트에 추가하려면 다음 단계를 따르세요.

  1. 왼쪽에서 편집기 를 클릭합니다.
  2. 왼쪽의 라이브러리 옆에 있는 라이브러리 추가 를 클릭합니다.
  3. 스크립트 ID 1B7FSrk5Zi6L1rSxxTDgDEUsPzlukDsi4KGuTMorsTQHhGBzBkMun4iDF를 입력합니다.
  4. 조회를 클릭한 다음 추가를 클릭합니다.

이 샘플은 고급 채팅 서비스를 사용하여 Google Chat API를 호출합니다. Apps Script 프로젝트에 서비스를 사용 설정하려면 다음 안내를 따르세요.

  1. 왼쪽에서 편집기 를 클릭합니다.
  2. 왼쪽의 서비스 옆에 있는 서비스 추가 를 클릭합니다.
  3. Google Chat API를 선택합니다.
  4. 버전에서 v1을 선택합니다.
  5. Add를 클릭합니다.

클라이언트 라이브러리에서 지원되는 모든 언어를 사용할 수 있습니다.

3단계: 서비스 계정을 사용하여 Chat API로 인증하는 스크립트 작성

다음 코드는 서비스 계정을 사용하여 Chat API로 인증한 후 Chat 스페이스에 메시지를 게시합니다.

Java

  1. 프로젝트 디렉터리에서 src/main/java/com/google/chat/app/authsample/App.java 파일을 엽니다.
  2. App.java의 콘텐츠를 다음 코드로 바꿉니다.

    package com.google.chat.app.authsample;
    
    import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
    import com.google.api.client.http.HttpRequestInitializer;
    import com.google.api.client.json.gson.GsonFactory;
    import com.google.api.services.chat.v1.HangoutsChat;
    import com.google.api.services.chat.v1.model.Message;
    import com.google.auth.http.HttpCredentialsAdapter;
    import com.google.auth.oauth2.GoogleCredentials;
    
    /**
     * Authenticates with Chat API via service account credentials,
     * then creates a Chat message.
     */
    public class App {
        // Specify required scopes.
        private static final String CHAT_SCOPE = "https://www.googleapis.com/auth/chat.bot";
    
        // Specify service account details.
        private static final String PRIVATE_KEY_RESOURCE_URI = "/credentials.json";
    
        public static void main( String[] args ) {
            try {
                // Run app.
                Message response = App.createChatMessage();
                // Print details about the created message.
                System.out.println(response);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    
        private static Message createChatMessage() throws Exception {
            // Build the Chat API client and authenticate with the service account.
            GoogleCredentials credentials = GoogleCredentials.fromStream(
                App.class.getResourceAsStream(PRIVATE_KEY_RESOURCE_URI))
                .createScoped(CHAT_SCOPE);
            HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter(credentials);
            HangoutsChat chatService = new HangoutsChat.Builder(
                GoogleNetHttpTransport.newTrustedTransport(),
                GsonFactory.getDefaultInstance(),
                requestInitializer)
                .setApplicationName("auth-sample-app")
                .build();
    
            // The space to create the message in.
            //
            // Replace SPACE_NAME with a space name.
            // Obtain the space name from the spaces resource of Chat API,
            // or from a space's URL.
            String spaceName = "spaces/SPACE_NAME";
    
            // Create a Chat message.
            Message message = new Message().setText("Hello, world!");
            return chatService.spaces().messages().create(spaceName, message).execute();
        }
    }
    
  3. 코드에서 SPACE_NAME을 스페이스 이름으로 바꿉니다. 이 이름은 Chat API의 spaces.list 메서드 또는 스페이스의 URL에서 가져올 수 있습니다.

  4. 프로젝트 디렉터리 내에 resources라는 새 하위 디렉터리를 만듭니다.

  5. 서비스 계정의 비공개 키 파일 이름이 credentials.json인지 확인하고 resources 하위 디렉터리에 복사합니다.

  6. 프로젝트 패키지에 비공개 키 파일을 포함하도록 Maven을 구성하려면 프로젝트 디렉터리에서 pom.xml 파일을 수정하고 다음 구성을 <build> 섹션에 추가합니다.

    <build>
      <!-- ... existing configurations ... -->
      <resources>
        <resource>
          <directory>resources</directory>
        </resource>
      </resources>
    </build>
    
  7. 프로젝트 패키지에 종속 항목을 포함하고 애플리케이션의 기본 클래스를 실행하도록 Maven을 구성하려면 프로젝트 디렉터리에서 pom.xml 파일을 수정하고 <plugins> 섹션에 다음 구성을 추가합니다.

    <plugins>
      <!-- ... existing configurations ... -->
      <plugin>
        <artifactId>maven-assembly-plugin</artifactId>
        <configuration>
          <archive>
            <manifest>
              <mainClass>com.google.chat.app.authsample.App</mainClass>
            </manifest>
          </archive>
          <descriptorRefs>
            <descriptorRef>jar-with-dependencies</descriptorRef>
          </descriptorRefs>
        </configuration>
      </plugin>
    </plugins>
    

Python

  1. 작업 디렉터리에서 chat_app_auth.py라는 파일을 만듭니다.
  2. chat_app_auth.py에 다음 코드를 포함합니다.

    from apiclient.discovery import build
    from google.oauth2 import service_account
    
    # Specify required scopes.
    SCOPES = ['https://www.googleapis.com/auth/chat.bot']
    
    # Specify service account details.
    CREDENTIALS = service_account.Credentials.from_service_account_file(
        'credentials.json', scopes=SCOPES)
    
    # Build the URI and authenticate with the service account.
    chat = build('chat', 'v1', credentials=CREDENTIALS)
    
    # Create a Chat message.
    result = chat.spaces().messages().create(
    
        # The space to create the message in.
        #
        # 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',
    
        # The message to create.
        body={'text': 'Hello, world!'}
    
    ).execute()
    
    # Prints details about the created message.
    print(result)
    
  3. 코드에서 SPACE_NAME을 스페이스 이름으로 바꿉니다. 이 이름은 Chat API의 spaces.list 메서드 또는 스페이스의 URL에서 가져올 수 있습니다. 서비스 계정의 비공개 키 파일 이름이 credentials.json인지 확인합니다.

Node.js

  1. 프로젝트 디렉터리에 chat_app_auth.js라는 파일을 만듭니다.
  2. chat_app_auth.js에 다음 코드를 포함합니다.

    const chat = require('@googleapis/chat');
    
    async function createMessage() {
      const auth = new chat.auth.GoogleAuth({
    
        // Specify service account details.
        keyFilename: 'credentials.json',
    
        // Specify required scopes.
        scopes: ['https://www.googleapis.com/auth/chat.bot']
    
      });
      const authClient = await auth.getClient();
    
      // Create the Chat API client and authenticate with the service account.
      const chatClient = await chat.chat({
        version: 'v1',
        auth: authClient
      });
    
      // Create a Chat message.
      const result = await chatClient.spaces.messages.create({
    
        // The space to create the message in.
        //
        // 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',
    
        // The message to create.
        requestBody: { 'text': 'Hello, world!' }
    
      });
      return result;
    }
    
    // Execute function then print details about the created message.
    createMessage().then(console.log);
    
  3. 코드에서 SPACE_NAME을 스페이스 이름으로 바꿉니다. 이 이름은 Chat API의 spaces.list 메서드 또는 스페이스의 URL에서 가져올 수 있습니다. 서비스 계정의 비공개 키 파일 이름이 credentials.json인지 확인합니다.

Apps Script

  1. Apps Script 편집기에서 appsscript.json 파일을 수정하고 외부 요청을 통해 서비스 계정 OAuth 토큰을 얻는 데 필요한 OAuth 범위를 추가합니다.

      "oauthScopes": [
        "https://www.googleapis.com/auth/script.external_request"
      ]
    
  2. Apps Script 프로젝트의 ChatAppAuth.gs 파일에 다음 코드를 저장합니다.

    // Specify the contents of the file credentials.json.
    const CREDENTIALS = CREDENTIALS;
    
    const SCOPE = 'https://www.googleapis.com/auth/chat.bot';
    
    // The space to create the message in.
    //
    // Replace SPACE_NAME with a space name.
    // Obtain the space name from the spaces resource of Chat API,
    // or from a space's URL.
    const PARENT = 'spaces/SPACE_NAME'
    
    /**
     * Authenticates with Chat API via app credentials, then posts a message.
     */
    function createMessageWithAppCredentials() {
      try {
        const service = getService_();
        if (!service.hasAccess()) {
          console.error(service.getLastError());
          return;
        }
    
        // Specify the message to create.
        const message = {'text': 'Hello world!'};
    
        // Call Chat API with a service account to create a message.
        const result = Chat.Spaces.Messages.create(
            message,
            PARENT,
            {},
            // Authenticate with the service account token.
            {'Authorization': 'Bearer ' + service.getAccessToken()});
    
        // Log details about the created message.
        console.log(result);
    
      } catch (err) {
        // TODO (developer) - Handle exception.
        console.log('Failed to create message with error %s', err.message);
      }
    }
    
    /**
     * Configures the OAuth library to authenticate with the service account.
     */
    function getService_() {
      return OAuth2.createService(CREDENTIALS.client_email)
          .setTokenUrl('https://oauth2.googleapis.com/token')
          .setPrivateKey(CREDENTIALS.private_key)
          .setIssuer(CREDENTIALS.client_email)
          .setSubject(CREDENTIALS.client_email)
          .setScope(SCOPE)
          .setPropertyStore(PropertiesService.getScriptProperties());
    }
    
  3. 코드에서 CREDENTIALScredentials.json 파일의 콘텐츠로 바꿉니다.

  4. 코드에서 SPACE_NAME을 스페이스 이름으로 바꿉니다. 이 이름은 Chat API의 spaces.list 메서드 또는 스페이스의 URL에서 가져올 수 있습니다.

4단계: 전체 예시 실행

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

Java

mvn compile assembly:single
java -jar target/auth-sample-app-1.0-SNAPSHOT-jar-with-dependencies.jar

Python

python3 chat_app_auth.py

Node.js

node chat_app_auth.js

Apps Script

Apps Script 편집기에서 ChatAppAuth.gs 파일을 열고 실행을 클릭합니다.

스크립트는 Chat API에 인증된 요청을 하고 Chat 스페이스에 채팅 앱으로 메시지를 게시하여 응답합니다.

예시 문제 해결

이 섹션에서는 이 샘플을 실행하려고 하는 동안 발생할 수 있는 일반적인 문제를 설명합니다.

이 앱을 사용할 권한이 없습니다.

스크립트를 실행할 때 다음과 같은 오류가 발생할 수 있습니다.

<HttpError 403 when requesting https://chat.googleapis.com/v1/spaces/{space}/messages?alt=json returned "You are not permitted to use this app". Details: "You are not permitted to use this app">

이 오류 메시지는 채팅 앱에 지정된 Chat 스페이스에서 Chat 메시지를 만들 권한이 없음을 의미합니다.

이 오류를 해결하려면 스크립트에 지정된 Chat 스페이스에 채팅 앱을 추가합니다.

Chat API 참조 문서를 검토하여 Chat API로 할 수 있는 다른 작업에 대해 알아보세요.