本指南說明如何使用 Google Chat API 代表使用者建立含有互動式資訊卡的訊息,以及如何非同步更新這些資訊卡。
建立及更新資訊卡有助於:
- 代表使用者發布代表工作或外部資源的資訊卡。
- 根據外部事件更新資訊卡狀態 (例如從「處理中」改為「已完成」),不必等待使用者互動。
- 重新整理使用者訊息中的資訊卡內容,例如連結預覽。
在開發人員搶先體驗計畫以外,透過使用者驗證建立的訊息只能包含文字。
必要條件
Node.js
- 具有 Google Chat 存取權的 Business 或 Enterprise 版 Google Workspace 帳戶。
- 設定環境:
- 建立 Google Cloud 專案。
- 設定 OAuth 同意畫面。
- 啟用及設定 Google Chat API,並為 Chat 應用程式命名、設定圖示和說明。
- 安裝 Node.js Google API 用戶端程式庫。
- 根據您要在 Google Chat API 要求中驗證身分的方式,建立存取憑證:
- 如要以 Chat 使用者身分進行驗證,請建立 OAuth 用戶端 ID 憑證,並將憑證儲存至本機目錄中名為
credentials.json的 JSON 檔案。 - 如要以 Chat 應用程式身分進行驗證,請建立服務帳戶憑證,並將憑證儲存為名為
credentials.json的 JSON 檔案。
- 如要以 Chat 使用者身分進行驗證,請建立 OAuth 用戶端 ID 憑證,並將憑證儲存至本機目錄中名為
- 根據您要以使用者或 Chat 應用程式的身分驗證,選擇授權範圍。
Python
- 具有 Google Chat 存取權的 Business 或 Enterprise 版 Google Workspace 帳戶。
- 設定環境:
- 建立 Google Cloud 專案。
- 設定 OAuth 同意畫面。
- 啟用及設定 Google Chat API,並為 Chat 應用程式命名、設定圖示和說明。
- 安裝 Python Google API 用戶端程式庫。
- 根據您要在 Google Chat API 要求中驗證身分的方式,建立存取憑證:
- 如要以 Chat 使用者身分進行驗證,請建立 OAuth 用戶端 ID 憑證,並將憑證儲存至本機目錄中名為
credentials.json的 JSON 檔案。 - 如要以 Chat 應用程式身分進行驗證,請建立服務帳戶憑證,並將憑證儲存為名為
credentials.json的 JSON 檔案。
- 如要以 Chat 使用者身分進行驗證,請建立 OAuth 用戶端 ID 憑證,並將憑證儲存至本機目錄中名為
- 根據您要以使用者或 Chat 應用程式的身分驗證,選擇授權範圍。
Java
- 具有 Google Chat 存取權的 Business 或 Enterprise 版 Google Workspace 帳戶。
- 設定環境:
- 建立 Google Cloud 專案。
- 設定 OAuth 同意畫面。
- 啟用及設定 Google Chat API,並為 Chat 應用程式命名、設定圖示和說明。
- 安裝 Java Google API 用戶端程式庫。
- 根據您要在 Google Chat API 要求中驗證身分的方式,建立存取憑證:
- 如要以 Chat 使用者身分進行驗證,請建立 OAuth 用戶端 ID 憑證,並將憑證儲存至本機目錄中名為
credentials.json的 JSON 檔案。 - 如要以 Chat 應用程式身分進行驗證,請建立服務帳戶憑證,並將憑證儲存為名為
credentials.json的 JSON 檔案。
- 如要以 Chat 使用者身分進行驗證,請建立 OAuth 用戶端 ID 憑證,並將憑證儲存至本機目錄中名為
- 根據您要以使用者或 Chat 應用程式的身分驗證,選擇授權範圍。
Apps Script
- 具有 Google Chat 存取權的 Business 或 Enterprise 版 Google Workspace 帳戶。
- 設定環境:
- 建立 Google Cloud 專案。
- 設定 OAuth 同意畫面。
- 啟用及設定 Google Chat API,並為 Chat 應用程式命名、設定圖示和說明。
- 建立獨立的 Apps Script 專案,並開啟進階 Chat 服務。
- 在本指南中,您必須使用使用者或應用程式驗證。如要以 Chat 應用程式的身分進行驗證,請建立服務帳戶憑證。如需相關步驟,請參閱「以 Google Chat 擴充應用程式的身分驗證及授權」。
- 根據您要以使用者或 Chat 應用程式的身分驗證,選擇授權範圍。
建立 API 金鑰,存取開發人員預先發布版功能
如要呼叫開發人員搶先體驗版 API 方法,您必須使用非公開的開發人員搶先體驗版 API 探索文件。如要驗證要求,您必須傳遞 API 金鑰。
如要建立 API 金鑰,請開啟應用程式的 Google Cloud 專案,然後執行下列操作:
- 在 Google Cloud 控制台中,依序前往「Menu」(選單) >「APIs & Services」(API 和服務) >「Credentials」(憑證)。
- 依序按一下「建立憑證」>「API 金鑰」。
- 系統會顯示新的 API 金鑰。
- 按一下「複製」圖示 ,即可複製 API 金鑰,在應用程式的程式碼中使用。您也可以在專案憑證的「API 金鑰」部分找到 API 金鑰。
- 為避免有人未經授權使用,建議您限制這組 API 金鑰的適用位置與 API。詳情請參閱「新增 API 限制」一文。
代表使用者建立卡片訊息
如要代表使用者建立含有資訊卡的訊息,請使用使用者驗證。
如要建立訊息,請在要求中指定下列項目:
chat.messages.create或chat.messages授權範圍。Message資源中的cardsV2欄位,內含卡片資料。- 每張卡的
cardId,這是非同步更新的必要條件。
以下範例說明如何代表使用者建立含有資訊卡的訊息:
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);
}
}
非同步更新資訊卡
使用資訊卡建立訊息後,您可以透過應用程式驗證非同步更新資訊卡。這樣一來,應用程式就能自動重新整理資訊卡內容,不必等待使用者操作。只有將資訊卡新增至使用者訊息的 Chat 應用程式可以取代該資訊卡。如果使用者編輯訊息文字,系統會移除應用程式擁有的資訊卡,您的應用程式也無法再更新這些資訊卡。
如要更新卡片,請使用下列項目呼叫 replaceCards 方法:
chat.bot授權範圍。- 要更新的訊息
name。 - 新的
cardsV2清單。這會取代訊息中的所有現有資訊卡。 如果提供空白清單,系統會移除卡片。
以下範例說明如何更新訊息的資訊卡:
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);
}
}
限制
代表使用者建立或更新含有資訊卡的訊息時,Chat 應用程式必須是聊天室成員。這項規定適用於下列情況:
這項規定與其他使用使用者驗證的 API 不同,後者通常不要求應用程式成為聊天室成員。
replaceCards方法支援更換及移除卡片,您可以在更換卡片時新增其他卡片,但無法在沒有卡片的訊息中新增卡片。Chat 應用程式只能取代自己附加到訊息的資訊卡,無法取代其他 Chat 應用程式附加的資訊卡。
如果使用者編輯訊息文字,系統會移除 Chat 應用程式擁有的資訊卡,您也無法再更新這些資訊卡。