本指南介绍如何在 Google Chat API 的 Media
资源上使用 get
方法来获取消息附件的相关元数据。响应是 Attachment
资源的实例。
当用户向您的应用发送消息时,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-auth
- 一个启用了并配置了 Google Chat API 的 Google Cloud 项目。如需了解相关步骤,请参阅构建 Google Chat 应用。
为 Chat 应用配置授权。如需获取消息,您需要使用
chat.bot
授权范围进行应用身份验证。
获取消息附件
如需在 Google Chat 中异步获取消息附件的相关元数据,请在请求中传递以下内容:
- 指定
chat.bot
授权范围。 - 对
Attachment
资源调用get
方法, - 传递消息附件的
name
。
下面介绍了如何获取邮件附件的相关元数据:
Python
- 在您的工作目录中,创建一个名为
chat_get_message_attachment.py
的文件。 在
chat_get_message_attachment.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) # Get a Chat message. result = chat.spaces().messages().attachments().get( # The message to get. # # 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/attachments/ATTACHMENT' ).execute() # Print Chat API's response in your command line interface. print(result)
在代码中,将
spaces/SPACE/messages/MESSAGE/attachments/ATTACHMENT
替换为消息附件名称。在您的工作目录中,构建并运行示例:
python3 chat_get_message_attachment.py
Chat API 会返回 Attachment
的实例,该实例详细说明了有关指定消息附件的元数据。