Sử dụng bộ sưu tập để sắp xếp ngăn nắp các trang
Lưu và phân loại nội dung dựa trên lựa chọn ưu tiên của bạn.
Hướng dẫn này giải thích cách sử dụng phương thức download trên tài nguyên Media của Google Chat API để tải nội dung nghe nhìn (tệp) xuống từ một tin nhắn trong Google Chat.
Khi người dùng gửi tin nhắn đến ứng dụng của bạn, Google Chat sẽ gửi một sự kiện tương tác MESSAGE.
Sự kiện tương tác mà ứng dụng của bạn nhận được bao gồm một phần nội dung yêu cầu. Đây là tải trọng JSON đại diện cho sự kiện tương tác, bao gồm cả mọi tệp đính kèm. Dữ liệu trong tệp đính kèm sẽ khác nhau tuỳ thuộc vào việc tệp đính kèm đó là nội dung được tải lên (tệp cục bộ) hay là tệp được lưu trữ trên Drive. Tài nguyên Media đại diện cho một tệp được tải lên Google Chat, chẳng hạn như hình ảnh, video và tài liệu.
Tài nguyên Attachment biểu thị một phiên bản của nội dung nghe nhìn (một tệp) được đính kèm vào tin nhắn. Tài nguyên Attachment bao gồm siêu dữ liệu về tệp đính kèm, chẳng hạn như vị trí lưu tệp.
Tạo thông tin đăng nhập để truy cập dựa trên cách bạn muốn xác thực trong yêu cầu Google Chat API:
Để xác thực với tư cách là người dùng Chat, hãy tạo thông tin xác thực mã ứng dụng OAuth và lưu thông tin xác thực dưới dạng tệp JSON có tên credentials.json vào thư mục cục bộ của bạn.
Chọn phạm vi uỷ quyền dựa trên việc bạn muốn xác thực với tư cách là người dùng hay ứng dụng Chat.
Tải xuống từ tệp đính kèm
Để tải nội dung nghe nhìn xuống từ một tệp đính kèm, hãy truyền nội dung sau vào yêu cầu của bạn:
Với xác thực người dùng, hãy chỉ định phạm vi uỷ quyền chat.messages.readonly hoặc chat.messages. Với xác thực ứng dụng, hãy chỉ định phạm vi uỷ quyền chat.bot.
Gọi các phương thức sau của Google Chat:
Lấy attachmentDataRef bằng cách gọi một trong các phương thức sau:
Phương thức get hoặc phương thức list trên tài nguyên Message.
Gọi phương thức download trên tài nguyên Media, rồi chỉ định attachmentDataRef.resourceName đã truy xuất trước đó làm media.download.resourceName.
Ví dụ sau đây tải một tệp đính kèm vào một thông báo:
Python
Trong thư mục làm việc, hãy tạo một tệp có tên là chat_media_and_attachment_download.py.
Thêm mã sau vào chat_media_and_attachment_download.py:
importiofromgoogle_auth_oauthlib.flowimportInstalledAppFlowfromgoogleapiclient.discoveryimportbuildfromgoogleapiclient.httpimportMediaIoBaseDownload# 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"]defmain():''' Authenticates with Chat API via user credentials, then downloads a file attached to a message. '''# Authenticate with Google Workspace# and get user authorization.flow=InstalledAppFlow.from_client_secrets_file('credentials.json',SCOPES)creds=flow.run_local_server()# Build a service endpoint for Chat API.chat=build('chat','v1',credentials=creds)# Download media resource.request=chat.media().download_media(resourceName=RESOURCE_NAME,)file=io.BytesIO()downloader=MediaIoBaseDownload(file,request)done=FalsewhiledoneisFalse:status,done=downloader.next_chunk()ifstatus.total_size:print(f'Total size: {status.total_size}')print(f'Download {int(status.progress()*100)}')if__name__=='__main__':main()
Trong mã, hãy thay thế RESOURCE_NAME bằng attachmentDataRef.resourceName. Bạn có thể truy xuất một trong các cách sau:
Nếu thành công, phương thức này sẽ trả về nội dung tệp dưới dạng byte.
Để tải nội dung tệp xuống, hãy chọn một trong các phương pháp sau:
Bạn nên sử dụng lớp MediaIoBaseDownload trong Python. Lớp này chứa các phương thức để tải tệp xuống theo từng phần và lưu nội dung vào một luồng đầu ra.
Nếu bạn phải thực hiện yêu cầu HTTP theo cách thủ công, hãy gọi phương thức download và chỉ định phần tệp mà bạn muốn tải xuống bằng cách sử dụng dải byte với tiêu đề Range – ví dụ: Range: bytes=500-999.
[null,null,["Cập nhật lần gần đây nhất: 2025-08-29 UTC."],[[["\u003cp\u003eThis guide demonstrates how to download media files (like images, videos, or documents) from messages in Google Chat using the Google Chat API's \u003ccode\u003edownload\u003c/code\u003e method.\u003c/p\u003e\n"],["\u003cp\u003eThe process involves retrieving the \u003ccode\u003eattachmentDataRef\u003c/code\u003e from the \u003ccode\u003eAttachment\u003c/code\u003e or \u003ccode\u003eMessage\u003c/code\u003e resource and then using it to call the \u003ccode\u003edownload\u003c/code\u003e method on the \u003ccode\u003eMedia\u003c/code\u003e resource.\u003c/p\u003e\n"],["\u003cp\u003eYou need a Google Workspace account, a configured Google Cloud project with the Chat API enabled, and the Google API Client Library for Python to implement this functionality.\u003c/p\u003e\n"],["\u003cp\u003eThe guide provides a Python code example for authenticating with the API and downloading the file content, along with instructions on how to retrieve the necessary resource names.\u003c/p\u003e\n"]]],["To download a file from Google Chat, utilize the `download` method on the `Media` resource. First, obtain the `attachmentDataRef` by using the `get` method on the `Attachment` resource or the `get` or `list` methods on the `Message` resource. Then, call the `download` method with the retrieved `attachmentDataRef.resourceName`. For Python, the `MediaIoBaseDownload` class is recommended. Authenticate as a user or app with appropriate authorization scopes. Avoid using `thumbnailUri` or `downloadUri` fields.\n"],null,["# Download media from a file attachment\n\nThis guide explains how to use the `download` method on the `Media` resource of\nthe Google Chat API to download media (a file) from a message in Google Chat.\n\nWhen the user sends a message to your app, Google Chat dispatches a\n[`MESSAGE` interaction event](/workspace/chat/events#message).\nThe interaction event received by your app includes a request body, which is the\nJSON payload representing the interaction event, including any attachments. The\ndata in the attachment is different depending on whether the attachment is\nuploaded content (a local file) or is a file stored on Drive. The\n[`Media` resource](/workspace/chat/api/reference/rest/v1/media)\nrepresents a file uploaded to Google Chat, like images, videos, and documents.\nThe\n[`Attachment` resource](/workspace/chat/api/reference/rest/v1/spaces.messages.attachments)\nrepresents an instance of media---a file---attached to a message. The `Attachment`\nresource includes the metadata about the attachment, such as\nwhere it's saved.\n\nPrerequisites\n-------------\n\n\n### Python\n\n- A Business or Enterprise [Google Workspace](https://support.google.com/a/answer/6043576) account with access to [Google Chat](https://workspace.google.com/products/chat/).\n\n\u003c!-- --\u003e\n\n- Set up your environment:\n - [Create a Google Cloud project](/workspace/guides/create-project).\n - [Configure the OAuth consent screen](/workspace/guides/configure-oauth-consent).\n - [Enable and configure the Google Chat API](/workspace/chat/configure-chat-api) with a name, icon, and description for your Chat app.\n - Install the Python [Google API Client Library](/workspace/chat/libraries?tab=python#google-api-client-libraries).\n - Create access credentials based on how you want to authenticate in your Google Chat API request:\n - To authenticate as a Chat user, [create OAuth client ID\n credentials](/workspace/chat/authenticate-authorize-chat-user) and save the credentials as a JSON file named `credentials.json` to your local directory.\n - To authenticate as the Chat app, [create service account\n credentials](/workspace/chat/authenticate-authorize-chat-app) and save the credentials as a JSON file named `credentials.json`.\n- [Choose an authorization scope](/workspace/chat/authenticate-authorize#asynchronous-chat-calls) based on whether you want to authenticate as a user or the Chat app.\n\nDownload from a file attachment\n-------------------------------\n\nTo download media from a file attachment, pass the following in your\nrequest:\n\n- With [user authentication](/workspace/chat/authenticate-authorize-chat-user), specify the `chat.messages.readonly` or `chat.messages` authorization scope. With [app authentication](/workspace/chat/authenticate-authorize-chat-app), specify the `chat.bot` authorization scope.\n- Call the following Google Chat methods:\n 1. Get `attachmentDataRef` by calling one of the following methods:\n - The [`get` method](/workspace/chat/api/reference/rest/v1/spaces.messages.attachments/get) on the [`Attachment` resource](/workspace/chat/api/reference/rest/v1/spaces.messages.attachments).\n - The [`get` method](/workspace/chat/api/reference/rest/v1/spaces.messages/get) or the [`list` method](/workspace/chat/api/reference/rest/v1/spaces.messages/list) on the [`Message` resource](/workspace/chat/api/reference/rest/v1/spaces.messages).\n 2. Call the [`download` method](/workspace/chat/api/reference/rest/v1/media/download) on the [`Media` resource](/workspace/chat/api/reference/rest/v1/media), and specify the previously retrieved `attachmentDataRef.resourceName` as `media.download.resourceName`.\n\nThe following example downloads a file attached to a message: \n\n### Python\n\n1. In your working directory, create a file named `chat_media_and_attachment_download.py`.\n2. Include the following code in `chat_media_and_attachment_download.py`:\n\n import io\n\n from google_auth_oauthlib.flow import InstalledAppFlow\n from googleapiclient.discovery import build\n from googleapiclient.http import MediaIoBaseDownload\n\n # Define your app's authorization scopes.\n # When modifying these scopes, delete the file token.json, if it exists.\n SCOPES = [\"https://www.googleapis.com/auth/chat.messages\"]\n\n def main():\n '''\n Authenticates with Chat API via user credentials,\n then downloads a file attached to a message.\n '''\n\n # Authenticate with Google Workspace\n # and get user authorization.\n flow = InstalledAppFlow.from_client_secrets_file(\n 'credentials.json', SCOPES)\n creds = flow.run_local_server()\n\n # Build a service endpoint for Chat API.\n chat = build('chat', 'v1', credentials=creds)\n\n # Download media resource.\n request = chat.media().download_media(\n resourceName=\u003cvar translate=\"no\"\u003e\u003cspan class=\"devsite-syntax-n\"\u003eRESOURCE_NAME\u003c/span\u003e\u003c/var\u003e,\n )\n file = io.BytesIO()\n downloader = MediaIoBaseDownload(file, request)\n\n done = False\n while done is False:\n status, done = downloader.next_chunk()\n if status.total_size:\n print(f'Total size: {status.total_size}')\n print(f'Download {int(status.progress() * 100)}')\n\n if __name__ == '__main__':\n main()\n\n3. In the code, replace \u003cvar translate=\"no\"\u003eRESOURCE_NAME\u003c/var\u003e with\n `attachmentDataRef.resourceName`, which you can retrieve one of the\n following ways:\n\n - The [`get` method](/workspace/chat/api/reference/rest/v1/spaces.messages.attachments/get) on the [`Attachment` resource](/workspace/chat/api/reference/rest/v1/spaces.messages.attachments).\n - The [`get` method](/workspace/chat/api/reference/rest/v1/spaces.messages/get) on the [`Message` resource](/workspace/chat/api/reference/rest/v1/spaces.messages).\n - The [`list` method](/workspace/chat/api/reference/rest/v1/spaces.messages/list) on the [`Message` resource](/workspace/chat/api/reference/rest/v1/spaces.messages).\n4. In your working directory, build and run the sample:\n\n python3 chat_media_and_attachment_download.py\n\nIf successful, this method returns the file content as bytes.\n\nTo download the file contents, choose one of the following approaches:\n\n- We recommend using the\n `MediaIoBaseDownload` class in Python, which contains methods to download\n the file in sections and save the contents to an output stream.\n\n- If you must make the HTTP request manually, call the `download` method and\n specify the portion of the file that you want to download by using a\n [byte\n range](https://www.rfc-editor.org/rfc/rfc9110.html#name-byte-ranges) with the `Range` header---for example: `Range: bytes=500-999`.\n\n| **Note:** Don't use the `thumbnailUri` and `downloadUri` fields to access the contents of the uploaded file from your app. Use the `thumbnailUri` field to preview the attachment for a human user. The `downloadUri` field is used to let a human user download the attachment.\n\nRelated topics\n--------------\n\n- If the message is a Drive file, use the [Drive API to get access to the file](/workspace/drive/api/guides/manage-downloads).\n- [Upload media as a file attachment](/workspace/chat/upload-media-attachments)\n- [Download media as a file attachment](/workspace/chat/download-media-attachments)\n- [Get metadata about a message attachment](/workspace/chat/get-media-attachments)"]]