העלאת מדיה כקובץ מצורף

במדריך הזה מוסבר איך להשתמש בשיטה upload במשאב Media של Google Chat API כדי להעלות מדיה (קובץ) ל-Google Chat ואז לצרף אותה להודעה.

כשהמשתמש שולח הודעה לאפליקציה, מערכת Google Chat שולחת אירוע אינטראקציה MESSAGE. אירוע האינטראקציה שמתקבל באפליקציה כולל גוף בקשה, שהוא מטען ייעודי (payload) בפורמט JSON שמייצג את אירוע האינטראקציה, כולל קבצים מצורפים. הנתונים בקובץ המצורף שונים בהתאם לסוג הקובץ המצורף: תוכן שהועלה (קובץ מקומי) או קובץ ששמור ב-Drive. ‫The Media resource represents a file uploaded to Google Chat, like images, videos, and documents. המשאב Attachment מייצג מופע של מדיה – קובץ – שמצורף להודעה. Attachmentהמשאב כולל את המטא-נתונים של הקובץ המצורף, כמו המיקום שבו הוא נשמר.

דרישות מוקדמות

Python

העלאה כקובץ מצורף

כדי להעלות מדיה ולצרף אותה להודעה, מעבירים את הפרטים הבאים בבקשה::

  • מציינים את היקף ההרשאות של chat.messages.create או chat.messages.
  • מפעילים את השיטות הבאות ב-Google Chat:
    1. כדי להעלות את הקובץ, מפעילים את ה-method‏ upload במשאב Media.
      • מגדירים את parent לשם המרחב שבו הקובץ מאוחסן.
      • ב-body (גוף הבקשה), מגדירים את filename לשם של הקובץ המצורף שהועלה.
      • מגדירים את media_body כמופע של הקובץ שרוצים להעלות.
    2. כדי ליצור הודעה עם הקובץ שהועלה כמצורף, צריך להפעיל את ה-method‏ create במשאב Messages.
      • מגדירים את attachment כתשובה מהתקשרות אל השיטה upload במשאב Media. השדה attachment מקבל רשימה.

בדוגמה הבאה מועלה קובץ תמונה בפורמט PNG ומצורף להודעה.

Python

  1. בספריית העבודה, יוצרים קובץ בשם chat_media_and_attachment_upload.py.
  2. מוסיפים את הקוד הבא אל 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()
    
  3. בקוד, מחליפים את SPACE בשם המרחב שאליו רוצים להעלות את הקובץ המצורף. אפשר לקבל את השם באמצעות השיטה spaces.list ב-Chat API או מכתובת ה-URL של המרחב.

  4. בספריית העבודה, מבצעים build ומריצים את הדוגמה:

    python3 chat_media_and_attachment_upload.py

‫Chat API מחזיר גוף תגובה שמכיל את attachmentDataRef עם פרטים על הקובץ שהועלה.

מגבלות ושיקולים

כשמתכוננים להעלות קבצים ולצרף אותם להודעות, חשוב לשים לב למגבלות ולשיקולים הבאים: