미디어를 첨부파일로 업로드

이 가이드에서는 Google Chat API의 Media 리소스에서 upload 메서드를 사용하여 미디어 (파일)를 Google Chat에 업로드한 다음 메시지에 첨부하는 방법을 설명합니다.

사용자가 앱에 메시지를 보내면 Google Chat에서 MESSAGE 상호작용 이벤트를 전달합니다. 앱에서 수신한 상호작용 이벤트에는 모든 첨부파일을 포함한 상호작용 이벤트를 나타내는 JSON 페이로드인 요청 본문이 포함됩니다. 첨부파일의 데이터는 첨부파일이 콘텐츠 (로컬 파일) 업로드되었는지 아니면 드라이브에 저장된 파일인지에 따라 다릅니다. Media 리소스는 이미지, 동영상, 문서처럼 Google Chat에 업로드된 파일을 나타냅니다. Attachment 리소스는 메시지에 첨부된 미디어(파일)의 인스턴스를 나타냅니다. Attachment 리소스에는 첨부파일에 대한 메타데이터(예: 저장된 위치)가 포함됩니다.

기본 요건

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.messages.create 또는 chat.messages사용자 인증이 필요합니다.

첨부파일로 업로드

미디어를 업로드하고 메시지에 첨부하려면 요청에 다음을 전달합니다.

  • chat.messages.create 또는 chat.messages 승인 범위를 지정합니다.
  • 다음 Google Chat 메서드를 호출합니다.
    1. 파일을 업로드하려면 Media 리소스에서 upload 메서드를 호출합니다.
      • parent을 파일을 호스팅하는 스페이스의 스페이스 이름으로 설정합니다.
      • body (요청 본문)에서 filename을 업로드된 첨부파일의 이름으로 설정합니다.
      • media_body를 업로드할 파일의 인스턴스로 설정합니다.
    2. 업로드된 파일이 첨부된 메시지를 만들려면 Messages 리소스에서 create 메서드를 호출합니다.

다음은 PNG 이미지 파일을 업로드하여 메시지에 첨부하는 예입니다.

Python

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

    from google_auth_oauthlib.flow import InstalledAppFlow
    from googleapiclient.discovery import build
    from googleapiclient.http import MediaFileUpload
    
    # 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.create"]
    
    def main():
        '''
        Authenticates with Chat API via user credentials,
        then uploads a file as media, creates a message, and
        attaches the file to the 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.
        service = build('chat', 'v1', credentials=creds)
    
        # Upload a file to Google Chat.
        media = MediaFileUpload('test_image.png', mimetype='image/png')
    
        # Create a message and attach the uploaded file to it.
        attachment_uploaded = service.media().upload(
    
            # The space to upload the attachment in.
            #
            # Replace SPACE with a space name.
            # Obtain the space name from the spaces resource of Chat API,
            # or from a space's URL.
            parent='spaces/SPACE',
    
            # The filename of the attachment, including the file extension.
            body={'filename': 'test_image.png'},
    
            # Media resource of the attachment.
            media_body=media
    
        ).execute()
    
        print(attachment_uploaded)
    
        # Create a Chat message with attachment.
        result = service.spaces().messages().create(
    
            # The space to create the message in.
            #
            # Replace SPACE with a space name.
            # Obtain the space name from the spaces resource of Chat API,
            # or from a space's URL.
            #
            # Must match the space name that the attachment is uploaded to.
            parent='spaces/SPACE',
    
            # The message to create.
            body={
                'text': 'Hello, world!',
                'attachment': [attachment_uploaded]
            }
    
        ).execute()
    
        print(result)
    
    if __name__ == '__main__':
        main()
    
  3. 코드에서 SPACE을 첨부파일을 업로드할 스페이스 이름으로 바꿉니다. 이 이름은 Chat API의 spaces.list 메서드 또는 스페이스의 URL에서 가져올 수 있습니다.

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

    python3 chat_media_and_attachment_upload.py
    

Chat API는 업로드된 파일에 대한 세부정보와 함께 attachmentDataRef가 포함된 응답 본문을 반환합니다.

제한사항 및 고려사항

파일 업로드 및 메시지 첨부를 준비할 때 다음 한도 및 고려사항에 유의하세요.

  • 최대 200MB의 파일을 업로드할 수 있습니다.
  • 일부 파일 형식은 지원되지 않으므로 업로드할 수 없습니다. 자세한 내용은 Google Chat에서 차단되는 파일 형식을 참고하세요.