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

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

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

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

Python

  • Python 3.6 ואילך
  • הכלי pip לניהול חבילות
  • ספריות הלקוח העדכניות של Google ל-Python. כדי להתקין או לעדכן אותן, מריצים את הפקודה הבאה בממשק שורת הפקודה:

    pip3 install --upgrade google-api-python-client google-auth-oauthlib
    
  • פרויקט ב-Google Cloud עם ממשק Google Chat API פעיל ומוגדר. במאמר איך יוצרים אפליקציה ל-Google Chat מוסבר איך עושים זאת.
  • הוגדרה הרשאה לאפליקציית Chat. כדי להעלות מדיה כקובץ מצורף, צריך אימות משתמש עם היקף ההרשאות chat.messages.create או chat.messages.

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

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

  • צריך לציין את היקף ההרשאה chat.messages.create או chat.messages.
  • מפעילים את השיטות הבאות ב-Google Chat:
    1. כדי להעלות את הקובץ, צריך להפעיל את השיטה method upload במשאב Media.
      • בוחרים את השם של המרחב המשותף שמארח את הקובץ parent.
      • ב-body (גוף הבקשה), מגדירים את filename לשם של הקובץ המצורף לקובץ שהועלה.
      • מגדירים את media_body כמופע של הקובץ להעלאה.
    2. כדי ליצור הודעה עם הקובץ שהועלה, צריך לקרוא ל-method 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 בשם של המרחב המשותף כדי להעלות את הקובץ המצורף. אפשר לקבל אותו מה-method spaces.list ב-Chat API או מכתובת ה-URL של המרחב המשותף.

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

    python3 chat_media_and_attachment_upload.py
    

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

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

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

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