사용자의 스페이스 읽기 상태 업데이트

이 가이드에서는 Google Chat API의 SpaceReadState 리소스에서 updateSpaceReadState 메서드를 사용하여 스페이스를 읽음 또는 읽지않음으로 표시하는 방법을 설명합니다.

SpaceReadState 리소스는 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.users.readstate 승인 범위를 사용한 사용자 인증이 필요합니다.

Node.js

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

    npm install @google-cloud/local-auth @googleapis/chat
    
  • Google Chat API가 사용 설정 및 구성된 Google Cloud 프로젝트 단계는 Google Chat 앱 빌드를 참고하세요.
  • 채팅 앱에 구성된 승인입니다. 스페이스 내에서 사용자의 읽기 상태에 관한 세부정보를 가져오려면 chat.users.readstate 승인 범위를 사용한 사용자 인증이 필요합니다.

Apps Script

  • Google Chat에 액세스할 수 있는 Google Workspace 계정
  • 게시된 채팅 앱입니다. 채팅 앱을 빌드하려면 이 quickstart을 따르세요.
  • 채팅 앱에 구성된 승인입니다. 스페이스 내에서 사용자의 읽기 상태에 관한 세부정보를 가져오려면 chat.users.readstate 승인 범위를 사용한 사용자 인증이 필요합니다.

호출하는 사용자의 스페이스 읽기 상태 업데이트

스페이스 내에서 사용자의 읽기 상태를 업데이트하려면 요청에 다음을 포함합니다.

  • chat.users.readstate 승인 범위를 지정합니다.
  • SpaceReadState 리소스에서 updateSpaceReadState 메서드를 호출합니다.
  • 가져올 스페이스 읽기 상태의 name를 전달합니다. 여기에는 사용자 ID 또는 별칭과 스페이스 ID가 포함됩니다. 공간 읽기 상태를 가져오면 호출하는 사용자의 읽기 상태만 가져올 수 있으며 다음 중 하나를 설정하여 지정할 수 있습니다.
    • me 별칭입니다. 예를 들면 users/me/spaces/SPACE/spaceReadState입니다.
    • 호출하는 사용자의 Workspace 이메일 주소입니다. 예를 들면 다음과 같습니다. users/user@example.com/spaces/SPACE/spaceReadState
    • 호출 사용자의 사용자 ID입니다. 예를 들면 다음과 같습니다. users/USER/spaces/SPACE/spaceReadState
  • 업데이트할 공간 읽기 상태의 측면을 지정하는 updateMask를 전달하며, 다음 필드 경로를 지원합니다.
    • lastReadTime: 사용자의 스페이스 읽기 상태가 업데이트된 시간입니다. 일반적으로 이는 마지막으로 읽은 메시지의 타임스탬프 또는 공간의 마지막 읽기 위치를 표시하기 위해 사용자가 지정한 타임스탬프에 해당합니다. lastReadTime가 마지막 메시지 생성 시간보다 이전이면 스페이스가 UI에서 읽지않음으로 표시됩니다. 스페이스를 읽음으로 표시하려면 lastReadTime를 최신 메시지 생성 시간보다 나중에 큰 값으로 설정합니다. lastReadTime는 최신 메시지 생성 시간과 일치하도록 강제됩니다. 스페이스 읽기 상태는 스페이스의 최상위 대화에 표시되는 메시지의 읽기 상태에만 영향을 미칩니다. 스레드의 응답은 이 타임스탬프의 영향을 받지 않으며 대신 스레드 읽기 상태에 의존합니다.

다음 예는 호출하는 사용자의 스페이스 읽기 상태를 업데이트합니다.

Python

  1. 작업 디렉터리에서 이름이 chat_spaceReadState_update.py인 파일을 만듭니다.
  2. chat_spaceReadState_update.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.users.readstate"]
    
    def main():
        '''
        Authenticates with Chat API via user credentials,
        then updates the space read state for the calling user.
        '''
    
        # 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.users().spaces().updateSpaceReadState(
    
            # The space read state to update.
            #
            # Replace USER with the calling user's ID, Workspace email,
            # or the alias me.
            #
            # Replace SPACE with a space name.
            # Obtain the space name from the spaces resource of Chat API,
            # or from a space's URL.
            name='users/me/spaces/SPACE/spaceReadState',
            updateMask='lastReadTime',
            body={'lastReadTime': f'{datetime.datetime(2000, 1, 3).isoformat()}Z'}
    
          ).execute()
    
        # Prints the API's response.
        print(result)
    
    if __name__ == '__main__':
        main()
    
  3. 코드에서 다음을 바꿉니다.

    • SPACE: Chat API의 spaces.list 메서드 또는 스페이스 URL에서 가져올 수 있는 스페이스 이름입니다.
  4. 작업 디렉터리에서 샘플을 빌드하고 실행합니다.

    python3 chat_spaceReadState_update.py
    

Node.js

  1. 작업 디렉터리에서 이름이 chat_spaceReadState_update.js인 파일을 만듭니다.
  2. chat_spaceReadState_update에 다음 코드를 포함합니다.

    const chat = require('@googleapis/chat');
    const {authenticate} = require('@google-cloud/local-auth');
    
    /**
    * Authenticates with Chat API via user credentials,
    * then updates the space read state for the calling user.
    * @return {!Promise<!Object>}
    */
    async function updateSpaceReadState() {
    
      /**
      * Authenticate with Google Workspace
      * and get user authorization.
      */
      const scopes = [
        'https://www.googleapis.com/auth/chat.users.readstate',
      ];
    
      const authClient =
          await authenticate({scopes, keyfilePath: 'client_secrets.json'});
    
      /**
      * Build a service endpoint for Chat API.
      */
      const chatClient = await chat.chat({version: 'v1', auth: authClient});
    
      /**
      * Use the service endpoint to call Chat API.
      */
      return await chatClient.users.spaces.updateSpaceReadState({
    
        /**
        * The space read state to update.
        *
        * Replace USER with the calling user's ID, Workspace email,
        * or the alias me.
        *
        * Replace SPACE with a space name.
        * Obtain the space name from the spaces resource of Chat API,
        * or from a space's URL.
        */
        name: 'users/me/spaces/SPACE/spaceReadState',
        updateMask: 'lastReadTime',
        requestBody: {
          lastReadTime: '{datetime.datetime(2000, 1, 3).isoformat()}Z'
        }
      });
    }
    
    /**
    * Use the service endpoint to call Chat API.
    */
    getSpaceReadState().then(console.log);
    
  3. 코드에서 다음을 바꿉니다.

    • SPACE: Chat API의 spaces.list 메서드 또는 스페이스 URL에서 가져올 수 있는 스페이스 이름입니다.
  4. 작업 디렉터리에서 샘플을 빌드하고 실행합니다.

    node chat_spaceReadState_update.js
    

Apps Script

이 예에서는 고급 Chat 서비스를 사용하여 Chat API를 호출합니다.

  1. Apps Script 프로젝트의 appsscript.json 파일에 chat.users.readstate 승인 범위를 추가합니다.

    "oauthScopes": [
      "https://www.googleapis.com/auth/chat.users.readstate"
    ]
    
  2. Apps Script 프로젝트의 코드에 다음과 같은 함수를 추가합니다.

    /**
    * Authenticates with Chat API via user credentials,
    * then updates the space read state for the calling user.
    * @param {string} spaceReadStateName The resource name of the space read state.
    */
    function updateSpaceReadState(spaceReadStateName) {
      try {
        const time = new Date('January 1, 2000')).toJSON();
        const body = {'lastReadTime': time};
        Chat.Users.Spaces.updateSpaceReadState(spaceReadStateName, body);
      } catch (err) {
        // TODO (developer) - Handle exception
        console.log('Failed to update read state with error %s', err.message);
      }
    }
    

Google Chat API는 지정된 스페이스 읽기 상태를 업데이트하고 SpaceReadState 리소스 인스턴스를 반환합니다.