Hướng dẫn này giải thích cách sử dụng Google Chat API để tạo tin nhắn có chứa thẻ tương tác thay mặt cho người dùng và cách cập nhật các thẻ đó một cách không đồng bộ.
Bạn nên tạo và cập nhật thẻ khi muốn làm những việc sau:
- Đăng thẻ đại diện cho một việc cần làm hoặc tài nguyên bên ngoài thay cho người dùng.
- Cập nhật trạng thái của thẻ (ví dụ: "Đang tiến hành" thành "Đã hoàn tất") dựa trên các sự kiện bên ngoài mà không cần chờ người dùng tương tác.
- Làm mới nội dung của thẻ trong tin nhắn của người dùng, chẳng hạn như bản xem trước đường liên kết.
Ngoài Chương trình dùng trước cho nhà phát triển, các thông báo được tạo bằng xác thực người dùng chỉ có thể chứa văn bản.
Điều kiện tiên quyết
Node.js
- Tài khoản Google Workspace Business hoặc Enterprise có quyền truy cập vào Google Chat.
- Thiết lập môi trường:
- Tạo một dự án trên Google Cloud.
- Định cấu hình màn hình xin phép bằng OAuth.
- Bật và định cấu hình Google Chat API bằng tên, biểu tượng và nội dung mô tả cho ứng dụng nhắn tin của bạn.
- Cài đặt Thư viện ứng dụng Google API Node.js.
- Tạo thông tin đăng nhập để truy cập dựa trên cách bạn muốn xác thực trong yêu cầu Google Chat API:
- Để xác thực với tư cách là người dùng Chat, hãy tạo thông tin xác thực mã ứng dụng khách OAuth và lưu thông tin xác thực dưới dạng tệp JSON có tên
credentials.jsonvào thư mục cục bộ của bạn. - Để xác thực dưới dạng ứng dụng nhắn tin, hãy tạo thông tin đăng nhập tài khoản dịch vụ và lưu thông tin đăng nhập dưới dạng tệp JSON có tên là
credentials.json.
- Để xác thực với tư cách là người dùng Chat, hãy tạo thông tin xác thực mã ứng dụng khách OAuth và lưu thông tin xác thực dưới dạng tệp JSON có tên
- Chọn phạm vi uỷ quyền dựa trên việc bạn muốn xác thực với tư cách là người dùng hay ứng dụng nhắn tin.
Python
- Tài khoản Google Workspace Business hoặc Enterprise có quyền truy cập vào Google Chat.
- Thiết lập môi trường:
- Tạo một dự án trên Google Cloud.
- Định cấu hình màn hình xin phép bằng OAuth.
- Bật và định cấu hình Google Chat API bằng tên, biểu tượng và nội dung mô tả cho ứng dụng nhắn tin của bạn.
- Cài đặt Thư viện ứng dụng Google API Python.
- Tạo thông tin đăng nhập để truy cập dựa trên cách bạn muốn xác thực trong yêu cầu Google Chat API:
- Để xác thực với tư cách là người dùng Chat, hãy tạo thông tin xác thực mã ứng dụng khách OAuth và lưu thông tin xác thực dưới dạng tệp JSON có tên
credentials.jsonvào thư mục cục bộ của bạn. - Để xác thực dưới dạng ứng dụng nhắn tin, hãy tạo thông tin đăng nhập tài khoản dịch vụ và lưu thông tin đăng nhập dưới dạng tệp JSON có tên là
credentials.json.
- Để xác thực với tư cách là người dùng Chat, hãy tạo thông tin xác thực mã ứng dụng khách OAuth và lưu thông tin xác thực dưới dạng tệp JSON có tên
- Chọn phạm vi uỷ quyền dựa trên việc bạn muốn xác thực với tư cách là người dùng hay ứng dụng nhắn tin.
Java
- Tài khoản Google Workspace Business hoặc Enterprise có quyền truy cập vào Google Chat.
- Thiết lập môi trường:
- Tạo một dự án trên Google Cloud.
- Định cấu hình màn hình xin phép bằng OAuth.
- Bật và định cấu hình Google Chat API bằng tên, biểu tượng và nội dung mô tả cho ứng dụng nhắn tin của bạn.
- Cài đặt Thư viện ứng dụng Java Google API.
- Tạo thông tin đăng nhập để truy cập dựa trên cách bạn muốn xác thực trong yêu cầu Google Chat API:
- Để xác thực với tư cách là người dùng Chat, hãy tạo thông tin xác thực mã ứng dụng khách OAuth và lưu thông tin xác thực dưới dạng tệp JSON có tên
credentials.jsonvào thư mục cục bộ của bạn. - Để xác thực dưới dạng ứng dụng nhắn tin, hãy tạo thông tin đăng nhập tài khoản dịch vụ và lưu thông tin đăng nhập dưới dạng tệp JSON có tên là
credentials.json.
- Để xác thực với tư cách là người dùng Chat, hãy tạo thông tin xác thực mã ứng dụng khách OAuth và lưu thông tin xác thực dưới dạng tệp JSON có tên
- Chọn phạm vi uỷ quyền dựa trên việc bạn muốn xác thực với tư cách là người dùng hay ứng dụng nhắn tin.
Apps Script
- Tài khoản Google Workspace Business hoặc Enterprise có quyền truy cập vào Google Chat.
- Thiết lập môi trường:
- Tạo một dự án trên Google Cloud.
- Định cấu hình màn hình xin phép bằng OAuth.
- Bật và định cấu hình Google Chat API bằng tên, biểu tượng và nội dung mô tả cho ứng dụng nhắn tin của bạn.
- Tạo một dự án Apps Script độc lập và bật Dịch vụ Chat nâng cao.
- Trong hướng dẫn này, bạn phải sử dụng quy trình xác thực người dùng hoặc ứng dụng. Để xác thực dưới dạng ứng dụng nhắn tin, hãy tạo thông tin đăng nhập tài khoản dịch vụ. Để biết các bước, hãy xem phần Xác thực và uỷ quyền dưới dạng ứng dụng nhắn tin Google Chat.
- Chọn phạm vi uỷ quyền dựa trên việc bạn muốn xác thực với tư cách là người dùng hay ứng dụng nhắn tin.
Tạo khoá API để truy cập vào các tính năng của Bản dùng trước cho nhà phát triển
Để gọi một phương thức API trong Bản dùng trước cho nhà phát triển, bạn phải sử dụng một phiên bản không công khai của tài liệu khám phá API trong Bản dùng trước cho nhà phát triển. Để xác thực yêu cầu, bạn phải truyền một khoá API.
Để tạo khoá API, hãy mở dự án trên đám mây của ứng dụng rồi làm như sau:
- Trong bảng điều khiển Google Cloud, hãy chuyển đến phần Trình đơn > API và Dịch vụ > Thông tin xác thực.
- Nhấp vào Tạo thông tin xác thực > Khoá API.
- Khoá API mới sẽ xuất hiện.
- Nhấp vào biểu tượng Sao chép để sao chép khoá API nhằm sử dụng trong mã của ứng dụng. Bạn cũng có thể tìm thấy khoá API trong phần "Khoá API" của thông tin xác thực dự án.
- Để ngăn chặn việc sử dụng trái phép, bạn nên hạn chế nơi và API mà khoá API có thể được dùng. Để biết thêm thông tin chi tiết, hãy xem phần Thêm các quy tắc hạn chế đối với API.
Tạo thông báo dạng thẻ thay cho người dùng
Để tạo một thông báo có thẻ thay cho người dùng, hãy sử dụng xác thực người dùng.
Để tạo thông báo, hãy chỉ định những thông tin sau trong yêu cầu của bạn:
- Phạm vi uỷ quyền
chat.messages.createhoặcchat.messages. - Trường
cardsV2trong tài nguyênMessage, chứa dữ liệu thẻ. cardIdcho mỗi thẻ, bắt buộc phải có để cập nhật không đồng bộ.
Ví dụ sau đây cho thấy cách tạo một thông báo có thẻ thay cho người dùng:
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);
}
}
Cập nhật thẻ không đồng bộ
Sau khi tạo một thông báo có thẻ, bạn có thể cập nhật thẻ một cách không đồng bộ bằng cách sử dụng xác thực ứng dụng. Điều này cho phép ứng dụng của bạn làm mới nội dung thẻ mà không cần lượt tương tác của người dùng. Chỉ ứng dụng nhắn tin đã thêm thẻ vào tin nhắn của người dùng mới có thể thay thế thẻ đó. Nếu người dùng chỉnh sửa nội dung tin nhắn, thì các thẻ thuộc sở hữu của ứng dụng sẽ bị xoá và ứng dụng của bạn sẽ không thể cập nhật các thẻ đó nữa.
Để cập nhật thẻ, hãy gọi phương thức replaceCards bằng nội dung sau:
- Phạm vi uỷ quyền
chat.bot. namecủa thông báo cần cập nhật.- Danh sách
cardsV2mới. Thao tác này sẽ thay thế tất cả thẻ hiện có trong thông báo. Nếu bạn cung cấp một danh sách trống, các thẻ sẽ bị xoá.
Ví dụ sau đây cho thấy cách cập nhật thẻ của một thông báo:
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);
}
}
Các điểm hạn chế
Khi tạo tin nhắn có thẻ thay cho người dùng hoặc cập nhật thẻ, ứng dụng nhắn tin phải là thành viên của không gian. Yêu cầu này áp dụng khi:
- Tạo thông báo bằng thẻ thay cho người dùng.
- Thay thế hoặc cập nhật thẻ của một thông báo.
Yêu cầu này khác với các API khác sử dụng tính năng xác thực người dùng, thường không yêu cầu ứng dụng phải là thành viên của không gian.
Phương thức
replaceCardshỗ trợ thay thế và xoá thẻ, đồng thời bạn có thể thêm thẻ khác trong khi thay thế thẻ, nhưng bạn không thể thêm thẻ vào một thông báo chưa có thẻ.Ứng dụng nhắn tin chỉ có thể thay thế những thẻ mà ứng dụng này đã đính kèm vào một tin nhắn, chứ không thể thay thế những thẻ mà các ứng dụng nhắn tin khác đã đính kèm.
Nếu người dùng chỉnh sửa nội dung tin nhắn, thì các thẻ thuộc ứng dụng Chat sẽ bị xoá và bạn không thể cập nhật các thẻ đó nữa.