메시지 업데이트하기

이 가이드에서는 Google Chat API의 Message 리소스에서 patch 메서드를 사용하여 스페이스의 텍스트 또는 카드 메시지를 업데이트하는 방법을 설명합니다. 메시지를 업데이트하여 메시지 내용 또는 카드 콘텐츠와 같은 메시지 속성을 변경합니다. 카드 메시지 앞에 문자 메시지를 추가하거나 문자 메시지 앞에 카드를 추가할 수도 있습니다.

Chat API도 update 메서드를 지원하지만 patch 메서드를 호출하는 것이 좋습니다. update에서 PUT HTTP 요청을 사용하는 동안 PATCH HTTP 요청을 사용하기 때문입니다. 자세한 내용은 AIP-134의 PATCHPUT 섹션을 참고하세요.

Message 리소스는 Google Chat의 텍스트 또는 카드 메시지를 나타냅니다. 상응하는 메서드를 호출하여 Google Chat API에서 메시지를 create, get, update 또는 delete할 수 있습니다. 문자 및 카드 메시지에 관한 자세한 내용은 Google Chat 메시지 개요를 참고하세요.

기본 요건

Python

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

    pip3 install --upgrade google-api-python-client google-auth-oauthlib google-auth
    
  • Google Chat API가 사용 설정 및 구성된 Google Cloud 프로젝트 단계는 Google Chat 앱 빌드를 참고하세요.
  • 채팅 앱에 구성된 승인은 다음과 같습니다.

    • SMS를 업데이트하면 다음 인증 방법을 모두 지원합니다.
      • chat.messages 승인 범위를 사용하는 사용자 인증은 해당 사용자가 만든 메시지를 업데이트할 수 있습니다.
      • chat.bot 승인 범위를 사용하는 앱 인증은 해당 앱에서 만든 메시지를 업데이트할 수 있습니다.
    • 카드 메시지를 업데이트하려면 chat.bot 승인 범위를 사용한 앱 인증이 필요합니다.

사용자 인증을 사용하여 문자 메시지 업데이트 또는 카드 메시지 앞에 문자 메시지 추가

사용자 인증을 사용하여 SMS를 업데이트하려면 요청에 다음을 전달합니다.

  • chat.messages 승인 범위
  • 업데이트할 메시지의 name입니다.
  • updateMask='text'
  • 업데이트된 메시지를 지정하는 body입니다.

업데이트된 메시지가 카드 메시지인 경우 카드 메시지 앞에 텍스트 메시지가 추가됩니다 (계속 표시됨).

사용자 인증을 사용하여 문자 메시지를 업데이트하거나 카드 메시지 앞에 문자 메시지를 추가하는 방법은 다음과 같습니다.

Python

  1. 작업 디렉터리에서 이름이 chat_update_text_message_user.py인 파일을 만듭니다.
  2. chat_update_text_message_user.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.messages"]
    
    def main():
        '''
        Authenticates with Chat API via user credentials,
        then updates a message.
        '''
    
        # 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)
    
        # Update a Chat message.
        result = chat.spaces().messages().patch(
    
          # The message to update, and the updated message.
          #
          # Replace SPACE with a space name.
          # Obtain the space name from the spaces resource of Chat API,
          # or from a space's URL.
          #
          # Replace MESSAGE with a message name.
          # Obtain the message name from the response body returned
          # after creating a message asynchronously with Chat REST API.
          name='spaces/SPACE/messages/MESSAGE',
          updateMask='text',
          body={'text': 'Updated message!'}
    
        ).execute()
    
        # Prints details about the created membership.
        print(result)
    
    if __name__ == '__main__':
        main()
    
  3. 코드에서 다음을 바꿉니다.

    • SPACE: Chat API의 spaces.list 메서드 또는 스페이스 URL에서 가져올 수 있는 스페이스 이름입니다.
    • MESSAGE: 메시지 이름으로, Chat API를 사용하여 메시지를 비동기식으로 만들거나 생성 시 메시지에 할당된 커스텀 이름을 사용하여 메시지를 만든 후 반환된 응답 본문에서 가져올 수 있습니다.
  4. 작업 디렉터리에서 샘플을 빌드하고 실행합니다.

    python3 chat_update_text_message_user.py
    

앱 인증을 사용하여 문자 메시지 업데이트 또는 카드 메시지 앞에 문자 메시지 추가

앱 인증으로 SMS를 업데이트하려면 요청에 다음을 전달합니다.

  • chat.bot 승인 범위
  • 업데이트할 메시지의 name입니다.
  • updateMask='text'
  • 업데이트된 메시지를 지정하는 body입니다.

업데이트된 메시지가 카드 메시지인 경우 카드 메시지 앞에 텍스트 메시지가 추가됩니다 (계속 표시됨).

앱 인증을 사용하여 문자 메시지를 문자 메시지로 업데이트하거나 카드 메시지 앞에 문자 메시지를 추가하는 방법은 다음과 같습니다.

Python

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

    from google.oauth2 import service_account
    from apiclient.discovery import build
    
    # 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')
        .with_scopes(SCOPES)
    )
    
    # Build the URI and authenticate with the service account.
    chat = build('chat', 'v1', credentials=CREDENTIALS)
    
    # Update a Chat message.
    result = chat.spaces().messages().patch(
    
      # The message to update, and the updated message.
      #
      # Replace SPACE with a space name.
      # Obtain the space name from the spaces resource of Chat API,
      # or from a space's URL.
      #
      # Replace MESSAGE with a message name.
      # Obtain the message name from the response body returned
      # after creating a message asynchronously with Chat REST API.
      name='spaces/SPACE/messages/MESSAGE',
      updateMask='text',
      body={'text': 'Updated message!'}
    
    ).execute()
    
    # Print Chat API's response in your command line interface.
    print(result)
    
  3. 코드에서 다음을 바꿉니다.

    • SPACE: Chat API의 spaces.list 메서드 또는 스페이스 URL에서 가져올 수 있는 스페이스 이름입니다.
    • MESSAGE: 메시지 이름으로, Chat API를 사용하여 메시지를 비동기식으로 만들거나 생성 시 메시지에 할당된 커스텀 이름을 사용하여 메시지를 만든 후 반환된 응답 본문에서 가져올 수 있습니다.
  4. 작업 디렉터리에서 샘플을 빌드하고 실행합니다.

    python3 chat_update_text_message_app.py
    

카드 메시지 업데이트 또는 문자 메시지에 카드 메시지 추가

카드 메시지를 업데이트하려면 요청에 다음을 전달합니다.

  • chat.bot 승인 범위 카드 메시지를 업데이트하려면 앱 인증이 필요합니다.
  • 업데이트할 메시지의 name입니다.
  • updateMask='cardsV2'
  • 업데이트된 메시지를 지정하는 body입니다.

업데이트된 메시지가 문자 메시지인 경우 문자 메시지에 카드가 추가됩니다 (계속 표시됨). 업데이트된 메시지 자체가 카드이면 표시된 카드가 업데이트됩니다.

메시지를 카드 메시지로 업데이트하는 방법은 다음과 같습니다.

Python

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

    from google.oauth2 import service_account
    from apiclient.discovery import build
    
    # 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')
        .with_scopes(SCOPES)
    )
    
    # Build the URI and authenticate with the service account.
    chat = build('chat', 'v1', credentials=CREDENTIALS)
    
    # Update a Chat message.
    result = chat.spaces().messages().patch(
    
      # The message to update, and the updated message.
      #
      # Replace SPACE with a space name.
      # Obtain the space name from the spaces resource of Chat API,
      # or from a space's URL.
      #
      # Replace MESSAGE with a message name.
      # Obtain the message name from the response body returned
      # after creating a message asynchronously with Chat REST API.
      name='spaces/SPACE/messages/MESSAGE',
      updateMask='cardsV2',
      body=
      {
        'cardsV2': [{
          'cardId': 'updateCardMessage',
          'card': {
            'header': {
              'title': 'An Updated Card Message!',
              'subtitle': 'Updated with Chat REST API',
              'imageUrl': 'https://developers.google.com/chat/images/chat-product-icon.png',
              'imageType': 'CIRCLE'
            },
            'sections': [
              {
                'widgets': [
                  {
                    'buttonList': {
                      'buttons': [
                        {
                          'text': 'Read the docs!',
                          'onClick': {
                            'openLink': {
                              'url': 'https://developers.google.com/chat'
                            }
                          }
                        }
                      ]
                    }
                  }
                ]
              }
            ]
          }
        }]
      }
    
    ).execute()
    
    # Print Chat API's response in your command line interface.
    print(result)
    
  3. 코드에서 다음을 바꿉니다.

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

    • MESSAGE: 메시지 이름으로, Chat API를 사용하여 메시지를 비동기식으로 만들거나 생성 시 메시지에 할당된 커스텀 이름을 사용하여 메시지를 만든 후 반환된 응답 본문에서 가져올 수 있습니다.

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

    python3 chat_update_card_message.py
    

Chat API는 업데이트된 메시지를 자세히 설명하는 Message 인스턴스를 반환합니다.

여러 필드 경로를 사용하여 동시에 메시지 업데이트

메시지가 업데이트되면 한 번에 여러 개의 메시지 필드 경로를 업데이트할 수 있습니다. 예를 들어 업데이트 메시지 요청에서 textcardsv2 필드 경로의 변경사항을 동시에 지정할 수 있습니다. 이렇게 하면 메시지의 텍스트와 카드가 모두 업데이트됩니다. 메시지에 텍스트만 있고 카드는 없으면 카드가 메시지에 추가됩니다. 지원되는 필드 경로에 대한 자세한 내용은 updateMask 매개변수를 참조하세요.

사용자 인증을 사용하여 메시지의 textcard를 모두 업데이트하려면 요청에 다음을 전달합니다.

  • chat.messages 승인 범위
  • 업데이트할 메시지의 name입니다.
  • 업데이트할 메시지 필드 경로를 쉼표로 구분하여 지정하는 updateMask(updateMask='text', 'cardsV2')입니다.

  • 업데이트된 모든 필드 경로를 포함하여 업데이트된 메시지를 지정하는 body입니다.

사용자 인증을 사용하여 메시지의 textcardsV2 필드 경로를 업데이트하는 방법은 다음과 같습니다.

Python

  1. 작업 디렉터리에서 이름이 chat_update_text_message_user.py인 파일을 만듭니다.
  2. chat_update_text_message_user.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.messages"]
    
    def main():
        '''
        Authenticates with Chat API via user credentials,
        then updates a message.
        '''
    
        # 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)
    
        # Update a Chat message.
        result = chat.spaces().messages().patch(
    
          # The message to update, and the updated message.
          #
          # Replace SPACE with a space name.
          # Obtain the space name from the spaces resource of Chat API,
          # or from a space's URL.
          #
          # Replace MESSAGE with a message name.
          # Obtain the message name from the response body returned
          # after creating a message asynchronously with Chat REST API.
          name='spaces/SPACE/messages/MESSAGE',
          updateMask='text,cardsV2',
          body=
          {'text': 'Updated message!',
                'cardsV2': [{
                  'cardId': 'updateCardMessage',
                  'card': {
                    'header': {
                      'title': 'An Updated Card Message!',
                      'subtitle': 'Updated with Chat REST API',
                      'imageUrl': 'https://developers.google.com/chat/images/chat-product-icon.png',
                      'imageType': 'CIRCLE'
                    },
                    'sections': [
                      {
                        'widgets': [
                          {
                            'buttonList': {
                              'buttons': [
                                {
                                  'text': 'Read the docs!',
                                  'onClick': {
                                    'openLink': {
                                      'url': 'https://developers.google.com/chat'
                                    }
                                  }
                                }
                              ]
                            }
                          }
                        ]
                      }
                    ]
                  }
                }]
          }
    
        ).execute()
    
        # Prints details about the created membership.
        print(result)
    
    if __name__ == '__main__':
        main()
    
  3. 코드에서 다음을 바꿉니다.

    • SPACE: Chat API의 spaces.list 메서드 또는 스페이스 URL에서 가져올 수 있는 스페이스 이름입니다.
    • MESSAGE: 메시지 이름으로, Chat API를 사용하여 메시지를 비동기식으로 만들거나 생성 시 메시지에 할당된 커스텀 이름을 사용하여 메시지를 만든 후 반환된 응답 본문에서 가져올 수 있습니다.
  4. 작업 디렉터리에서 샘플을 빌드하고 실행합니다.

    python3 chat_update_text_message_user.py