با مجموعهها، منظم بمانید
ذخیره و طبقهبندی محتوا براساس اولویتهای شما.
این راهنما نحوه استفاده از روش download را در منبع Media Google Chat API برای بارگیری رسانه (فایل) از یک پیام در Google Chat توضیح می دهد.
وقتی کاربر پیامی به برنامه شما ارسال میکند، Google Chat یک رویداد تعاملی MESSAGE را ارسال میکند. رویداد تعاملی که توسط برنامه شما دریافت میشود شامل یک بدنه درخواست است، که بار JSON نشاندهنده رویداد تعامل، از جمله هر پیوستی است. بسته به اینکه پیوست محتوای آپلود شده (فایل محلی) یا فایل ذخیره شده در Drive باشد، داده های پیوست متفاوت است. منبع Media فایلی را نشان میدهد که در چت Google آپلود شده است، مانند تصاویر، ویدیوها و اسناد. منبع Attachment نمونه ای از رسانه – یک فایل – را نشان می دهد که به یک پیام پیوست شده است. منبع Attachment شامل فراداده مربوط به پیوست است، مانند محل ذخیره آن.
اعتبارنامه دسترسی را بر اساس نحوه احراز هویت در درخواست Google Chat API خود ایجاد کنید:
برای احراز هویت به عنوان کاربر چت، اعتبار شناسه مشتری OAuth را ایجاد کنید و اعتبارنامه ها را به عنوان یک فایل JSON با نام credentials.json در فهرست محلی خود ذخیره کنید.
برای احراز هویت بهعنوان برنامه چت، اعتبار حساب سرویس ایجاد کنید و اعتبارنامهها را بهعنوان فایل JSON با نام credentials.json ذخیره کنید.
روش 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 جایگزین کنید، که می توانید یکی از راه های زیر را بازیابی کنید:
در صورت موفقیت آمیز بودن، این روش محتوای فایل را به صورت بایت برمی گرداند.
برای دانلود محتوای فایل یکی از روش های زیر را انتخاب کنید:
توصیه می کنیم از کلاس MediaIoBaseDownload در پایتون استفاده کنید که شامل روش هایی برای دانلود فایل در بخش ها و ذخیره محتویات در یک جریان خروجی است.
اگر باید درخواست HTTP را به صورت دستی انجام دهید، روش download را فراخوانی کنید و با استفاده از یک محدوده بایت با سربرگ Range ، بخشی از فایل را که میخواهید دانلود کنید مشخص کنید - به عنوان مثال: Range: bytes=500-999 .
تاریخ آخرین بهروزرسانی 2025-08-29 بهوقت ساعت هماهنگ جهانی.
[null,null,["تاریخ آخرین بهروزرسانی 2025-08-29 بهوقت ساعت هماهنگ جهانی."],[[["\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)"]]