以文件附件形式上传媒体内容

本指南介绍如何在 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.createchat.messages 授权范围的用户身份验证

以文件附件的形式上传

如需上传媒体并将其附加到消息,请在请求中传递以下内容:

  • 指定 chat.messages.createchat.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 方法或聊天室网址获取。

  4. 在您的工作目录中,构建并运行示例:

    python3 chat_media_and_attachment_upload.py
    

Chat API 会返回包含 attachmentDataRef 的响应正文,其中包含已上传文件的详细信息。

限制和注意事项

在准备上传文件并将其附加到消息时,请注意以下限制和注意事项: