이 가이드에서는 Google Chat API를 사용하여 사용자를 대신하여 대화형 카드를 포함하는 메시지를 만드는 방법과 이러한 카드를 비동기식으로 업데이트하는 방법을 설명합니다.
카드를 만들고 업데이트하는 것은 다음과 같은 경우에 유용합니다.
- 사용자를 대신하여 작업 또는 외부 리소스를 나타내는 카드를 게시합니다.
- 사용자 상호작용을 기다리지 않고 외부 이벤트를 기반으로 카드 상태를 업데이트합니다 (예: '진행 중'에서 '완료됨'으로).
- 링크 미리보기와 같은 사용자 메시지의 카드 콘텐츠를 새로고침합니다.
개발자 미리보기 프로그램 외부에서 사용자 인증으로 만든 메시지에는 텍스트만 포함될 수 있습니다.
기본 요건
Node.js
- Google Chat에 액세스할 수 있는 Business 또는 Enterprise Google Workspace 계정
- 환경을 설정합니다.
- Google Cloud 프로젝트를 만듭니다.
- OAuth 동의 화면 구성
- Chat 앱의 이름, 아이콘, 설명으로 Google Chat API를 사용 설정하고 구성합니다.
- 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 동의 화면 구성
- Chat 앱의 이름, 아이콘, 설명으로 Google Chat API를 사용 설정하고 구성합니다.
- Python Google API 클라이언트 라이브러리를 설치합니다.
- Google Chat API 요청에서 인증하려는 방식에 따라 액세스 사용자 인증 정보를 만듭니다.
- Chat 사용자로 인증하려면 OAuth 클라이언트 ID 사용자 인증 정보를 만들고 사용자 인증 정보를
credentials.json라는 JSON 파일로 로컬 디렉터리에 저장합니다. - Chat 앱으로 인증하려면 서비스 계정 사용자 인증 정보를 만들고 사용자 인증 정보를
credentials.json라는 JSON 파일로 저장합니다.
- Chat 사용자로 인증하려면 OAuth 클라이언트 ID 사용자 인증 정보를 만들고 사용자 인증 정보를
- 사용자로 인증할지 아니면 Chat 앱으로 인증할지에 따라 승인 범위 선택
자바
- Google Chat에 액세스할 수 있는 Business 또는 Enterprise Google Workspace 계정
- 환경을 설정합니다.
- Google Cloud 프로젝트를 만듭니다.
- OAuth 동의 화면 구성
- Chat 앱의 이름, 아이콘, 설명으로 Google Chat API를 사용 설정하고 구성합니다.
- 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 동의 화면 구성
- Chat 앱의 이름, 아이콘, 설명으로 Google Chat API를 사용 설정하고 구성합니다.
- 독립형 Apps Script 프로젝트를 만들고 고급 Chat 서비스를 사용 설정합니다.
- 이 가이드에서는 사용자 또는 앱 인증을 사용해야 합니다. Chat 앱으로 인증하려면 서비스 계정 사용자 인증 정보를 만드세요. 단계는 Google Chat 앱으로 인증 및 승인하기를 참고하세요.
- 사용자로 인증할지 아니면 Chat 앱으로 인증할지에 따라 승인 범위 선택
개발자 프리뷰 기능에 액세스할 API 키 만들기
개발자 프리뷰 API 메서드를 호출하려면 공개되지 않은 개발자 프리뷰 버전의 API 검색 문서를 사용해야 합니다. 요청을 인증하려면 API 키를 전달해야 합니다.
API 키를 만들려면 앱의 Google Cloud 프로젝트를 열고 다음 단계를 따르세요.
- Google Cloud 콘솔에서 메뉴 > API 및 서비스 > 사용자 인증 정보로 이동합니다.
- 사용자 인증 정보 만들기 > 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()
자바
/**
* 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()
자바
/**
* 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 앱 소유 카드가 삭제되며 더 이상 업데이트할 수 없습니다.