스페이스에 사용자, Google 그룹 또는 Google Chat 앱을 초대하거나 추가하기

이 가이드에서는 Google Chat API의 membership 리소스에서 create 메서드를 사용하여 사용자, Google 그룹 또는 채팅 앱을 멤버십 만들기라고 하는 스페이스에 초대하거나 추가하는 방법을 설명합니다. 멤버십을 만들 때 지정된 구성원의 자동 수락 정책이 사용 중지된 경우 이 구성원은 초대되며 참여하기 전에 스페이스 초대를 수락해야 합니다. 그 외의 경우에는 멤버십을 만들면 지정된 스페이스에 구성원이 직접 추가됩니다.

Membership 리소스는 실제 사용자 또는 Google Chat 앱이 스페이스에 초대되었는지, 스페이스의 일부인지 또는 스페이스에 없는지를 나타냅니다.

기본 요건

Python

  • Python 3.6 이상
  • pip 패키지 관리 도구
  • Python용 최신 Google 클라이언트 라이브러리입니다. 이를 설치하거나 업데이트하려면 명령줄 인터페이스에서 다음 명령어를 실행합니다.

    pip3 install --upgrade google-api-python-client google-auth-oauthlib
    
  • Google Chat API가 사용 설정되고 구성된 Google Cloud 프로젝트 단계는 Google Chat 앱 빌드를 참고하세요.
  • 채팅 앱에 구성된 승인입니다. 멤버십을 만들려면 chat.memberships 또는 chat.memberships.app 승인 범위를 사용하는 사용자 인증이 필요합니다.

Node.js

  • Node.js 및 npm
  • Node.js용 최신 Google 클라이언트 라이브러리입니다. 이를 설치하려면 명령줄 인터페이스에서 다음 명령어를 실행합니다.

    npm install @google-cloud/local-auth @googleapis/chat
    
  • Google Chat API가 사용 설정되고 구성된 Google Cloud 프로젝트 단계는 Google Chat 앱 빌드를 참고하세요.
  • 채팅 앱에 구성된 승인입니다. 멤버십을 만들려면 chat.memberships 또는 chat.memberships.app 승인 범위를 사용하는 사용자 인증이 필요합니다.

스페이스에 사용자 초대 또는 추가하기

스페이스에 사용자를 초대하거나 추가하려면 요청에 다음을 전달합니다.

  • chat.memberships 승인 범위를 지정합니다.
  • membership 리소스에서 create 메서드를 호출합니다.
  • parent을 멤버십을 만들 스페이스의 리소스 이름으로 설정합니다.
  • memberusers/{user}로 설정합니다. 여기서 {user}은 멤버십을 만들려는 사람이고 다음 중 하나입니다.
    • People API의 사용자 ID입니다. 예를 들어 People API 사람 resourceNamepeople/123456789이면 membership.member.nameusers/123456789로 설정합니다.
    • Directory API의 사용자 ID입니다.
    • 사용자의 이메일 주소 예를 들면 users/222larabrown@gmail.com 또는 users/larabrown@cymbalgroup.com입니다. 사용자가 Google 계정을 사용하거나 다른 Google Workspace 조직에 속한 경우 사용자의 이메일 주소를 사용해야 합니다.

다음 예에서는 스페이스에 사용자를 추가합니다.

Python

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

    from google_auth_oauthlib.flow import InstalledAppFlow
    from googleapiclient.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.memberships"]
    
    def main():
        '''
        Authenticates with Chat API via user credentials,
        then adds a user to a Chat space by creating a membership.
        '''
    
        # Authenticate with Google Workspace
        # and get user authorization.
        flow = InstalledAppFlow.from_client_secrets_file(
                    'client_secrets.json', SCOPES)
        creds = flow.run_local_server()
    
        # Build a service endpoint for Chat API.
        chat = build('chat', 'v1', credentials=creds)
    
        # Use the service endpoint to call Chat API.
        result = chat.spaces().members().create(
    
            # The space in which to create a membership.
            parent = 'spaces/SPACE',
    
            # Specify which user the membership is for.
            body = {
              'member': {
                'name':'users/USER',
                'type': 'HUMAN'
              }
            }
    
        ).execute()
    
        # Prints details about the created membership.
        print(result)
    
    if __name__ == '__main__':
        main()
    
  3. 코드에서 다음을 바꿉니다.

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

    • USER: 사용자 ID입니다.

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

    python3 chat_membership_user_create.py
    

Node.js

  1. 작업 디렉터리에 add-user-to-space.js라는 파일을 만듭니다.
  2. add-user-to-space.js에 다음 코드를 포함합니다.

    const chat = require('@googleapis/chat');
    const {authenticate} = require('@google-cloud/local-auth');
    
    /**
    * Adds the user to the Chat space.
    * @return {!Promise<!Object>}
    */
    async function addUserToSpace() {
      const scopes = [
        'https://www.googleapis.com/auth/chat.memberships',
      ];
    
      const authClient =
          await authenticate({scopes, keyfilePath: 'client_secrets.json'});
    
      const chatClient = await chat.chat({version: 'v1', auth: authClient});
    
      return await chatClient.spaces.members.create({
        parent: 'spaces/SPACE',
        requestBody: {member: {name: 'users/USER', type: 'HUMAN'}}
      });
    }
    
    addUserToSpace().then(console.log);
    
  3. 코드에서 다음을 바꿉니다.

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

    • USER: 사용자 ID입니다.

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

    node add-user-to-space.js
    

Chat API는 생성된 사용자 멤버십을 자세히 설명하는 membership 인스턴스를 반환합니다.

스페이스에 Google 그룹 초대 또는 추가

스페이스에 Google 그룹을 초대하거나 추가하려면 요청에 다음을 전달합니다.

  • chat.memberships 승인 범위를 지정합니다.
  • membership 리소스에서 create 메서드를 호출합니다.
  • parent을 멤버십을 만들 스페이스의 리소스 이름으로 설정합니다.
  • groupMembergroups/{group}로 설정합니다. 여기서 {group}는 멤버십을 만들려는 그룹 ID입니다. 그룹의 ID는 Cloud ID API를 사용하여 검색할 수 있습니다. 예를 들어 Cloud ID API가 이름이 groups/123456789인 그룹을 반환하면 membership.groupMember.namegroups/123456789로 설정합니다.

Google 그룹스는 그룹 채팅이나 채팅 메시지에 추가할 수 없으며 이름이 지정된 스페이스에만 추가할 수 있습니다. 다음 예에서는 이름이 지정된 스페이스에 그룹을 추가합니다.

Python

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

    from google_auth_oauthlib.flow import InstalledAppFlow
    from googleapiclient.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.memberships"]
    
    def main():
        '''
        Authenticates with Chat API via user credentials,
        then adds a group to a Chat space by creating a membership.
        '''
    
        # Authenticate with Google Workspace
        # and get user authorization.
        flow = InstalledAppFlow.from_client_secrets_file(
                    'client_secrets.json', SCOPES)
        creds = flow.run_local_server()
    
        # Build a service endpoint for Chat API.
        chat = build('chat', 'v1', credentials=creds)
    
        # Use the service endpoint to call Chat API.
        result = chat.spaces().members().create(
    
            # The named space in which to create a membership.
            parent = 'spaces/SPACE',
    
            # Specify which group the membership is for.
            body = {
              'groupMember': {
                'name':'groups/GROUP',
              }
            }
    
        ).execute()
    
        # Prints details about the created membership.
        print(result)
    
    if __name__ == '__main__':
        main()
    
  3. 코드에서 다음을 바꿉니다.

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

    • GROUP: 그룹 ID입니다.

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

    python3 chat_membership_group_create.py
    

Node.js

  1. 작업 디렉터리에 add-group-to-space.js라는 파일을 만듭니다.
  2. add-group-to-space.js에 다음 코드를 포함합니다.

    const chat = require('@googleapis/chat');
    const {authenticate} = require('@google-cloud/local-auth');
    
    /**
    * Adds the group to the Chat space.
    * @return {!Promise<!Object>}
    */
    async function addUserToSpace() {
      const scopes = [
        'https://www.googleapis.com/auth/chat.memberships',
      ];
    
      const authClient =
          await authenticate({scopes, keyfilePath: 'client_secrets.json'});
    
      const chatClient = await chat.chat({version: 'v1', auth: authClient});
    
      return await chatClient.spaces.members.create({
        parent: 'spaces/SPACE',
        requestBody: {groupMember: {name: 'groups/GROUP'}}
      });
    }
    
    addUserToSpace().then(console.log);
    
  3. 코드에서 다음을 바꿉니다.

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

    • GROUP: 그룹 ID입니다.

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

    node add-group-to-space.js
    

Chat API는 생성된 그룹 멤버십을 자세히 설명하는 membership 인스턴스를 반환합니다.

스페이스에 채팅 앱 추가하기

채팅 앱은 스페이스에 다른 앱을 멤버로 추가할 수 없습니다. 두 사용자 간의 스페이스 또는 채팅 메시지에 채팅 앱을 추가하려면 요청에 다음을 전달합니다.

  • chat.memberships.app 승인 범위를 지정합니다.
  • membership 리소스에서 create 메서드를 호출합니다.
  • parent을 멤버십을 만들 스페이스의 리소스 이름으로 설정합니다.
  • member를 Chat API를 호출하는 앱을 나타내는 별칭인 users/app로 설정합니다.

다음 예에서는 스페이스에 채팅 앱을 추가합니다.

Python

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

    from google_auth_oauthlib.flow import InstalledAppFlow
    from googleapiclient.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.memberships.app"]
    
    def main():
        '''
        Authenticates with Chat API via user credentials,
        then adds the Chat app to a Chat space.
        '''
    
        # Authenticate with Google Workspace
        # and get user authorization.
        flow = InstalledAppFlow.from_client_secrets_file(
                    'client_secrets.json', SCOPES)
        creds = flow.run_local_server()
    
        # Build a service endpoint for Chat API.
        chat = build('chat', 'v1', credentials=creds)
    
        # Use the service endpoint to call Chat API.
        result = chat.spaces().members().create(
    
            # The space in which to create a membership.
            parent = 'spaces/SPACE',
    
            # Set the Chat app as the entity that gets added to the space.
            # 'app' is an alias for the Chat app calling the API.
            body = {
                'member': {
                  'name':'users/app',
                  'type': 'BOT'
                }
            }
    
        ).execute()
    
        # Prints details about the created membership.
        print(result)
    
    if __name__ == '__main__':
        main()
    
  3. 코드에서 SPACE을 스페이스 이름으로 바꿉니다. 이 이름은 Chat API의 spaces.list 메서드에서 가져오거나 스페이스의 URL에서 가져올 수 있습니다.

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

    python3 chat_membership_app_create.py
    

Node.js

  1. 작업 디렉터리에 add-app-to-space.js라는 파일을 만듭니다.
  2. add-app-to-space.js에 다음 코드를 포함합니다.

    const chat = require('@googleapis/chat');
    const {authenticate} = require('@google-cloud/local-auth');
    
    /**
    * Adds the app to the Chat space.
    * @return {!Promise<!Object>}
    */
    async function addAppToSpace() {
      const scopes = [
        'https://www.googleapis.com/auth/chat.memberships.app',
      ];
    
      const authClient =
          await authenticate({scopes, keyfilePath: 'client_secrets.json'});
    
      const chatClient = await chat.chat({version: 'v1', auth: authClient});
    
      return await chatClient.spaces.members.create({
        parent: 'spaces/SPACE',
        requestBody: {member: {name: 'users/app', type: 'BOT'}}
      });
    }
    
    addAppToSpace().then(console.log);
    
  3. 코드에서 SPACE을 스페이스 이름으로 바꿉니다. 이 이름은 Chat API의 spaces.list 메서드에서 가져오거나 스페이스의 URL에서 가져올 수 있습니다.

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

    node add-app-to-space.js
    

Chat API는 생성된 앱 멤버십을 자세히 설명하는 membership 인스턴스를 반환합니다.