Google Chat 앱으로 인증

이 가이드에서는 서비스 계정을 설정하고 사용하여 Google Chat API 할 수 있습니다. 먼저, 서비스 계정을 만드는 방법을 설명합니다. 그런 다음 서비스 계정을 사용하여 Chat에 인증하는 스크립트를 작성합니다. API를 사용하여 Chat 스페이스에 메시지를 게시합니다.

채팅 앱은 비동기식으로 호출할 때 서비스 계정을 사용하여 인증할 수 있습니다. 다음과 같은 도움을 줄 수 있습니다.

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

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

채팅 앱에서 사용자 데이터에 액세스하거나 사용자의 대신 사용자로 인증하세요.

도메인 관리자인 경우 도메인 전체 권한 위임 애플리케이션의 서비스 계정이 사용자의 데이터를 각 사용자의 동의를 얻어야 합니다. 도메인 전체 위임을 구성한 후 할 수 있습니다 서비스 계정을 사용하여 API 호출을 수행하여 사용자 계정을 가장합니다. 서비스 계정은 인증, 도메인 전체 위임은 사용자를 가장하여 사용자 인증으로 간주됩니다. 사용자가 필요로 하는 모든 기능 도메인 전체 위임을 사용할 수 있습니다

Chat 앱에 인증이 필요한 경우 및 어떤 종류의 인증을 사용해야 하는지 필수 인증 유형 를 참조하세요.

기본 요건

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

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

자바

  • 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 클라이언트 라이브러리와 기타 종속 항목을 설치합니다.

자바

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

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

npm install "@googleapis/chat"

Apps Script

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

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

이 샘플은 고급 Chat 서비스 Google Chat API를 호출할 수 있습니다 다음에 대해 서비스를 사용 설정하려면 다음 단계를 따르세요. Apps Script 프로젝트:

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

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

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

다음 코드는 서비스 계정을 사용하여 Chat API를 만든 다음 Chat 스페이스에 메시지를 게시할 때:

자바

  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를 공백으로 바꿉니다. 이름(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를 공백으로 바꿉니다. 이름(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를 공백으로 바꿉니다. 이름(spaces.list에서 가져올 수 있음) 메서드를 사용하거나 스페이스의 URL에서 가져올 수 있습니다. 그런 다음 서비스 계정의 비공개 키 파일 이름은 credentials.json입니다.

Apps Script

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

      "oauthScopes": [
        "https://www.googleapis.com/auth/script.external_request"
      ]
    
  2. 다음 코드를 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를 공백으로 바꿉니다. 이름(spaces.list에서 가져올 수 있음) 메서드를 사용하거나 스페이스의 URL에서 가져올 수 있습니다.

4단계: 전체 예시 실행

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

자바

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 API를 검토하여 Chat API로 할 수 있는 다른 작업 알아보기 참조 문서를 확인하세요.