Tetap teratur dengan koleksi
Simpan dan kategorikan konten berdasarkan preferensi Anda.
Panduan ini menjelaskan cara menggunakan metode download pada resource Media
Google Chat API untuk mendownload media (file) dari pesan di Google Chat.
Saat pengguna mengirim pesan ke aplikasi Anda, Google Chat akan mengirimkan
peristiwa interaksi MESSAGE.
Peristiwa interaksi yang diterima oleh aplikasi Anda menyertakan isi permintaan, yang merupakan
payload JSON yang mewakili peristiwa interaksi, termasuk lampiran apa pun. Data
dalam lampiran berbeda-beda bergantung pada apakah lampiran tersebut
adalah konten yang diupload (file lokal) atau file yang disimpan di Drive. Resource Media mewakili file yang diupload ke Google Chat, seperti gambar, video, dan dokumen.
Resource Attachment mewakili instance media—file—yang dilampirkan ke pesan. Resource Attachment
menyertakan metadata tentang lampiran, seperti
tempat penyimpanannya.
Buat kredensial akses berdasarkan cara Anda ingin melakukan autentikasi dalam permintaan Google Chat API:
Untuk mengautentikasi sebagai pengguna Chat,
buat kredensial client ID
OAuth dan simpan kredensial sebagai file JSON bernama
credentials.json ke direktori lokal Anda.
Untuk mengautentikasi sebagai aplikasi Chat,
buat kredensial akun layanan dan simpan kredensial sebagai file JSON bernama
credentials.json.
Pilih cakupan otorisasi berdasarkan apakah Anda ingin mengautentikasi sebagai pengguna atau
aplikasi Chat.
Mendownload dari lampiran file
Untuk mendownload media dari lampiran file, teruskan hal berikut dalam
permintaan Anda:
Dengan autentikasi pengguna, tentukan cakupan otorisasi chat.messages.readonly atau chat.messages. Dengan
autentikasi aplikasi,
tentukan cakupan otorisasi chat.bot.
Panggil metode Google Chat berikut:
Dapatkan attachmentDataRef dengan memanggil salah satu metode berikut:
Panggil metode download
di
resource Media, dan tentukan
attachmentDataRef.resourceName yang diambil sebelumnya sebagai
media.download.resourceName.
Contoh berikut mendownload file yang dilampirkan ke pesan:
Python
Di direktori kerja Anda, buat file bernama
chat_media_and_attachment_download.py.
Sertakan kode berikut di 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()
Dalam kode, ganti RESOURCE_NAME dengan
attachmentDataRef.resourceName, yang dapat Anda ambil dengan salah satu
cara berikut:
Jika berhasil, metode ini akan menampilkan konten file sebagai byte.
Untuk mendownload konten file, pilih salah satu pendekatan berikut:
Sebaiknya gunakan
class MediaIoBaseDownload di Python, yang berisi metode untuk mendownload
file dalam beberapa bagian dan menyimpan konten ke aliran output.
Jika Anda harus membuat permintaan HTTP secara manual, panggil metode download dan
tentukan bagian file yang ingin Anda download menggunakan
rentang
byte dengan header Range—misalnya: Range: bytes=500-999.
[[["Mudah dipahami","easyToUnderstand","thumb-up"],["Memecahkan masalah saya","solvedMyProblem","thumb-up"],["Lainnya","otherUp","thumb-up"]],[["Informasi yang saya butuhkan tidak ada","missingTheInformationINeed","thumb-down"],["Terlalu rumit/langkahnya terlalu banyak","tooComplicatedTooManySteps","thumb-down"],["Sudah usang","outOfDate","thumb-down"],["Masalah terjemahan","translationIssue","thumb-down"],["Masalah kode / contoh","samplesCodeIssue","thumb-down"],["Lainnya","otherDown","thumb-down"]],["Terakhir diperbarui pada 2025-06-05 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,["This 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\nPython\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\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\nPython\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- 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)"]]