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

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

כשהמשתמש שולח הודעה לאפליקציה, Google Chat שולח אירוע אינטראקציה אחד (MESSAGE). אירוע האינטראקציה שהאפליקציה מקבלת כולל את גוף הבקשה, מטען ייעודי (payload) של JSON שמייצג את אירוע האינטראקציה, כולל קבצים מצורפים. הנתונים שבקובץ המצורף משתנים בהתאם למכשיר תוכן שהועלה (קובץ מקומי) או שהוא קובץ שמאוחסן ב-Drive. משאב אחד (Media) מייצג קובץ שהועלה ל-Google Chat, כמו תמונות, סרטונים ומסמכים. משאב אחד (Attachment) מייצג מופע של מדיה — קובץ — שמצורף להודעה. Attachment המשאב כולל את המטא-נתונים על הקובץ המצורף, כמו שבו הוא נשמר.

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

Python

  • Python 3.6 ומעלה
  • הכלי לניהול חבילות pip
  • ספריות הלקוח העדכניות של Google. כדי להתקין או לעדכן אותם, מריצים את הפקודה הבאה בממשק שורת הפקודה:
    pip3 install --upgrade google-api-python-client google-auth-oauthlib
    

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

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

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

בדוגמה הבאה מעלים קובץ תמונה בפורמט 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(
                      'client_secrets.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. בספריית העבודה, יוצרים ומריצים את הדוגמה:

    python3 chat_media_and_attachment_upload.py
    

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

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

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

  • אפשר להעלות קבצים בגודל של עד 200MB.
  • חלק מסוגי הקבצים אינם נתמכים ולא ניתן להעלות אותם. פרטים נוספים זמינים במאמר סוגי קבצים חסומים ב-Google Chat