تحميل الوسائط كمرفق ملف
تنظيم صفحاتك في مجموعات
يمكنك حفظ المحتوى وتصنيفه حسب إعداداتك المفضّلة.
يشرح هذا الدليل كيفية استخدام طريقة upload
في مورد Media
ضمن Google Chat API لتحميل وسائط (ملف) إلى Google Chat ثم إرفاقها برسالة.
عندما يرسل المستخدم رسالة إلى تطبيقك، يرسل Google Chat حدث تفاعل MESSAGE
.
يتضمّن حدث التفاعل الذي يتلقّاه تطبيقك نص طلب، وهو حمولة JSON التي تمثّل حدث التفاعل، بما في ذلك أي مرفقات. تختلف البيانات في المرفق حسب ما إذا كان المرفق محتوًى تم تحميله (ملف محلي) أو ملفًا مخزّنًا على Drive. يمثّل
Media
المورد
ملفًا تم تحميله إلى Google Chat، مثل الصور والفيديوهات والمستندات.
يمثّل مورد
Attachment
مثيلاً للوسائط، أي ملفًا مرفقًا برسالة. يتضمّن Attachment
المورد البيانات الوصفية حول المرفق، مثل
مكان حفظه.
المتطلبات الأساسية
تحميل الملف كمرفق
لتحميل وسائط وإرفاقها برسالة، أدرِج ما يلي في طلبك:
- حدِّد نطاق تفويض
chat.messages.create
أو chat.messages
.
- استدعاء طرق Google Chat التالية:
- لتحميل الملف، استدعِ الطريقة
upload
في المورد Media
.
- اضبط
parent
على اسم المساحة التي تستضيف الملف.
- في
body
(نص الطلب)، اضبط filename
على اسم مرفق الملف الذي تم تحميله.
- اضبط
media_body
كمثيل للملف الذي سيتم تحميله.
- لإنشاء رسالة مع إرفاق الملف الذي تم تحميله، استدعِ الطريقة
create
في المورد
Messages
.
- اضبط
attachment
كاستجابة من خلال استدعاء الطريقة
upload
على المورد
Media
. يقبل الحقل attachment
قائمة.
يحمّل المثال التالي ملف صورة بتنسيق PNG ويرفقه برسالة.
Python
- في دليل العمل، أنشئ ملفًا باسم
chat_media_and_attachment_upload.py
.
أدرِج الرمز التالي في chat_media_and_attachment_upload.py
:
from google_auth_oauthlib.flow import InstalledAppFlow
from googleapiclient.discovery import build
from googleapiclient.http import MediaFileUpload
# 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.create"]
def main():
'''
Authenticates with Chat API via user credentials,
then uploads a file as media, creates a message, and
attaches the file to the 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.
service = build('chat', 'v1', credentials=creds)
# Upload a file to Google Chat.
media = MediaFileUpload('test_image.png', mimetype='image/png')
# Create a message and attach the uploaded file to it.
attachment_uploaded = service.media().upload(
# The space to upload the attachment in.
#
# Replace SPACE with a space name.
# Obtain the space name from the spaces resource of Chat API,
# or from a space's URL.
parent='spaces/SPACE',
# The filename of the attachment, including the file extension.
body={'filename': 'test_image.png'},
# Media resource of the attachment.
media_body=media
).execute()
print(attachment_uploaded)
# Create a Chat message with attachment.
result = service.spaces().messages().create(
# The space to create the message in.
#
# Replace SPACE with a space name.
# Obtain the space name from the spaces resource of Chat API,
# or from a space's URL.
#
# Must match the space name that the attachment is uploaded to.
parent='spaces/SPACE',
# The message to create.
body={
'text': 'Hello, world!',
'attachment': [attachment_uploaded]
}
).execute()
print(result)
if __name__ == '__main__':
main()
في الرمز، استبدِل SPACE
باسم المساحة التي تريد تحميل المرفق فيها، ويمكنك الحصول على هذا الاسم من خلال الطريقة spaces.list
في Chat API أو من عنوان URL الخاص بمساحة.
في دليل العمل، أنشئ النموذج وشغِّله:
python3 chat_media_and_attachment_upload.py
تعرض Chat API نص استجابة يحتوي على attachmentDataRef
مع تفاصيل حول الملف الذي تم تحميله.
الحدود والاعتبارات
عند الاستعداد لتحميل الملفات وإرفاقها بالرسائل، يُرجى الانتباه إلى الحدود والاعتبارات التالية:
إنّ محتوى هذه الصفحة مرخّص بموجب ترخيص Creative Commons Attribution 4.0 ما لم يُنصّ على خلاف ذلك، ونماذج الرموز مرخّصة بموجب ترخيص Apache 2.0. للاطّلاع على التفاصيل، يُرجى مراجعة سياسات موقع Google Developers. إنّ Java هي علامة تجارية مسجَّلة لشركة Oracle و/أو شركائها التابعين.
تاريخ التعديل الأخير: 2025-08-04 (حسب التوقيت العالمي المتفَّق عليه)
[null,null,["تاريخ التعديل الأخير: 2025-08-04 (حسب التوقيت العالمي المتفَّق عليه)"],[[["\u003cp\u003eThis guide demonstrates how to upload a file to Google Chat and attach it to a message using the \u003ccode\u003eupload\u003c/code\u003e method of the \u003ccode\u003eMedia\u003c/code\u003e resource and the \u003ccode\u003ecreate\u003c/code\u003e method of the \u003ccode\u003eMessages\u003c/code\u003e resource.\u003c/p\u003e\n"],["\u003cp\u003eYou'll need a Google Workspace account, a Google Cloud project, and the Google Chat API enabled to follow the steps outlined in this guide.\u003c/p\u003e\n"],["\u003cp\u003eThe provided Python code sample requires specific authorization scopes and utilizes the Google API Client Library for interaction with the Chat API.\u003c/p\u003e\n"],["\u003cp\u003eFile uploads are limited to 200 MB and certain file types are blocked; messages with attachments cannot include accessory widgets.\u003c/p\u003e\n"]]],["To upload and attach a file to a Google Chat message using the Chat API, first, call the `upload` method on the `Media` resource. Set the space name as the `parent`, the file name, and `media_body` with the file instance. Then, use the `create` method on the `Messages` resource to send a message, including the `attachment` field, set as the response from the `upload` method. File size should not exceed 200MB and some file types are not supported.\n"],null,["# Upload media as a file attachment\n\nThis guide explains how to use the `upload` method on the `Media` resource of\nthe Google Chat API to upload media (a file) to Google Chat and then attach it to\na message.\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 OAuth client ID credentials](/workspace/chat/authenticate-authorize-chat-user#step-2:) for a desktop application. To run the sample in this guide, save the credentials as a JSON file named `credentials.json` to your local directory.\n- [Choose an authorization scope](/workspace/chat/authenticate-authorize#asynchronous-chat-calls) that supports user authentication.\n\nUpload as a file attachment\n---------------------------\n\nTo upload media and attach it to a message, pass the following in your\nrequest::\n\n- Specify the `chat.messages.create` or `chat.messages` authorization scope.\n- Call the following Google Chat methods:\n 1. To upload the file, call the [`upload` method](/workspace/chat/api/reference/rest/v1/media/upload) on the [`Media`](/workspace/chat/api/reference/rest/v1/media) resource.\n - Set `parent` to the space name of the space that hosts the file.\n - In `body` (the request body), set `filename` to the name of the uploaded file attachment.\n - Set `media_body` as an instance of the file to be uploaded.\n 2. To create a message with the uploaded file attached, call the [`create` method](/workspace/chat/api/reference/rest/v1/spaces.messages/create) on the [`Messages` resource](/workspace/chat/api/reference/rest/v1/spaces.messages).\n - Set `attachment` as the response from calling the [`upload` method](/workspace/chat/api/reference/rest/v1/media/upload) on the [`Media` resource](/workspace/chat/api/reference/rest/v1/media). The `attachment` field accepts a list.\n\nThe following example uploads a PNG image file and attaches it to a message. \n\n### Python\n\n1. In your working directory, create a file named `chat_media_and_attachment_upload.py`.\n2. Include the following code in `chat_media_and_attachment_upload.py`:\n\n from google_auth_oauthlib.flow import InstalledAppFlow\n from googleapiclient.discovery import build\n from googleapiclient.http import MediaFileUpload\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.create\"]\n\n def main():\n '''\n Authenticates with Chat API via user credentials,\n then uploads a file as media, creates a message, and\n attaches the file to the 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 service = build('chat', 'v1', credentials=creds)\n\n # Upload a file to Google Chat.\n media = MediaFileUpload('test_image.png', mimetype='image/png')\n\n # Create a message and attach the uploaded file to it.\n attachment_uploaded = service.media().upload(\n\n # The space to upload the attachment in.\n #\n # Replace SPACE with a space name.\n # Obtain the space name from the spaces resource of Chat API,\n # or from a space's URL.\n parent='spaces/\u003cvar translate=\"no\"\u003eSPACE\u003c/var\u003e',\n\n # The filename of the attachment, including the file extension.\n body={'filename': 'test_image.png'},\n\n # Media resource of the attachment.\n media_body=media\n\n ).execute()\n\n print(attachment_uploaded)\n\n # Create a Chat message with attachment.\n result = service.spaces().messages().create(\n\n # The space to create the message in.\n #\n # Replace SPACE with a space name.\n # Obtain the space name from the spaces resource of Chat API,\n # or from a space's URL.\n #\n # Must match the space name that the attachment is uploaded to.\n parent='spaces/\u003cvar translate=\"no\"\u003eSPACE\u003c/var\u003e',\n\n # The message to create.\n body={\n 'text': 'Hello, world!',\n 'attachment': [attachment_uploaded]\n }\n\n ).execute()\n\n print(result)\n\n if __name__ == '__main__':\n main()\n\n3. In the code, replace \u003cvar translate=\"no\"\u003eSPACE\u003c/var\u003e with the space name to\n upload the attachment in, which you can obtain from the\n [`spaces.list` method](/workspace/chat/api/reference/rest/v1/spaces/list)\n in the Chat API, or from a space's URL.\n\n4. In your working directory, build and run the sample:\n\n python3 chat_media_and_attachment_upload.py\n\nThe Chat API returns a response body containing\n`attachmentDataRef` with details about the uploaded file.\n\nLimits and considerations\n-------------------------\n\nAs you prepare to upload files and attach them to messages, take note of these\nlimits and considerations:\n\n- You can upload file sizes up to 200 MB.\n- Some file types aren't supported, and can't be uploaded. For details, see [File types blocked in Google Chat](https://support.google.com/chat/answer/7651457?&co=GENIE.Platform%3DDesktop#File%20types%20blocked%20in%20Google%20Chat).\n- Your message must omit [accessory widgets](/workspace/chat/api/reference/rest/v1/spaces.messages#Message.FIELDS.accessory_widgets).\n\nRelated topics\n--------------\n\n- [Download media as a file attachment](/workspace/chat/download-media-attachments)\n- [Get metadata about a message attachment](/workspace/chat/get-media-attachments)"]]