Panduan ini menjelaskan cara menggunakan Google Chat API untuk membuat pesan yang berisi kartu interaktif atas nama pengguna, dan cara memperbarui kartu tersebut secara asinkron.
Membuat dan memperbarui kartu berguna jika Anda ingin melakukan hal berikut:
- Memposting kartu yang mewakili tugas atau resource eksternal atas nama pengguna.
- Memperbarui status kartu (misalnya, "Sedang Berlangsung" menjadi "Selesai") berdasarkan peristiwa eksternal, tanpa menunggu interaksi pengguna.
- Memuat ulang konten kartu pada pesan pengguna, seperti pratinjau link.
Di luar Program Pratinjau Developer, pesan yang dibuat dengan autentikasi pengguna hanya dapat berisi teks.
Prasyarat
Node.js
- Menyiapkan lingkungan Anda:
- Buat project Google Cloud.
- Konfigurasikan layar izin OAuth.
- Aktifkan dan konfigurasi Google Chat API dengan nama, ikon, dan deskripsi untuk aplikasi Chat Anda.
- Instal Library Klien Google API Node.js.
- Buat kredensial akses berdasarkan cara Anda ingin melakukan autentikasi dalam permintaan Google Chat API
request:
- Untuk melakukan autentikasi sebagai pengguna Chat,
buat kredensial ID klien OAuth dan simpan kredensial sebagai file JSON bernama
credentials.jsonke direktori lokal Anda. - Untuk melakukan autentikasi sebagai aplikasi Chat,
buat kredensial akun layanan dan simpan kredensial sebagai file JSON bernama
credentials.json.
- Untuk melakukan autentikasi sebagai pengguna Chat,
buat kredensial ID klien OAuth dan simpan kredensial sebagai file JSON bernama
- Pilih cakupan otorisasi berdasarkan apakah Anda ingin melakukan autentikasi sebagai pengguna atau aplikasi Chat.
Python
- Menyiapkan lingkungan Anda:
- Buat project Google Cloud.
- Konfigurasikan layar izin OAuth.
- Aktifkan dan konfigurasi Google Chat API dengan nama, ikon, dan deskripsi untuk aplikasi Chat Anda.
- Instal Library Klien Google APIPython .
- Buat kredensial akses berdasarkan cara Anda ingin melakukan autentikasi dalam permintaan Google Chat API
request:
- Untuk melakukan autentikasi sebagai pengguna Chat,
buat kredensial ID klien OAuth dan simpan kredensial sebagai file JSON bernama
credentials.jsonke direktori lokal Anda. - Untuk melakukan autentikasi sebagai aplikasi Chat,
buat kredensial akun layanan dan simpan kredensial sebagai file JSON bernama
credentials.json.
- Untuk melakukan autentikasi sebagai pengguna Chat,
buat kredensial ID klien OAuth dan simpan kredensial sebagai file JSON bernama
- Pilih cakupan otorisasi berdasarkan apakah Anda ingin melakukan autentikasi sebagai pengguna atau aplikasi Chat.
Java
- Menyiapkan lingkungan Anda:
- Buat project Google Cloud.
- Konfigurasikan layar izin OAuth.
- Aktifkan dan konfigurasi Google Chat API dengan nama, ikon, dan deskripsi untuk aplikasi Chat Anda.
- Instal Library Klien Google API Java .
- Buat kredensial akses berdasarkan cara Anda ingin melakukan autentikasi dalam permintaan Google Chat API
request:
- Untuk melakukan autentikasi sebagai pengguna Chat,
buat kredensial ID klien OAuth dan simpan kredensial sebagai file JSON bernama
credentials.jsonke direktori lokal Anda. - Untuk melakukan autentikasi sebagai aplikasi Chat,
buat kredensial akun layanan dan simpan kredensial sebagai file JSON bernama
credentials.json.
- Untuk melakukan autentikasi sebagai pengguna Chat,
buat kredensial ID klien OAuth dan simpan kredensial sebagai file JSON bernama
- Pilih cakupan otorisasi berdasarkan apakah Anda ingin melakukan autentikasi sebagai pengguna atau aplikasi Chat.
Apps Script
- Menyiapkan lingkungan Anda:
- Buat project Google Cloud.
- Konfigurasikan layar izin OAuth.
- Aktifkan dan konfigurasi Google Chat API dengan nama, ikon, dan deskripsi untuk aplikasi Chat Anda.
- Buat project Apps Script mandiri, dan aktifkan Layanan Chat Lanjutan.
- Dalam panduan ini, Anda harus menggunakan autentikasi pengguna atau aplikasi. Untuk melakukan autentikasi sebagai aplikasi Chat, buat kredensial akun layanan. Untuk mengetahui langkah-langkahnya, lihat Mengautentikasi dan memberi otorisasi sebagai aplikasi Google Chat.
- Pilih cakupan otorisasi berdasarkan apakah Anda ingin melakukan autentikasi sebagai pengguna atau aplikasi Chat.
Membuat kunci API untuk mengakses fitur Pratinjau Developer
Untuk memanggil metode API Pratinjau Developer, Anda harus menggunakan versi pratinjau developer non-publik dari dokumen penemuan API. Untuk mengautentikasi permintaan, Anda harus meneruskan kunci API.
Untuk membuat Kunci API, buka project Google Cloud aplikasi Anda dan lakukan hal berikut:
- Di konsol Google Cloud, buka menu > API & Layanan > Kredensial.
- Klik Buat kredensial > Kunci API.
- Kunci API baru Anda akan ditampilkan.
- Klik Salin untuk menyalin kunci API Anda agar dapat digunakan dalam kode aplikasi Anda. Kunci API juga dapat ditemukan di bagian "Kunci API" pada kredensial project Anda.
- Untuk mencegah penggunaan yang tidak sah, sebaiknya batasi tempat dan API yang dapat menggunakan kunci API dapat digunakan. Untuk mengetahui detail selengkapnya, lihat Menambahkan pembatasan API.
Membuat pesan kartu atas nama pengguna
Untuk membuat pesan dengan kartu atas nama pengguna, gunakan autentikasi pengguna.
Untuk membuat pesan, tentukan hal berikut dalam permintaan Anda:
- Cakupan otorisasi
chat.messages.createatauchat.messages. - Kolom
cardsV2dalam resourceMessage, yang berisi data kartu. cardIduntuk setiap kartu, yang diperlukan untuk pembaruan asinkron.
Contoh berikut menunjukkan cara membuat pesan dengan kartu atas nama pengguna:
Node.js
/**
* This sample shows how to create a message with a card on behalf of a user.
*/
const {google} = require('googleapis');
const {auth} = require('google-auth-library');
async function main() {
// Create a client
const authClient = await auth.getClient({
scopes: ['https://www.googleapis.com/auth/chat.messages.create']
});
google.options({auth: authClient});
// Initialize the Chat API with Developer Preview labels
const chat = await google.discoverAPI(
'https://chat.googleapis.com/$discovery/rest?version=v1&labels=DEVELOPER_PREVIEW&key=API_KEY'
);
// The space to create the message in.
const parent = 'spaces/SPACE_NAME';
// Create the request
const request = {
parent: parent,
requestBody: {
text: 'Here is a card created on my behalf:',
cardsV2: [{
cardId: 'unique-card-id',
card: {
header: {
title: 'Card Title',
subtitle: 'Card Subtitle'
},
sections: [{
widgets: [{
textParagraph: {
text: 'This card is attached to a user message.'
}
}]
}]
}
}]
}
};
// Call the API
const response = await chat.spaces.messages.create(request);
// Handle the response
console.log(response.data);
}
main().catch(console.error);
Python
"""
This sample shows how to create a message with a card on behalf of a user.
"""
from google.oauth2 import service_account
from googleapiclient.discovery import build
import google.auth
def create_message_with_card():
# Create a client
scopes = ["https://www.googleapis.com/auth/chat.messages.create"]
credentials, _ = google.auth.default(scopes=scopes)
# Build the service endpoint for Chat API with Developer Preview labels.
service = build(
'chat',
'v1',
credentials=credentials,
discoveryServiceUrl='https://chat.googleapis.com/$discovery/rest?version=v1&labels=DEVELOPER_PREVIEW&key=API_KEY'
)
# The space to create the message in.
parent = "spaces/SPACE_NAME"
# Create the request
result = service.spaces().messages().create(
parent=parent,
body={
'text': 'Here is a card created on my behalf:',
'cardsV2': [{
'cardId': 'unique-card-id',
'card': {
'header': {
'title': 'Card Title',
'subtitle': 'Card Subtitle'
},
'sections': [{
'widgets': [{
'textParagraph': {
'text': 'This card is attached to a user message.'
}
}]
}]
}
}]
}
).execute()
print(result)
if __name__ == "__main__":
create_message_with_card()
Java
/**
* This sample shows how to create a message with a card on behalf of a user.
*/
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.http.GenericUrl;
import com.google.api.client.http.HttpRequest;
import com.google.api.client.http.HttpRequestFactory;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.json.JsonHttpContent;
import com.google.api.client.json.gson.GsonFactory;
import com.google.auth.http.HttpCredentialsAdapter;
import com.google.auth.oauth2.GoogleCredentials;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
public class CreateMessageWithCard {
public static void main(String[] args) throws Exception {
HttpTransport transport = GoogleNetHttpTransport.newTrustedTransport();
GsonFactory jsonFactory = GsonFactory.getDefaultInstance();
GoogleCredentials credentials = GoogleCredentials.getApplicationDefault()
.createScoped(Arrays.asList("https://www.googleapis.com/auth/chat.messages.create"));
HttpRequestFactory requestFactory = transport.createRequestFactory(new HttpCredentialsAdapter(credentials));
String parent = "spaces/SPACE_NAME";
GenericUrl url = new GenericUrl("https://chat.googleapis.com/v1/" + parent + "/messages");
// Construct the message body
Map<String, Object> message = new HashMap<>();
message.put("text", "Here is a card created on my behalf:");
Map<String, Object> header = new HashMap<>();
header.put("title", "Card Title");
header.put("subtitle", "Card Subtitle");
Map<String, Object> textParagraph = new HashMap<>();
textParagraph.put("text", "This card is attached to a user message.");
Map<String, Object> widget = new HashMap<>();
widget.put("textParagraph", textParagraph);
Map<String, Object> section = new HashMap<>();
section.put("widgets", Collections.singletonList(widget));
Map<String, Object> card = new HashMap<>();
card.put("header", header);
card.put("sections", Collections.singletonList(section));
Map<String, Object> cardWithId = new HashMap<>();
cardWithId.put("cardId", "unique-card-id");
cardWithId.put("card", card);
message.put("cardsV2", Collections.singletonList(cardWithId));
HttpRequest request = requestFactory.buildPostRequest(url, new JsonHttpContent(jsonFactory, message));
System.out.println(request.execute().parseAsString());
}
}
Apps Script
/**
* This sample shows how to create a message with a card on behalf of a user.
*/
function createMessageWithCard() {
const parent = 'spaces/SPACE_NAME';
const url = `https://chat.googleapis.com/v1/${parent}/messages`;
const message = {
text: 'Here is a card created on my behalf:',
cardsV2: [{
cardId: 'unique-card-id',
card: {
header: {
title: 'Card Title',
subtitle: 'Card Subtitle'
},
sections: [{
widgets: [{
textParagraph: {
text: 'This card is attached to a user message.'
}
}]
}]
}
}]
};
const options = {
method: 'post',
headers: {
Authorization: 'Bearer ' + ScriptApp.getOAuthToken()
},
contentType: 'application/json',
payload: JSON.stringify(message),
muteHttpExceptions: true
};
try {
const response = UrlFetchApp.fetch(url, options);
console.log(response.getContentText());
} catch (err) {
console.log('Failed to create message: ' + err.message);
}
}
Memperbarui kartu secara asinkron
Setelah membuat pesan dengan kartu, Anda dapat memperbarui kartu secara asinkron menggunakan autentikasi aplikasi. Hal ini memungkinkan aplikasi Anda memuat ulang konten kartu tanpa memerlukan interaksi pengguna. Hanya aplikasi Chat yang menambahkan kartu ke pesan pengguna yang dapat menggantinya. Jika pengguna mengedit teks pesan, kartu milik aplikasi akan dihapus, dan aplikasi Anda tidak dapat lagi memperbaruinya.
Untuk memperbarui kartu, panggil metode replaceCards dengan hal berikut:
- Cakupan otorisasi
chat.bot. namepesan yang akan diperbarui.- Daftar
cardsV2baru. Tindakan ini akan mengganti semua kartu yang ada dalam pesan. Jika Anda memberikan daftar kosong, kartu akan dihapus.
Contoh berikut menunjukkan cara memperbarui kartu pesan:
Node.js
/**
* This sample shows how to update cards on a message.
*/
const {google} = require('googleapis');
const {auth} = require('google-auth-library');
async function main() {
// Create a client with app credentials
const authClient = await auth.getClient({
scopes: ['https://www.googleapis.com/auth/chat.bot']
});
google.options({auth: authClient});
// Initialize the Chat API with Developer Preview labels
const chat = await google.discoverAPI(
'https://chat.googleapis.com/$discovery/rest?version=v1&labels=DEVELOPER_PREVIEW&key=API_KEY'
);
// The message to update.
const messageName = 'spaces/SPACE_NAME/messages/MESSAGE_ID';
// Create the request
const request = {
name: messageName,
requestBody: {
cardsV2: [{
cardId: 'unique-card-id',
card: {
header: {
title: 'Updated Card Title',
subtitle: 'Updated Card Subtitle'
},
sections: [{
widgets: [{
textParagraph: {
text: 'The card content has been updated asynchronously.'
}
}]
}]
}
}]
}
};
// Call the API
await chat.spaces.messages.replaceCards(request);
console.log('Cards updated.');
}
main().catch(console.error);
Python
"""
This sample shows how to update cards on a message.
"""
from google.oauth2 import service_account
from googleapiclient.discovery import build
import google.auth
def replace_message_cards():
# Create a client with app credentials
scopes = ["https://www.googleapis.com/auth/chat.bot"]
credentials, _ = google.auth.default(scopes=scopes)
# Build the service endpoint for Chat API with Developer Preview labels.
service = build(
'chat',
'v1',
credentials=credentials,
discoveryServiceUrl='https://chat.googleapis.com/$discovery/rest?version=v1&labels=DEVELOPER_PREVIEW&key=API_KEY'
)
# The message to update.
message_name = "spaces/SPACE_NAME/messages/MESSAGE_ID"
# Create the request
result = service.spaces().messages().replaceCards(
name=message_name,
body={
'cardsV2': [{
'cardId': 'unique-card-id',
'card': {
'header': {
'title': 'Updated Card Title',
'subtitle': 'Updated Card Subtitle'
},
'sections': [{
'widgets': [{
'textParagraph': {
'text': 'The card content has been updated asynchronously.'
}
}]
}]
}
}]
}
).execute()
print("Cards updated.")
if __name__ == "__main__":
replace_message_cards()
Java
/**
* This sample shows how to update cards on a message.
*/
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.http.GenericUrl;
import com.google.api.client.http.HttpRequest;
import com.google.api.client.http.HttpRequestFactory;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.json.JsonHttpContent;
import com.google.api.client.json.gson.GsonFactory;
import com.google.auth.http.HttpCredentialsAdapter;
import com.google.auth.oauth2.GoogleCredentials;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
public class ReplaceMessageCards {
public static void main(String[] args) throws Exception {
HttpTransport transport = GoogleNetHttpTransport.newTrustedTransport();
GsonFactory jsonFactory = GsonFactory.getDefaultInstance();
GoogleCredentials credentials = GoogleCredentials.getApplicationDefault()
.createScoped(Arrays.asList("https://www.googleapis.com/auth/chat.bot"));
HttpRequestFactory requestFactory = transport.createRequestFactory(new HttpCredentialsAdapter(credentials));
String messageName = "spaces/SPACE_NAME/messages/MESSAGE_ID";
GenericUrl url = new GenericUrl("https://chat.googleapis.com/v1/" + messageName + ":replaceCards");
// Construct the body
Map<String, Object> header = new HashMap<>();
header.put("title", "Updated Card Title");
header.put("subtitle", "Updated Card Subtitle");
Map<String, Object> textParagraph = new HashMap<>();
textParagraph.put("text", "The card content has been updated asynchronously.");
Map<String, Object> widget = new HashMap<>();
widget.put("textParagraph", textParagraph);
Map<String, Object> section = new HashMap<>();
section.put("widgets", Collections.singletonList(widget));
Map<String, Object> card = new HashMap<>();
card.put("header", header);
card.put("sections", Collections.singletonList(section));
Map<String, Object> cardWithId = new HashMap<>();
cardWithId.put("cardId", "unique-card-id");
cardWithId.put("card", card);
Map<String, Object> body = new HashMap<>();
body.put("cardsV2", Collections.singletonList(cardWithId));
HttpRequest request = requestFactory.buildPostRequest(url, new JsonHttpContent(jsonFactory, body));
request.execute();
System.out.println("Cards updated.");
}
}
Apps Script
/**
* This sample shows how to update cards on a message.
*/
function replaceMessageCards() {
const messageName = 'spaces/SPACE_NAME/messages/MESSAGE_ID';
const url = `https://chat.googleapis.com/v1/${messageName}:replaceCards`;
const request = {
cardsV2: [{
cardId: 'unique-card-id',
card: {
header: {
title: 'Updated Card Title',
subtitle: 'Updated Card Subtitle'
},
sections: [{
widgets: [{
textParagraph: {
text: 'The card content has been updated asynchronously.'
}
}]
}]
}
}]
};
const options = {
method: 'post',
headers: {
Authorization: 'Bearer ' + ScriptApp.getOAuthToken()
},
contentType: 'application/json',
payload: JSON.stringify(request),
muteHttpExceptions: true
};
try {
const response = UrlFetchApp.fetch(url, options);
console.log('Cards updated.');
} catch (err) {
console.log('Failed to update cards: ' + err.message);
}
}
Batasan
Saat membuat pesan dengan kartu atas nama pengguna atau memperbarui kartu, aplikasi Chat harus menjadi anggota ruang. Persyaratan ini berlaku saat:
- Membuat pesan dengan kartu atas nama pengguna.
- Mengganti atau memperbarui kartu pesan.
Persyaratan ini berbeda dengan API lain yang menggunakan autentikasi pengguna, yang biasanya tidak mengharuskan aplikasi menjadi anggota ruang.
Metode
replaceCardsmendukung penggantian dan penghapusan kartu, dan Anda dapat menambahkan kartu tambahan saat menggantinya, tetapi Anda tidak dapat menambahkan kartu ke pesan yang belum memiliki kartu.Aplikasi Chat hanya dapat mengganti kartu yang dilampirkannya ke pesan, bukan kartu yang dilampirkan oleh aplikasi Chat lainnya.
Jika pengguna mengedit teks pesan, kartu milik aplikasi Chat akan dihapus, dan Anda tidak dapat lagi memperbaruinya.