คู่มือนี้อธิบายวิธีใช้ Google Chat API เพื่อสร้างข้อความที่มี การ์ดแบบอินเทอร์แอกทีฟใน นามของผู้ใช้ และวิธีอัปเดตการ์ดเหล่านั้นแบบไม่พร้อมกัน
การสร้างและอัปเดตการ์ดมีประโยชน์ในกรณีต่อไปนี้
- โพสต์การ์ดที่แสดงถึงงานหรือแหล่งข้อมูลภายนอกในนามของผู้ใช้
- อัปเดตสถานะของการ์ด (เช่น จาก "อยู่ระหว่างดำเนินการ" เป็น "เสร็จสมบูรณ์") ตามเหตุการณ์ภายนอก โดยไม่ต้องรอให้ผู้ใช้โต้ตอบ
- รีเฟรชเนื้อหาของการ์ดในข้อความของผู้ใช้ เช่น การแสดงตัวอย่างลิงก์
นอกโปรแกรมเวอร์ชันทดลองสำหรับนักพัฒนาแอป ข้อความที่สร้างขึ้น ด้วยการตรวจสอบสิทธิ์ผู้ใช้จะมีได้ เฉพาะข้อความเท่านั้น
ข้อกำหนดเบื้องต้น
Node.js
- บัญชี Google Workspace เวอร์ชัน Business หรือ Enterprise ที่มีสิทธิ์เข้าถึง Google Chat
- ตั้งค่าสภาพแวดล้อมดังนี้
- สร้างโปรเจ็กต์ Google Cloud
- กำหนดค่าหน้าจอขอความยินยอม OAuth
- เปิดใช้และกำหนดค่า Google Chat API ด้วยชื่อ ไอคอน และคำอธิบายสำหรับแอป Chat
- ติดตั้งไลบรารีของไคลเอ็นต์ Google API สำหรับ Node.js.
- สร้างข้อมูลเข้าสู่ระบบเพื่อเข้าถึงโดยอิงตามวิธีที่คุณต้องการตรวจสอบสิทธิ์ในคำขอ Google Chat API
ดังนี้:
- หากต้องการตรวจสอบสิทธิ์ในฐานะผู้ใช้ Chat
ให้สร้างข้อมูลเข้าสู่ระบบรหัสไคลเอ็นต์ OAuthและบันทึกข้อมูลเข้าสู่ระบบเป็นไฟล์ JSON ชื่อ
credentials.jsonในไดเรกทอรีภายในเครื่อง - หากต้องการตรวจสอบสิทธิ์ในฐานะแอป Chat,
สร้างข้อมูลเข้าสู่ระบบของบัญชีบริการ และบันทึกข้อมูลเข้าสู่ระบบเป็นไฟล์ JSON ชื่อ
credentials.json
- หากต้องการตรวจสอบสิทธิ์ในฐานะผู้ใช้ Chat
ให้สร้างข้อมูลเข้าสู่ระบบรหัสไคลเอ็นต์ OAuthและบันทึกข้อมูลเข้าสู่ระบบเป็นไฟล์ JSON ชื่อ
- เลือกขอบเขตการให้สิทธิ์โดยพิจารณาว่าคุณต้องการตรวจสอบสิทธิ์ในฐานะผู้ใช้หรือ แอป Chat
Python
- บัญชี Google Workspace เวอร์ชัน Business หรือ Enterprise ที่มีสิทธิ์เข้าถึง Google Chat
- ตั้งค่าสภาพแวดล้อมดังนี้
- สร้างโปรเจ็กต์ Google Cloud
- กำหนดค่าหน้าจอขอความยินยอม OAuth
- เปิดใช้และกำหนดค่า Google Chat API ด้วยชื่อ ไอคอน และคำอธิบายสำหรับแอป Chat
- ติดตั้งไลบรารีของไคลเอ็นต์ Google API สำหรับ Python.
- สร้างข้อมูลเข้าสู่ระบบเพื่อเข้าถึงโดยอิงตามวิธีที่คุณต้องการตรวจสอบสิทธิ์ในคำขอ Google Chat API
ดังนี้:
- หากต้องการตรวจสอบสิทธิ์ในฐานะผู้ใช้ Chat
ให้สร้างข้อมูลเข้าสู่ระบบรหัสไคลเอ็นต์ OAuthและบันทึกข้อมูลเข้าสู่ระบบเป็นไฟล์ JSON ชื่อ
credentials.jsonในไดเรกทอรีภายในเครื่อง - หากต้องการตรวจสอบสิทธิ์ในฐานะแอป Chat,
สร้างข้อมูลเข้าสู่ระบบของบัญชีบริการ และบันทึกข้อมูลเข้าสู่ระบบเป็นไฟล์ JSON ชื่อ
credentials.json
- หากต้องการตรวจสอบสิทธิ์ในฐานะผู้ใช้ Chat
ให้สร้างข้อมูลเข้าสู่ระบบรหัสไคลเอ็นต์ OAuthและบันทึกข้อมูลเข้าสู่ระบบเป็นไฟล์ JSON ชื่อ
- เลือกขอบเขตการให้สิทธิ์โดยพิจารณาว่าคุณต้องการตรวจสอบสิทธิ์ในฐานะผู้ใช้หรือ แอป Chat
Java
- บัญชี Google Workspace เวอร์ชัน Business หรือ Enterprise ที่มีสิทธิ์เข้าถึง Google Chat
- ตั้งค่าสภาพแวดล้อมดังนี้
- สร้างโปรเจ็กต์ Google Cloud
- กำหนดค่าหน้าจอขอความยินยอม OAuth
- เปิดใช้และกำหนดค่า Google Chat API ด้วยชื่อ ไอคอน และคำอธิบายสำหรับแอป Chat
- ติดตั้งไลบรารีของไคลเอ็นต์ Google API สำหรับ Java.
- สร้างข้อมูลเข้าสู่ระบบเพื่อเข้าถึงโดยอิงตามวิธีที่คุณต้องการตรวจสอบสิทธิ์ในคำขอ Google Chat API
ดังนี้:
- หากต้องการตรวจสอบสิทธิ์ในฐานะผู้ใช้ Chat
ให้สร้างข้อมูลเข้าสู่ระบบรหัสไคลเอ็นต์ OAuthและบันทึกข้อมูลเข้าสู่ระบบเป็นไฟล์ JSON ชื่อ
credentials.jsonในไดเรกทอรีภายในเครื่อง - หากต้องการตรวจสอบสิทธิ์ในฐานะแอป Chat,
สร้างข้อมูลเข้าสู่ระบบของบัญชีบริการ และบันทึกข้อมูลเข้าสู่ระบบเป็นไฟล์ JSON ชื่อ
credentials.json
- หากต้องการตรวจสอบสิทธิ์ในฐานะผู้ใช้ Chat
ให้สร้างข้อมูลเข้าสู่ระบบรหัสไคลเอ็นต์ OAuthและบันทึกข้อมูลเข้าสู่ระบบเป็นไฟล์ JSON ชื่อ
- เลือกขอบเขตการให้สิทธิ์โดยพิจารณาว่าคุณต้องการตรวจสอบสิทธิ์ในฐานะผู้ใช้หรือ แอป Chat
Apps Script
- บัญชี Google Workspace เวอร์ชัน Business หรือ Enterprise ที่มีสิทธิ์เข้าถึง Google Chat
- ตั้งค่าสภาพแวดล้อมดังนี้
- สร้างโปรเจ็กต์ Google Cloud
- กำหนดค่าหน้าจอขอความยินยอม OAuth
- เปิดใช้และกำหนดค่า Google Chat API ด้วยชื่อ ไอคอน และคำอธิบายสำหรับแอป Chat
- สร้างโปรเจ็กต์ Apps Script แบบสแตนด์อโลน, แล้วเปิดใช้บริการ Chat ขั้นสูง
- ในคู่มือนี้ คุณต้องใช้การตรวจสอบสิทธิ์ผู้ใช้ หรือแอป หากต้องการตรวจสอบสิทธิ์ในฐานะแอป Chat ให้สร้าง ข้อมูลเข้าสู่ระบบของบัญชีบริการ ดูขั้นตอนได้ที่หัวข้อ ตรวจสอบสิทธิ์และให้สิทธิ์ในฐานะ แอป Google Chat
- เลือกขอบเขตการให้สิทธิ์โดยพิจารณาว่าคุณต้องการตรวจสอบสิทธิ์ในฐานะผู้ใช้หรือ แอป Chat
สร้างคีย์ API เพื่อเข้าถึงฟีเจอร์เวอร์ชันตัวอย่างสำหรับนักพัฒนาซอฟต์แวร์
หากต้องการเรียกใช้เมธอด API ของเวอร์ชันตัวอย่างสำหรับนักพัฒนาซอฟต์แวร์ คุณต้องใช้เอกสารการค้นพบ API เวอร์ชันตัวอย่างสำหรับนักพัฒนาซอฟต์แวร์ที่ไม่ใช่เวอร์ชันสาธารณะ และต้องส่งคีย์ API เพื่อตรวจสอบสิทธิ์คำขอ
หากต้องการสร้างคีย์ API ให้เปิดโปรเจ็กต์ที่อยู่ในระบบคลาวด์ Google ของแอป แล้วทำดังนี้
- ในคอนโซล Google Cloud ให้ไปที่เมนู > API และบริการ > ข้อมูลเข้าสู่ระบบ
- คลิกสร้างข้อมูลเข้าสู่ระบบ > คีย์ API
- คีย์ API ใหม่จะแสดงขึ้น
- คลิกคัดลอก เพื่อคัดลอกคีย์ API ไปใช้ในโค้ดของแอป นอกจากนี้ คุณยังดูคีย์ API ได้ในส่วน "คีย์ API" ของ ข้อมูลเข้าสู่ระบบของโปรเจ็กต์
- เราขอแนะนำให้จำกัดตำแหน่งและ API ที่สามารถใช้คีย์ API เพื่อป้องกันการใช้งานที่ไม่ได้รับอนุญาต ดูรายละเอียดเพิ่มเติมได้ที่ หัวข้อเพิ่มข้อจำกัด API.
สร้างข้อความการ์ดในนามของผู้ใช้
หากต้องการสร้างข้อความที่มีการ์ดในนามของผู้ใช้ ให้ใช้ การตรวจสอบสิทธิ์ผู้ใช้
หากต้องการสร้างข้อความ ให้ระบุข้อมูลต่อไปนี้ในคำขอ
- ขอบเขตการให้สิทธิ์
chat.messages.createหรือchat.messages - ฟิลด์
cardsV2ในทรัพยากรMessageซึ่งมีข้อมูลการ์ด 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 จะนำการ์ดที่เป็นของแอปออก และคุณจะอัปเดตการ์ดเหล่านั้นไม่ได้อีกต่อไป