本指南說明如何使用 Google Chat API,代表使用者建立含有互動式資訊卡的訊息,以及如何以非同步方式更新這些資訊卡。
在下列情況下,建立及更新資訊卡會很有幫助:
- 代表使用者張貼資訊卡,呈現工作或外部資源。
- 根據外部事件更新資訊卡狀態 (例如從「進行中」變更為「已完成」),不必等待使用者互動。
- 重新整理使用者訊息中的資訊卡內容,例如連結預覽。
必要條件
Node.js
- Business 或 Enterprise Google Workspace 帳戶,且可存取 Google Chat。
- 設定環境:
- 建立 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
- Business 或 Enterprise Google Workspace 帳戶,且可存取 Google Chat。
- 設定環境:
- 建立 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
- Business 或 Enterprise Google Workspace 帳戶,且可存取 Google Chat。
- 設定環境:
- 建立 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
- Business 或 Enterprise Google Workspace 帳戶,且可存取 Google Chat。
- 設定環境:
- 建立 Google Cloud 專案。
- 設定 OAuth 同意畫面。
- 啟用及設定 Google Chat API,為 Chat 擴充應用程式指定名稱、圖示和說明。
- 建立獨立 Apps Script 專案,並啟用進階 Chat 服務。
- 在本指南中,您必須使用使用者或應用程式驗證。如要以 Chat 擴充應用程式的身分進行驗證,請建立服務帳戶憑證。如需相關步驟,請參閱「以 Google Chat 應用程式的身分驗證及授權」。
- 根據您要以使用者或 Chat 擴充應用程式的身分進行驗證, 選擇授權範圍。
代表使用者建立資訊卡訊息
如要代表使用者建立含有資訊卡的訊息,請使用使用者驗證。
如要建立訊息,請在要求中指定下列項目:
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
const chat = google.chat({version: 'v1'});
// 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.
service = build('chat', 'v1', credentials=credentials)
# 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
const chat = google.chat({version: 'v1'});
// 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.
service = build('chat', 'v1', credentials=credentials)
# 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 擴充應用程式擁有的資訊卡就會移除,您也無法再更新。