Оптимизируйте свои подборки
Сохраняйте и классифицируйте контент в соответствии со своими настройками.
В этом руководстве объясняется, как использовать метод download на ресурсе Media API Google Chat для загрузки медиафайла (файла) из сообщения в Google Chat.
Когда пользователь отправляет сообщение в ваше приложение, Google Chat отправляет событие взаимодействия MESSAGE . Событие взаимодействия, полученное вашим приложением, включает тело запроса, представляющее собой полезную нагрузку JSON, представляющую событие взаимодействия, включая любые вложения. Данные во вложении различаются в зависимости от того, является ли вложение загруженным контентом (локальным файлом) или файлом, хранящимся на Диске. Ресурс Media представляет собой файл, загруженный в Google Chat, такой как изображения, видео и документы. Ресурс Attachment представляет собой экземпляр медиафайла (файла), прикрепленного к сообщению. Ресурс Attachment содержит метаданные о вложении, например, место его сохранения.
Вызовите метод download на ресурсе Media и укажите ранее извлеченный attachmentDataRef.resourceName как media.download.resourceName .
В следующем примере загружается файл, прикрепленный к сообщению:
Питон
В рабочем каталоге создайте файл с именем chat_media_and_attachment_download.py .
Включите следующий код в 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()
В коде замените RESOURCE_NAME на attachmentDataRef.resourceName , который можно получить одним из следующих способов:
В вашем рабочем каталоге соберите и запустите пример:
python3chat_media_and_attachment_download.py
В случае успеха этот метод возвращает содержимое файла в виде байтов.
Чтобы загрузить содержимое файла, выберите один из следующих способов:
Мы рекомендуем использовать класс MediaIoBaseDownload в Python, который содержит методы для загрузки файла по разделам и сохранения содержимого в выходном потоке.
Если вам необходимо сделать HTTP-запрос вручную, вызовите метод download и укажите часть файла, которую вы хотите загрузить, используя диапазон байтов с заголовком Range , например: Range: bytes=500-999 .
[null,null,["Последнее обновление: 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)"]]