メディアを添付ファイルとしてアップロード

このガイドでは、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 アプリ用に構成された認可。メディアを添付ファイルとしてアップロードするには、承認スコープが chat.messages.create または chat.messagesユーザー認証が必要です。

添付ファイルとしてアップロード

メディアをアップロードしてメッセージに添付するには、リクエストに次の内容を渡します。

  • chat.messages.create または chat.messages 承認スコープを指定します。
  • 次の Google Chat メソッドを呼び出します。
    1. ファイルをアップロードするには、Media リソースの upload メソッドを呼び出します。
      • parent を、ファイルをホストするスペースのスペース名に設定します。
      • body(リクエストの本文)で、filename をアップロードされた添付ファイルの名前に設定します。
      • アップロードするファイルのインスタンスとして media_body を設定します。
    2. アップロードされたファイルが添付されたメッセージを作成するには、Messages リソースに対して create メソッドを呼び出します。
      • Media リソースupload メソッド呼び出しに対するレスポンスとして attachment を設定します。attachment フィールドにはリストを指定できます。

次の例では、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 を含むレスポンス本文を返します。

制限事項と考慮事項

ファイルをアップロードしてメッセージに添付する準備をする際は、次の制限事項と考慮事項に注意してください。