Scaricare contenuti multimediali da un file allegato
Mantieni tutto organizzato con le raccolte
Salva e classifica i contenuti in base alle tue preferenze.
Questa guida spiega come utilizzare il metodo download sulla risorsa Media dell'API Google Chat per scaricare contenuti multimediali (un file) da un messaggio in Google Chat.
Quando l'utente invia un messaggio alla tua app, Google Chat invia un
MESSAGE evento di interazione.
L'evento di interazione ricevuto dalla tua app include un corpo della richiesta, ovvero il
payload JSON che rappresenta l'evento di interazione, inclusi eventuali allegati. I dati
dell'allegato variano a seconda che l'allegato sia
un contenuto caricato (un file locale) o un file archiviato su Drive. La
risorsa Media
rappresenta un file caricato su Google Chat, come immagini, video e documenti.
La risorsa
Attachment
rappresenta un'istanza di contenuti multimediali, ovvero un file, allegato a un messaggio. La risorsa Attachment
include i metadati relativi all'allegato, ad esempio
la posizione in cui è salvato.
Per scaricare contenuti multimediali da un allegato, trasmetti quanto segue nella
richiesta:
Con l'autenticazione utente, specifica l'ambito di autorizzazione
chat.messages.readonly o chat.messages. Con l'autenticazione delle app, specifica l'ambito di autorizzazione chat.bot.
Chiama i seguenti metodi di Google Chat:
Ottieni attachmentDataRef chiamando uno dei seguenti metodi:
Chiama il metodo download
sulla
risorsa Media e specifica
attachmentDataRef.resourceName recuperato in precedenza come
media.download.resourceName.
L'esempio seguente scarica un file allegato a un messaggio:
Python
Nella directory di lavoro, crea un file denominato chat_media_and_attachment_download.py.
Includi il seguente codice in 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()
Nel codice, sostituisci RESOURCE_NAME con
attachmentDataRef.resourceName, che puoi recuperare in uno dei
seguenti modi:
Nella directory di lavoro, compila ed esegui l'esempio:
python3chat_media_and_attachment_download.py
In caso di esito positivo, questo metodo restituisce i contenuti del file come byte.
Per scaricare i contenuti del file, scegli uno dei seguenti approcci:
Ti consigliamo di utilizzare la classe MediaIoBaseDownload in Python, che contiene metodi per scaricare il file in sezioni e salvare i contenuti in un flusso di output.
Se devi effettuare la richiesta HTTP manualmente, chiama il metodo download e specifica la parte del file che vuoi scaricare utilizzando un intervallo di byte con l'intestazione Range, ad esempio: Range: bytes=500-999.
[null,null,["Ultimo aggiornamento 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)"]]