Upload media sebagai lampiran file

Panduan ini menjelaskan cara menggunakan metode upload pada resource Media dari Google Chat API untuk mengupload media (file) ke Google Chat, lalu melampirkannya ke pesan.

Saat pengguna mengirim pesan ke aplikasi Anda, Google Chat akan mengirimkan peristiwa interaksi MESSAGE. Peristiwa interaksi yang diterima oleh aplikasi Anda mencakup isi permintaan, yang merupakan payload JSON yang merepresentasikan peristiwa interaksi, termasuk lampiran apa pun. Data dalam lampiran berbeda-beda, bergantung pada apakah lampiran tersebut adalah konten yang diupload (file lokal) atau file yang disimpan di Drive. Resource Media merepresentasikan file yang diupload ke Google Chat, seperti gambar, video, dan dokumen. Resource Attachment mewakili instance media—file—yang dilampirkan ke pesan. Resource Attachment mencakup metadata tentang lampiran, seperti tempat lampiran disimpan.

Prasyarat

Python

Mengupload sebagai lampiran file

Untuk mengupload media dan melampirkannya ke pesan, teruskan hal berikut dalam permintaan Anda:

  • Tentukan cakupan otorisasi chat.messages.create atau chat.messages.
  • Panggil metode Google Chat berikut:
    1. Untuk mengupload file, panggil metode upload pada resource Media.
      • Tetapkan parent ke nama ruang yang menghosting file.
      • Di body (isi permintaan), tetapkan filename ke nama lampiran file yang diupload.
      • Tetapkan media_body sebagai instance file yang akan diupload.
    2. Untuk membuat pesan dengan file yang diupload terlampir, panggil metode create pada resource Messages.
      • Tetapkan attachment sebagai respons dari panggilan metode upload pada resource Media. Kolom attachment menerima daftar.

Contoh berikut mengupload file gambar PNG dan melampirkannya ke pesan.

Python

  1. Di direktori kerja Anda, buat file bernama chat_media_and_attachment_upload.py.
  2. Sertakan kode berikut di 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. Dalam kode, ganti SPACE dengan nama ruang untuk mengupload lampiran, yang dapat Anda peroleh dari metode spaces.list di Chat API, atau dari URL ruang.

  4. Di direktori kerja Anda, buat dan jalankan sampel:

    python3 chat_media_and_attachment_upload.py

Chat API menampilkan isi respons yang berisi attachmentDataRef dengan detail tentang file yang diupload.

Batas dan pertimbangan

Saat Anda bersiap untuk mengupload file dan melampirkannya ke pesan, perhatikan batas dan pertimbangan berikut: