Mengirim pesan menggunakan Google Chat API

Panduan ini menjelaskan cara memanggil API Google Chat messages.create() metode untuk melakukan salah satu tindakan berikut:

  • Kirim pesan yang berisi teks, kartu, dan widget interaktif.
  • Mengirim pesan secara pribadi kepada pengguna Chat tertentu.
  • Memulai atau membalas rangkaian pesan.
  • Beri nama pesan sehingga Anda dapat menentukannya di Chat API lain permintaan.

Ukuran pesan maksimum (termasuk teks atau kartu apa pun) adalah 32.000 byte. Untuk mengirim pesan yang melebihi ukuran ini, aplikasi Chat Anda harus mengirim beberapa pesan.

Selain memanggil metode messages.create(), aplikasi Chat dapat membuat dan mengirim pesan untuk membalas interaksi pengguna, seperti memposting pesan selamat datang setelah pengguna menambahkan aplikasi Chat ke spasi. Saat merespons interaksi, aplikasi Chat dapat menggunakan jenis fitur pesan, termasuk dialog interaktif dan pratinjau link antarmuka. Untuk membalas pengguna, aplikasi Chat akan kembali pesan secara sinkron, tanpa memanggil Chat API. Untuk mempelajari tentang mengirim pesan untuk merespons interaksi, lihat Menerima dan merespons interaksi dengan aplikasi Google Chat.

Cara Chat menampilkan dan mengatribusikan pesan yang dibuat dengan Chat API

Anda dapat memanggil metode messages.create() menggunakan autentikasi aplikasi dan autentikasi pengguna. Chat mengatribusikan pengirim pesan secara berbeda tergantung pada jenis otentikasi yang Anda gunakan.

Saat Anda melakukan autentikasi sebagai aplikasi Chat, aplikasi Chat mengirimkan pesan.

Memanggil metode messages.create() dengan autentikasi aplikasi.
Gambar 1: Dengan autentikasi aplikasi, aplikasi Chat mengirim menulis pesan. Perlu diketahui bahwa pengirim bukan orang, Chat menampilkan App di samping namanya.

Saat Anda melakukan autentikasi sebagai pengguna, aplikasi Chat akan mengirim pesan atas nama pengguna. Chat juga mengaitkan Aplikasi Chat ke pesan dengan menampilkan namanya.

Memanggil metode messages.create() dengan autentikasi pengguna.
Gambar 2: Dengan autentikasi pengguna, pengguna dapat mengirim pesan, dan Chat menampilkan Nama aplikasi Chat di samping nama pengguna.

Jenis otentikasi juga menentukan fitur dan antarmuka pesan mana yang dapat Anda sertakan dalam pesan tersebut. Dengan otentikasi aplikasi, Aplikasi chat dapat mengirim pesan yang berisi teks kaya, antarmuka berbasis kartu, dan {i>widget<i} interaktif. Karena pengguna Chat hanya dapat mengirim teks dalam pesan mereka, Anda dapat hanya menyertakan teks saat membuat pesan menggunakan otentikasi pengguna. Untuk mempelajari fitur pesan lebih lanjut yang tersedia untuk Chat API, lihat Ringkasan pesan Google Chat.

Panduan ini menjelaskan cara menggunakan salah satu jenis autentikasi untuk mengirim pesan dengan Chat API.

Prasyarat

Node.js

Python

Java

Apps Script

Mengirim pesan sebagai aplikasi Chat

Bagian ini menjelaskan cara mengirim pesan yang berisi teks, kartu, dan widget aksesori interaktif menggunakan autentikasi aplikasi.

Pesan dikirim dengan autentikasi aplikasi
Gambar 4. Aplikasi Chat mengirim pesan dengan teks, kartu, dan tombol aksesori.

Untuk memanggil messages.create() menggunakan autentikasi aplikasi, Anda harus menentukan kolom berikut dalam permintaan:

  • Cakupan otorisasi chat.bot.
  • Resource Space tempat tempat Anda ingin memposting pesan. Aplikasi Chat harus anggota ruang.
  • Message resource yang akan dibuat. Untuk menentukan isi pesan, Anda dapat menyertakan teks kaya (text), satu atau beberapa antarmuka kartu (cardsV2), atau keduanya.

Secara opsional, Anda dapat menyertakan hal berikut:

Kode berikut menunjukkan contoh cara aplikasi Chat dapat mengirim pesan yang diposting sebagai aplikasi Chat yang berisi teks, kartu, dan tombol yang dapat diklik di bagian bawah pesan:

Node.js

chat/client-libraries/cloud/create-message-app-cred.js
import {createClientWithAppCredentials} from './authentication-utils.js';

// This sample shows how to create message with app credential
async function main() {
  // Create a client
  const chatClient = createClientWithAppCredentials();

  // Initialize request argument(s)
  const request = {
    // Replace SPACE_NAME here.
    parent: 'spaces/SPACE_NAME',
    message: {
      text: '👋🌎 Hello world! I created this message by calling ' +
            'the Chat API\'s `messages.create()` method.',
      cardsV2 : [{ card: {
        header: {
          title: 'About this message',
          imageUrl: 'https://fonts.gstatic.com/s/i/short-term/release/googlesymbols/info/default/24px.svg'
        },
        sections: [{
          header: 'Contents',
          widgets: [{ textParagraph: {
              text: '🔡 <b>Text</b> which can include ' +
                    'hyperlinks 🔗, emojis 😄🎉, and @mentions 🗣️.'
            }}, { textParagraph: {
              text: '🖼️ A <b>card</b> to display visual elements' +
                    'and request information such as text 🔤, ' +
                    'dates and times 📅, and selections ☑️.'
            }}, { textParagraph: {
              text: '👉🔘 An <b>accessory widget</b> which adds ' +
                    'a button to the bottom of a message.'
            }}
          ]}, {
            header: "What's next",
            collapsible: true,
            widgets: [{ textParagraph: {
                text: "❤️ <a href='https://developers.google.com/workspace/chat/api/reference/rest/v1/spaces.messages.reactions/create'>Add a reaction</a>."
              }}, { textParagraph: {
                text: "🔄 <a href='https://developers.google.com/workspace/chat/api/reference/rest/v1/spaces.messages/patch'>Update</a> " +
                      "or  <a href='https://developers.google.com/workspace/chat/api/reference/rest/v1/spaces.messages/delete'>delete</a> " +
                      "the message."
              }
            }]
          }
        ]
      }}],
      accessoryWidgets: [{ buttonList: { buttons: [{
        text: 'View documentation',
        icon: { materialIcon: { name: 'link' }},
        onClick: { openLink: {
          url: 'https://developers.google.com/workspace/chat/create-messages'
        }}
      }]}}]
    }
  };

  // Make the request
  const response = await chatClient.createMessage(request);

  // Handle the response
  console.log(response);
}

main().catch(console.error);

Python

chat/client-libraries/cloud/create_message_app_cred.py
from authentication_utils import create_client_with_app_credentials
from google.apps import chat_v1 as google_chat

# This sample shows how to create message with app credential
def create_message_with_app_cred():
    # Create a client
    client = create_client_with_app_credentials()

    # Initialize request argument(s)
    request = google_chat.CreateMessageRequest(
        # Replace SPACE_NAME here.
        parent = "spaces/SPACE_NAME",
        message = {
            "text": '👋🌎 Hello world! I created this message by calling ' +
                    'the Chat API\'s `messages.create()` method.',
            "cards_v2" : [{ "card": {
                "header": {
                    "title": 'About this message',
                    "image_url": 'https://fonts.gstatic.com/s/i/short-term/release/googlesymbols/info/default/24px.svg'
                },
                "sections": [{
                    "header": "Contents",
                    "widgets": [{ "text_paragraph": {
                            "text": '🔡 <b>Text</b> which can include ' +
                                    'hyperlinks 🔗, emojis 😄🎉, and @mentions 🗣️.'
                        }}, { "text_paragraph": {
                            "text": '🖼️ A <b>card</b> to display visual elements' +
                                    'and request information such as text 🔤, ' +
                                    'dates and times 📅, and selections ☑️.'
                        }}, { "text_paragraph": {
                            "text": '👉🔘 An <b>accessory widget</b> which adds ' +
                                    'a button to the bottom of a message.'
                        }}
                    ]}, {
                        "header": "What's next",
                        "collapsible": True,
                        "widgets": [{ "text_paragraph": {
                                "text": "❤️ <a href='https://developers.google.com/workspace/chat/api/reference/rest/v1/spaces.messages.reactions/create'>Add a reaction</a>."
                            }}, { "text_paragraph": {
                                "text": "🔄 <a href='https://developers.google.com/workspace/chat/api/reference/rest/v1/spaces.messages/patch'>Update</a> " +
                                        "or  <a href='https://developers.google.com/workspace/chat/api/reference/rest/v1/spaces.messages/delete'>delete</a> " +
                                        "the message."
                            }
                        }]
                    }
                ]
            }}],
            "accessory_widgets": [{ "button_list": { "buttons": [{
                "text": 'View documentation',
                "icon": { "material_icon": { "name": 'link' }},
                "on_click": { "open_link": {
                    "url": 'https://developers.google.com/workspace/chat/create-messages'
                }}
            }]}}]
        }
    )

    # Make the request
    response = client.create_message(request)

    # Handle the response
    print(response)

create_message_with_app_cred()

Java

chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/CreateMessageAppCred.java
import com.google.apps.card.v1.Button;
import com.google.apps.card.v1.ButtonList;
import com.google.apps.card.v1.Card;
import com.google.apps.card.v1.Icon;
import com.google.apps.card.v1.MaterialIcon;
import com.google.apps.card.v1.OnClick;
import com.google.apps.card.v1.OpenLink;
import com.google.apps.card.v1.TextParagraph;
import com.google.apps.card.v1.Widget;
import com.google.apps.card.v1.Card.CardHeader;
import com.google.apps.card.v1.Card.Section;
import com.google.chat.v1.AccessoryWidget;
import com.google.chat.v1.CardWithId;
import com.google.chat.v1.ChatServiceClient;
import com.google.chat.v1.CreateMessageRequest;
import com.google.chat.v1.Message;

// This sample shows how to create message with app credential.
public class CreateMessageAppCred {

  public static void main(String[] args) throws Exception {
    try (ChatServiceClient chatServiceClient =
        AuthenticationUtils.createClientWithAppCredentials()) {
      CreateMessageRequest.Builder request = CreateMessageRequest.newBuilder()
        // Replace SPACE_NAME here.
        .setParent("spaces/SPACE_NAME")
        .setMessage(Message.newBuilder()
          .setText( "👋🌎 Hello world! I created this message by calling " +
                    "the Chat API\'s `messages.create()` method.")
          .addCardsV2(CardWithId.newBuilder().setCard(Card.newBuilder()
            .setHeader(CardHeader.newBuilder()
              .setTitle("About this message")
              .setImageUrl("https://fonts.gstatic.com/s/i/short-term/release/googlesymbols/info/default/24px.svg"))
            .addSections(Section.newBuilder()
              .setHeader("Contents")
              .addWidgets(Widget.newBuilder().setTextParagraph(TextParagraph.newBuilder().setText(
                "🔡 <b>Text</b> which can include " +
                "hyperlinks 🔗, emojis 😄🎉, and @mentions 🗣️.")))
              .addWidgets(Widget.newBuilder().setTextParagraph(TextParagraph.newBuilder().setText(
                "🖼️ A <b>card</b> to display visual elements " +
                "and request information such as text 🔤, " +
                "dates and times 📅, and selections ☑️.")))
              .addWidgets(Widget.newBuilder().setTextParagraph(TextParagraph.newBuilder().setText(
                "👉🔘 An <b>accessory widget</b> which adds " +
                "a button to the bottom of a message."))))
            .addSections(Section.newBuilder()
              .setHeader("What's next")
              .setCollapsible(true)
              .addWidgets(Widget.newBuilder().setTextParagraph(TextParagraph.newBuilder().setText(
                "❤️ <a href='https://developers.google.com/workspace/chat/api/reference/rest/v1/spaces.messages.reactions/create'>Add a reaction</a>.")))
              .addWidgets(Widget.newBuilder().setTextParagraph(TextParagraph.newBuilder().setText(
                "🔄 <a href='https://developers.google.com/workspace/chat/api/reference/rest/v1/spaces.messages/patch'>Update</a> " +
                "or  <a href='https://developers.google.com/workspace/chat/api/reference/rest/v1/spaces.messages/delete'>delete</a> " +
                "the message."))))))
          .addAccessoryWidgets(AccessoryWidget.newBuilder()
            .setButtonList(ButtonList.newBuilder()
              .addButtons(Button.newBuilder()
                .setText("View documentation")
                .setIcon(Icon.newBuilder()
                  .setMaterialIcon(MaterialIcon.newBuilder().setName("link")))
                .setOnClick(OnClick.newBuilder()
                  .setOpenLink(OpenLink.newBuilder()
                    .setUrl("https://developers.google.com/workspace/chat/create-messages")))))));
      Message response = chatServiceClient.createMessage(request.build());

      System.out.println(JsonFormat.printer().print(response));
    }
  }
}

Apps Script

chat/advanced-service/Main.gs
/**
 * This sample shows how to create message with app credential
 * 
 * It relies on the OAuth2 scope 'https://www.googleapis.com/auth/chat.bot'
 * used by service accounts.
 */
function createMessageAppCred() {
  // Initialize request argument(s)
  // TODO(developer): Replace SPACE_NAME here.
  const parent = 'spaces/SPACE_NAME';
  const message = {
    text: '👋🌎 Hello world! I created this message by calling ' +
          'the Chat API\'s `messages.create()` method.',
    cardsV2 : [{ card: {
      header: {
        title: 'About this message',
        imageUrl: 'https://fonts.gstatic.com/s/i/short-term/release/googlesymbols/info/default/24px.svg'
      },
      sections: [{
        header: 'Contents',
        widgets: [{ textParagraph: {
            text: '🔡 <b>Text</b> which can include ' +
                  'hyperlinks 🔗, emojis 😄🎉, and @mentions 🗣️.'
          }}, { textParagraph: {
            text: '🖼️ A <b>card</b> to display visual elements' +
                  'and request information such as text 🔤, ' +
                  'dates and times 📅, and selections ☑️.'
          }}, { textParagraph: {
            text: '👉🔘 An <b>accessory widget</b> which adds ' +
                  'a button to the bottom of a message.'
          }}
        ]}, {
          header: "What's next",
          collapsible: true,
          widgets: [{ textParagraph: {
              text: "❤️ <a href='https://developers.google.com/workspace/chat/api/reference/rest/v1/spaces.messages.reactions/create'>Add a reaction</a>."
            }}, { textParagraph: {
              text: "🔄 <a href='https://developers.google.com/workspace/chat/api/reference/rest/v1/spaces.messages/patch'>Update</a> " +
                    "or  <a href='https://developers.google.com/workspace/chat/api/reference/rest/v1/spaces.messages/delete'>delete</a> " +
                    "the message."
            }
          }]
        }
      ]
    }}],
    accessoryWidgets: [{ buttonList: { buttons: [{
      text: 'View documentation',
      icon: { materialIcon: { name: 'link' }},
      onClick: { openLink: {
        url: 'https://developers.google.com/workspace/chat/create-messages'
      }}
    }]}}]
  };
  const parameters = {};

  // Make the request
  const response = Chat.Spaces.Messages.create(
    message, parent, parameters, getHeaderWithAppCredentials()
  );

  // Handle the response
  console.log(response);
}

Untuk menjalankan contoh ini, ganti SPACE_NAME dengan ID dari ruang Kolom name. Anda bisa mendapatkan ID dengan memanggil Metode spaces.list() atau dari URL ruang.

Menambahkan widget interaktif di bagian bawah pesan

Dalam contoh kode pertama dari panduan ini, Pesan aplikasi Chat menampilkan tombol yang dapat diklik di bagian bawah pesan, yang dikenal sebagai widget aksesori. Widget aksesori akan muncul setelah teks atau kartu dalam pesan. Anda dapat menggunakan widget ini untuk berinteraksi dengan pesan Anda dalam banyak cara, termasuk hal berikut:

  • Memberi rating akurasi atau kepuasan pesan.
  • Laporkan masalah terkait pesan atau aplikasi Chat.
  • Buka link ke konten terkait, seperti dokumentasi.
  • Menutup atau menunda pesan serupa dari aplikasi Chat selama jangka waktu tertentu.

Untuk menambahkan widget aksesori, sertakan accessoryWidgets[] di isi permintaan Anda dan tentukan satu atau beberapa widget yang diinginkan untuk disertakan.

Gambar berikut menunjukkan aplikasi Chat yang menambahkan pesan teks dengan widget aksesori agar pengguna dapat menilai pengalaman mereka dengan aplikasi Chat.

Widget aksesori.
Gambar 5: Pesan aplikasi Chat dengan widget teks dan aksesori.

Berikut ini adalah isi permintaan yang membuat pesan teks dengan dua tombol aksesori. Saat pengguna mengeklik tombol, atribut (seperti doUpvote) memproses interaksi:

{
  text: "Rate your experience with this Chat app.",
  accessoryWidgets: [{ buttonList: { buttons: [{
    icon: { material_icon: {
      name: "thumb_up"
    }},
    color: { red: 0, blue: 255, green: 0 },
    onClick: { action: {
      function: "doUpvote"
    }}
  }, {
    icon: { material_icon: {
      name: "thumb_down"
    }},
    color: { red: 0, blue: 255, green: 0 },
    onClick: { action: {
      function: "doDownvote"
    }}
  }]}}]
}

Mengirim pesan secara pribadi

Aplikasi Chat dapat mengirim pesan secara pribadi sehingga pesan hanya dapat dilihat oleh pengguna tertentu dalam ruang. Ketika seorang Aplikasi Chat mengirimkan pesan pribadi, yaitu pesan menampilkan label yang memberi tahu pengguna bahwa pesan tersebut hanya dapat dilihat oleh mereka.

Untuk mengirim pesan secara pribadi menggunakan Chat API, tentukan atribut privateMessageViewer di isi permintaan Anda. Untuk menentukan pengguna, Anda menetapkan nilai ke resource User yang mewakili pengguna Chat. Anda juga dapat menggunakan Kolom name halaman User, seperti yang ditunjukkan dalam contoh berikut:

{
  text: "Hello private world!",
  privateMessageViewer: {
    name: "users/USER_ID"
  }
}

Untuk menggunakan contoh ini, ganti USER_ID dengan ID unik untuk pengguna tersebut, seperti 12345678987654321 atau hao@cymbalgroup.com. Untuk informasi selengkapnya tentang menentukan pengguna, lihat Mengidentifikasi dan menentukan pengguna Google Chat.

Untuk mengirim pesan secara pribadi, Anda harus menghapus hal berikut dalam permintaan:

Mengirim pesan teks atas nama pengguna

Bagian ini menjelaskan cara mengirim pesan atas nama pengguna menggunakan autentikasi pengguna. Dengan autentikasi pengguna, isi pesan hanya dapat berisi teks dan wajib menghapus fitur pesan yang hanya tersedia untuk Aplikasi chat, termasuk antarmuka kartu dan widget interaktif.

Pesan dikirim dengan autentikasi pengguna
Gambar 3. Aplikasi Chat mengirimkan pesan teks pada nama pengguna.

Untuk memanggil messages.create() menggunakan autentikasi pengguna, Anda harus menentukan kolom berikut dalam permintaan:

  • Cakupan otorisasi yang mendukung otentikasi pengguna untuk metode ini. Contoh berikut menggunakan cakupan chat.messages.create.
  • Resource Space tempat tempat Anda ingin memposting pesan. Pengguna terautentikasi haruslah anggota spasi.
  • Message resource yang akan dibuat. Untuk mendefinisikan isi pesan, Anda harus menyertakan atribut text kolom tersebut.

Secara opsional, Anda dapat menyertakan hal berikut:

Kode berikut menunjukkan contoh cara aplikasi Chat dapat mengirim pesan teks di ruang tertentu atas nama pengguna terautentikasi:

Node.js

chat/client-libraries/cloud/create-message-user-cred.js
import {createClientWithUserCredentials} from './authentication-utils.js';

const USER_AUTH_OAUTH_SCOPES = ['https://www.googleapis.com/auth/chat.messages.create'];

// This sample shows how to create message with user credential
async function main() {
  // Create a client
  const chatClient = await createClientWithUserCredentials(USER_AUTH_OAUTH_SCOPES);

  // Initialize request argument(s)
  const request = {
    // Replace SPACE_NAME here.
    parent: 'spaces/SPACE_NAME',
    message: {
      text: '👋🌎 Hello world!' +
            'Text messages can contain things like:\n\n' +
            '* Hyperlinks 🔗\n' +
            '* Emojis 😄🎉\n' +
            '* Mentions of other Chat users `@` \n\n' +
            'For details, see the ' +
            '<https://developers.google.com/workspace/chat/format-messages' +
            '|Chat API developer documentation>.'
    }
  };

  // Make the request
  const response = await chatClient.createMessage(request);

  // Handle the response
  console.log(response);
}

main().catch(console.error);

Python

chat/client-libraries/cloud/create_message_user_cred.py
from authentication_utils import create_client_with_user_credentials
from google.apps import chat_v1 as google_chat

SCOPES = ["https://www.googleapis.com/auth/chat.messages.create"]

def create_message_with_user_cred():
    # Create a client
    client = create_client_with_user_credentials(SCOPES)

    # Initialize request argument(s)
    request = google_chat.CreateMessageRequest(
        # Replace SPACE_NAME here.
        parent = "spaces/SPACE_NAME",
        message = {
            "text": '👋🌎 Hello world!' +
                    'Text messages can contain things like:\n\n' +
                    '* Hyperlinks 🔗\n' +
                    '* Emojis 😄🎉\n' +
                    '* Mentions of other Chat users `@` \n\n' +
                    'For details, see the ' +
                    '<https://developers.google.com/workspace/chat/format-messages' +
                    '|Chat API developer documentation>.'
        }
    )

    # Make the request
    response = client.create_message(request)

    # Handle the response
    print(response)

create_message_with_user_cred()

Java

chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/CreateMessageUserCred.java
import com.google.chat.v1.ChatServiceClient;
import com.google.chat.v1.CreateMessageRequest;
import com.google.chat.v1.Message;

// This sample shows how to create message with user credential.
public class CreateMessageUserCred {

  private static final String SCOPE =
    "https://www.googleapis.com/auth/chat.messages.create";

  public static void main(String[] args) throws Exception {
    try (ChatServiceClient chatServiceClient =
        AuthenticationUtils.createClientWithUserCredentials(
          ImmutableList.of(SCOPE))) {
      CreateMessageRequest.Builder request = CreateMessageRequest.newBuilder()
        // Replace SPACE_NAME here.
        .setParent("spaces/SPACE_NAME")
        .setMessage(Message.newBuilder()
          .setText( "👋🌎 Hello world!" +
                    "Text messages can contain things like:\n\n" +
                    "* Hyperlinks 🔗\n" +
                    "* Emojis 😄🎉\n" +
                    "* Mentions of other Chat users `@` \n\n" +
                    "For details, see the " +
                    "<https://developers.google.com/workspace/chat/format-messages" +
                    "|Chat API developer documentation>."));
      Message response = chatServiceClient.createMessage(request.build());

      System.out.println(JsonFormat.printer().print(response));
    }
  }
}

Apps Script

chat/advanced-service/Main.gs
/**
 * This sample shows how to create message with user credential
 * 
 * It relies on the OAuth2 scope 'https://www.googleapis.com/auth/chat.messages.create'
 * referenced in the manifest file (appsscript.json).
 */
function createMessageUserCred() {
  // Initialize request argument(s)
  // TODO(developer): Replace SPACE_NAME here.
  const parent = 'spaces/SPACE_NAME';
  const message = {
    text: '👋🌎 Hello world!' +
          'Text messages can contain things like:\n\n' +
          '* Hyperlinks 🔗\n' +
          '* Emojis 😄🎉\n' +
          '* Mentions of other Chat users `@` \n\n' +
          'For details, see the ' +
          '<https://developers.google.com/workspace/chat/format-messages' +
          '|Chat API developer documentation>.'
  };

  // Make the request
  const response = Chat.Spaces.Messages.create(message, parent);

  // Handle the response
  console.log(response);
}

Untuk menjalankan contoh ini, ganti SPACE_NAME dengan ID dari ruang name kolom tersebut. Anda bisa mendapatkan ID dengan memanggil Metode spaces.list() atau dari URL ruang.

Memulai atau membalas dalam rangkaian pesan

Untuk ruang yang menggunakan thread, Anda dapat menentukan apakah pesan baru memulai rangkaian pesan, atau membalas ke rangkaian pesan yang sudah ada.

Secara default, pesan yang Anda buat menggunakan Chat API akan memulai . Untuk membantu Anda mengidentifikasi rangkaian pesan dan membalasnya nanti, Anda dapat menentukan kunci thread dalam permintaan Anda:

  • Dalam isi permintaan Anda, tentukan thread.threadKey kolom tersebut.
  • Menentukan parameter kueri messageReplyOption untuk menentukan apa yang akan terjadi jika kunci tersebut sudah ada.

Untuk membuat pesan yang membalas rangkaian pesan yang ada:

  • Dalam isi permintaan Anda, sertakan kolom thread. Jika diatur, Anda dapat menentukan threadKey yang Anda buat. Jika tidak, Anda harus menggunakan name dari utas.
  • Tentukan parameter kueri messageReplyOption.

Kode berikut menunjukkan contoh cara aplikasi Chat dapat mengirim pesan teks yang dimulai atau membalas ke utas tertentu yang diidentifikasi oleh kunci dari ruang tertentu atas nama pengguna terautentikasi:

Node.js

chat/client-libraries/cloud/create-message-user-cred-thread-key.js
import {createClientWithUserCredentials} from './authentication-utils.js';
const {MessageReplyOption} = require('@google-apps/chat').protos.google.chat.v1.CreateMessageRequest;

const USER_AUTH_OAUTH_SCOPES = ['https://www.googleapis.com/auth/chat.messages.create'];

// This sample shows how to create message with user credential with thread key
async function main() {
  // Create a client
  const chatClient = await createClientWithUserCredentials(USER_AUTH_OAUTH_SCOPES);

  // Initialize request argument(s)
  const request = {
    // Replace SPACE_NAME here.
    parent: 'spaces/SPACE_NAME',
    // Creates the message as a reply to the thread specified by thread_key
    // If it fails, the message starts a new thread instead
    messageReplyOption: MessageReplyOption.REPLY_MESSAGE_FALLBACK_TO_NEW_THREAD,
    message: {
      text: 'Hello with user credential!',
      thread: {
        // Thread key specifies a thread and is unique to the chat app
        // that sets it
        threadKey: 'THREAD_KEY'
      }
    }
  };

  // Make the request
  const response = await chatClient.createMessage(request);

  // Handle the response
  console.log(response);
}

main().catch(console.error);

Python

chat/client-libraries/cloud/create_message_user_cred_thread_key.py
from authentication_utils import create_client_with_user_credentials
from google.apps import chat_v1 as google_chat

import google.apps.chat_v1.CreateMessageRequest.MessageReplyOption

SCOPES = ["https://www.googleapis.com/auth/chat.messages.create"]

# This sample shows how to create message with user credential with thread key
def create_message_with_user_cred_thread_key():
    # Create a client
    client = create_client_with_user_credentials(SCOPES)

    # Initialize request argument(s)
    request = google_chat.CreateMessageRequest(
        # Replace SPACE_NAME here
        parent = "spaces/SPACE_NAME",
        # Creates the message as a reply to the thread specified by thread_key.
        # If it fails, the message starts a new thread instead.
        message_reply_option = MessageReplyOption.REPLY_MESSAGE_FALLBACK_TO_NEW_THREAD,
        message = {
            "text": "Hello with user credential!",
            "thread": {
                # Thread key specifies a thread and is unique to the chat app
                # that sets it.
                "thread_key": "THREAD_KEY"
            }
        }
    )

    # Make the request
    response = client.create_message(request)

    # Handle the response
    print(response)

create_message_with_user_cred_thread_key()

Java

chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/CreateMessageUserCredThreadKey.java
import com.google.chat.v1.ChatServiceClient;
import com.google.chat.v1.CreateMessageRequest;
import com.google.chat.v1.CreateMessageRequest.MessageReplyOption;
import com.google.chat.v1.Message;
import com.google.chat.v1.Thread;

// This sample shows how to create message with a thread key with user
// credential.
public class CreateMessageUserCredThreadKey {

  private static final String SCOPE =
    "https://www.googleapis.com/auth/chat.messages.create";

  public static void main(String[] args) throws Exception {
    try (ChatServiceClient chatServiceClient =
        AuthenticationUtils.createClientWithUserCredentials(
          ImmutableList.of(SCOPE))) {
      CreateMessageRequest.Builder request = CreateMessageRequest.newBuilder()
        // Replace SPACE_NAME here.
        .setParent("spaces/SPACE_NAME")
        // Creates the message as a reply to the thread specified by thread_key.
        // If it fails, the message starts a new thread instead.
        .setMessageReplyOption(
          MessageReplyOption.REPLY_MESSAGE_FALLBACK_TO_NEW_THREAD)
        .setMessage(Message.newBuilder()
          .setText("Hello with user credentials!")
          // Thread key specifies a thread and is unique to the chat app
          // that sets it.
          .setThread(Thread.newBuilder().setThreadKey("THREAD_KEY")));
      Message response = chatServiceClient.createMessage(request.build());

      System.out.println(JsonFormat.printer().print(response));
    }
  }
}

Apps Script

chat/advanced-service/Main.gs
/**
 * This sample shows how to create message with user credential with thread key
 * 
 * It relies on the OAuth2 scope 'https://www.googleapis.com/auth/chat.messages.create'
 * referenced in the manifest file (appsscript.json).
 */
function createMessageUserCredThreadKey() {
  // Initialize request argument(s)
  // TODO(developer): Replace SPACE_NAME here.
  const parent = 'spaces/SPACE_NAME';
  // Creates the message as a reply to the thread specified by thread_key
  // If it fails, the message starts a new thread instead
  const messageReplyOption = 'REPLY_MESSAGE_FALLBACK_TO_NEW_THREAD';
  const message = {
    text: 'Hello with user credential!',
    thread: {
      // Thread key specifies a thread and is unique to the chat app
      // that sets it
      threadKey: 'THREAD_KEY'
    }
  };

  // Make the request
  const response = Chat.Spaces.Messages.create(message, parent, {
    messageReplyOption: messageReplyOption
  });

  // Handle the response
  console.log(response);
}

Untuk menjalankan contoh ini, ganti kode berikut:

  • THREAD_KEY: kunci thread yang ada dalam ruang, atau untuk membuat thread baru, nama unik untuk thread.
  • SPACE_NAME: ID dari name kolom tersebut. Anda bisa mendapatkan ID dengan memanggil Metode spaces.list() atau dari URL ruang.

Memberi nama pesan

Untuk mengambil atau menetapkan pesan dalam panggilan API mendatang, Anda dapat memberi nama pesan dengan menyetel kolom messageId dalam permintaan messages.create() Anda. Memberi nama pesan memungkinkan Anda menentukan pesan tanpa perlu menyimpan ID yang ditetapkan sistem dari nama resource pesan (diwakili dalam name ).

Misalnya, untuk mengambil pesan menggunakan metode get(), Anda menggunakan nama resource untuk menetapkan pesan yang akan diambil. Nama resource-nya adalah diformat sebagai spaces/{space}/messages/{message}, dengan {message} mewakili ID yang ditetapkan sistem atau nama kustom yang Anda tetapkan saat membuat untuk membuat pesan email baru.

Untuk memberi nama pesan, tentukan ID kustom di messageId saat Anda membuat pesan. Kolom messageId menetapkan nilai untuk clientAssignedMessageId pada kolom resource Message.

Anda hanya dapat memberi nama pesan saat membuat pesan. Anda tidak dapat memberi nama atau mengubah ID kustom untuk pesan yang ada. ID kustom harus memenuhi persyaratan berikut persyaratan:

  • Diawali dengan client-. Misalnya, client-custom-name adalah domain kustom yang valid ID, tetapi custom-name tidak.
  • Berisi maksimal 63 karakter dan hanya huruf kecil, angka, dan tanda hubung.
  • Unik dalam ruang. Aplikasi Chat tidak dapat menggunakan ID kustom yang sama untuk pesan yang berbeda.

Kode berikut menunjukkan contoh cara aplikasi Chat dapat mengirim pesan teks dengan ID ke ruang tertentu atas nama pengguna terautentikasi:

Node.js

chat/client-libraries/cloud/create-message-user-cred-message-id.js
import {createClientWithUserCredentials} from './authentication-utils.js';

const USER_AUTH_OAUTH_SCOPES = ['https://www.googleapis.com/auth/chat.messages.create'];

// This sample shows how to create message with user credential with message id
async function main() {
  // Create a client
  const chatClient = await createClientWithUserCredentials(USER_AUTH_OAUTH_SCOPES);

  // Initialize request argument(s)
  const request = {
    // Replace SPACE_NAME here.
    parent: 'spaces/SPACE_NAME',
    // Message id lets chat apps get, update or delete a message without needing
    // to store the system assigned ID in the message's resource name
    messageId: 'client-MESSAGE-ID',
    message: { text: 'Hello with user credential!' }
  };

  // Make the request
  const response = await chatClient.createMessage(request);

  // Handle the response
  console.log(response);
}

main().catch(console.error);

Python

chat/client-libraries/cloud/create_message_user_cred_message_id.py
from authentication_utils import create_client_with_user_credentials
from google.apps import chat_v1 as google_chat

SCOPES = ["https://www.googleapis.com/auth/chat.messages.create"]

# This sample shows how to create message with user credential with message id
def create_message_with_user_cred_message_id():
    # Create a client
    client = create_client_with_user_credentials(SCOPES)

    # Initialize request argument(s)
    request = google_chat.CreateMessageRequest(
        # Replace SPACE_NAME here
        parent = "spaces/SPACE_NAME",
        # Message id let chat apps get, update or delete a message without needing
        # to store the system assigned ID in the message's resource name.
        message_id = "client-MESSAGE-ID",
        message = {
            "text": "Hello with user credential!"
        }
    )

    # Make the request
    response = client.create_message(request)

    # Handle the response
    print(response)

create_message_with_user_cred_message_id()

Java

chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/CreateMessageUserCredMessageId.java
import com.google.chat.v1.ChatServiceClient;
import com.google.chat.v1.CreateMessageRequest;
import com.google.chat.v1.Message;

// This sample shows how to create message with message id specified with user
// credential.
public class CreateMessageUserCredMessageId {

  private static final String SCOPE =
    "https://www.googleapis.com/auth/chat.messages.create";

  public static void main(String[] args) throws Exception {
    try (ChatServiceClient chatServiceClient =
        AuthenticationUtils.createClientWithUserCredentials(
          ImmutableList.of(SCOPE))) {
      CreateMessageRequest.Builder request = CreateMessageRequest.newBuilder()
        // Replace SPACE_NAME here.
        .setParent("spaces/SPACE_NAME")
        .setMessage(Message.newBuilder()
          .setText("Hello with user credentials!"))
        // Message ID lets chat apps get, update or delete a message without
        // needing to store the system assigned ID in the message's resource
        // name.
        .setMessageId("client-MESSAGE-ID");
      Message response = chatServiceClient.createMessage(request.build());

      System.out.println(JsonFormat.printer().print(response));
    }
  }
}

Apps Script

chat/advanced-service/Main.gs
/**
 * This sample shows how to create message with user credential with message id
 * 
 * It relies on the OAuth2 scope 'https://www.googleapis.com/auth/chat.messages.create'
 * referenced in the manifest file (appsscript.json).
 */
function createMessageUserCredMessageId() {
  // Initialize request argument(s)
  // TODO(developer): Replace SPACE_NAME here.
  const parent = 'spaces/SPACE_NAME';
  // Message id lets chat apps get, update or delete a message without needing
  // to store the system assigned ID in the message's resource name
  const messageId = 'client-MESSAGE-ID';
  const message = { text: 'Hello with user credential!' };

  // Make the request
  const response = Chat.Spaces.Messages.create(message, parent, {
    messageId: messageId
  });

  // Handle the response
  console.log(response);
}

Untuk menjalankan contoh ini, ganti kode berikut:

  • SPACE_NAME: ID dari name kolom tersebut. Anda bisa mendapatkan ID dengan memanggil Metode spaces.list() atau dari URL ruang.
  • MESSAGE-ID: nama untuk pesan yang dimulai dengan custom-. Harus unik dari nama pesan lainnya yang dibuat oleh Aplikasi Chat di ruang yang ditentukan.

Memecahkan masalah

Saat aplikasi Google Chat atau kartu menampilkan error, Antarmuka Chat menampilkan pesan yang bertuliskan "Terjadi masalah". atau "Tidak dapat memproses permintaan Anda". Terkadang UI Chat tidak menampilkan pesan error apa pun, tetapi aplikasi Chat atau memberikan hasil yang tidak diharapkan; misalnya, pesan kartu mungkin tidak akan muncul.

Meskipun pesan error mungkin tidak ditampilkan di UI Chat, pesan error deskriptif dan data log tersedia untuk membantu Anda memperbaiki error saat logging error untuk aplikasi Chat diaktifkan. Untuk bantuan melihat, men-debug, dan memperbaiki error, melihat Memecahkan masalah dan memperbaiki error Google Chat.