사용자로부터 메시지를 받은 후 답장을 보낼 수 있습니다. 대화를 계속하세요. 최대 30일 후 사용자에게 메시지를 보낼 수 있습니다. 사용자의 마지막 메시지입니다.
에이전트는 메시지를 주고받음으로써 사용자와 커뮤니케이션합니다. 보내기 메시지를 사용자에게 보내면 에이전트가 Business Messages에 메시지 요청을 보냅니다.
메시지를 보내려면 Business Messages API에 HTTP POST 요청을 보냅니다. 여기에는
- 고유한 메시지 ID
- 대화 ID
- 메일 내용
Business Messages API는 사용자에게 메시지를 보내면
200 OK
메시지에서 필수 값이 누락된 경우 API는
400
오류를 반환합니다. 메시지가 잘못된 사용자 인증 정보를 사용하는 경우 API는 다음을 반환합니다.
401
오류가 발생합니다.
비즈니스 커뮤니케이션 개발자 콘솔 로그 사용 페이지 메일 전송 문제를 디버그할 수 있습니다.
대체 전략
사용자의 기기가 전송하려는 메시지를 지원하지 않는 경우(예:
사용자가 추천 답장을 지원하지 않는 경우 API가 400 (FAILED
PRECONDITION)
오류를 반환합니다. 하지만
보내는 각 메일에 fallback
텍스트를 지정합니다. fallback
를 지정하는 경우
사용자의 기기에 연결되지 않은 경우에도 API는 200 OK
응답을 반환합니다.
해당 메시지 유형을 지원해야 합니다.
사용자가 기기에서 지원하지 않지만 다음을 포함하고 있다는 메시지를 받는 경우
fallback
텍스트가 있으면 기기에 fallback
텍스트가 대신 표시됩니다. 이
사전 대응적인 방식으로 대화를 이어갈 수 있습니다.
대화 흐름을 중단하거나 400
(FAILED PRECONDITION)
오류를 처리하는 데 시간을 더 할애하여 대체 메시지를 식별합니다.
특정 메시지의 fallback
텍스트는 메시지의 기능을 미러링해야 합니다.
예를 들면 다음과 같습니다.
- 추천 답장 또는 작업이 있는 메일의 경우 메시지 내용을
fallback
텍스트를 포함하고 사용자가 사용할 수 있는 옵션에 대한 안내를 포함합니다. 대화를 계속하세요. - 리치 카드나 캐러셀의 경우
fallback
텍스트와 이미지 또는 웹사이트 링크를 포함할 수 있습니다.
fallback
텍스트에 줄바꿈을 삽입하려면 \n
또는 \r\n
을 사용합니다.
대체 텍스트 테스트
에이전트를 실행하기 전에 대체 텍스트가 어떻게 표시되는지 테스트할 수 있습니다.
URL 매개변수 forceFallback
를
true
입니다. 대체 텍스트를 강제로 적용하면 대화에서 기본 텍스트를 무시합니다.
메시지 콘텐츠 (다음 예에서 텍스트 및 Open URL 추천)
대신 대체 텍스트를 표시합니다.
cURL
# Copyright 2021 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # https://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # This code sends a text message to the user with a fallback text. # Read more: https://developers.google.com/business-communications/business-messages/guides/how-to/message/send?hl=en#fallback_strategy # Replace the __CONVERSATION_ID__ with a conversation id that you can send messages to # Make sure a service account key file exists at ./service_account_key.json curl -X POST \ "https://businessmessages.googleapis.com/v1/conversations/__CONVERSATION_ID__/messages?forceFallback=true" \ -H "Content-Type: application/json" \ -H "User-Agent: curl/business-messages" \ -H "$(oauth2l header --json ./service_account_key.json businessmessages)" \ -d "{ 'messageId': '$(uuidgen)', 'text': 'Hello world!', 'fallback': 'Hello, world!\n\nSay \"Hello\" at https://www.growingtreebank.com', 'suggestions': [ { 'action': { 'text': 'Hello', 'postbackData': 'hello-formal', 'openUrlAction': { 'url': 'https://www.growingtreebank.com', } }, }, ], 'representative': { 'avatarImage': 'https://developers.google.com/identity/images/g-logo.png', 'displayName': 'Chatbot', 'representativeType': 'BOT' } }"
Node.js
/** * This code sends a text message to the user with a fallback text. * Read more: https://developers.google.com/business-communications/business-messages/guides/how-to/message/send?hl=en#fallback_strategy * * This code is based on the https://github.com/google-business-communications/nodejs-businessmessages Node.js * Business Messages client library. */ /** * Edit the values below: */ const PATH_TO_SERVICE_ACCOUNT_KEY = './service_account_key.json'; const CONVERSATION_ID = 'EDIT_HERE'; const businessmessages = require('businessmessages'); const uuidv4 = require('uuid').v4; const {google} = require('googleapis'); // Initialize the Business Messages API const bmApi = new businessmessages.businessmessages_v1.Businessmessages({}); // Set the scope that we need for the Business Messages API const scopes = [ 'https://www.googleapis.com/auth/businessmessages', ]; // Set the private key to the service account file const privatekey = require(PATH_TO_SERVICE_ACCOUNT_KEY); /** * Posts a message to the Business Messages API defaulting to the fallback text. * * @param {string} conversationId The unique id for this user and agent. * @param {string} message The message text to send the user. * @param {string} representativeType A value of BOT or HUMAN. */ async function sendMessage(conversationId, message, representativeType) { const authClient = await initCredentials(); // Create the payload for sending a message const apiParams = { auth: authClient, parent: 'conversations/' + conversationId, forceFallback: true, // Force usage of the fallback text resource: { messageId: uuidv4(), representative: { representativeType: representativeType, }, text: message, fallback: 'This is the fallback text' }, }; // Call the message create function using the // Business Messages client library bmApi.conversations.messages.create(apiParams, {auth: authClient}, (err, response) => { console.log(err); console.log(response); }); } /** * Initializes the Google credentials for calling the * Business Messages API. */ async function initCredentials() { // configure a JWT auth client const authClient = new google.auth.JWT( privatekey.client_email, null, privatekey.private_key, scopes, ); return new Promise(function(resolve, reject) { // authenticate request authClient.authorize(function(err, tokens) { if (err) { reject(false); } else { resolve(authClient); } }); }); } sendMessage(CONVERSATION_ID, 'BOT');
자바
import com.google.api.client.googleapis.services.AbstractGoogleClientRequest; import com.google.api.client.http.HttpBackOffUnsuccessfulResponseHandler; import com.google.api.client.http.HttpRequest; import com.google.api.client.googleapis.auth.oauth2.GoogleCredential; import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport; import com.google.api.client.http.HttpTransport; import com.google.api.client.json.jackson2.JacksonFactory; import com.google.api.client.util.ExponentialBackOff; import com.google.api.services.businessmessages.v1.Businessmessages; import com.google.api.services.businessmessages.v1.model.*; import java.io.FileInputStream; import java.util.Arrays; import java.util.UUID; class TestFallbackTestSnippet { /** * Initializes credentials used by the Business Messages API. */ private static Businessmessages.Builder getBusinessMessagesBuilder() { Businessmessages.Builder builder = null; try { GoogleCredential credential = GoogleCredential .fromStream(new FileInputStream("PATH_TO_SERVICE_ACCOUNT_KEY")); credential = credential.createScoped(Arrays.asList( "https://www.googleapis.com/auth/businessmessages")); credential.refreshToken(); HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport(); JacksonFactory jsonFactory = JacksonFactory.getDefaultInstance(); // Create instance of the Business Messages API builder = new Businessmessages .Builder(httpTransport, jsonFactory, null) .setApplicationName("Sample Application"); // Set the API credentials and endpoint builder.setHttpRequestInitializer(credential); } catch (Exception e) { e.printStackTrace(); } return builder; } public static void main(String args[]) { try { String conversationId = "CONVERSATION_ID"; // Create client library reference Businessmessages.Builder builder = getBusinessMessagesBuilder(); // Create a basic text message with fallback text BusinessMessagesMessage message = new BusinessMessagesMessage() .setMessageId(UUID.randomUUID().toString()) .setFallback("This is the fallback text") .setText("MESSAGE_TEXT") .setRepresentative(new BusinessMessagesRepresentative() .setRepresentativeType("TYPE")); // Create message request Businessmessages.Conversations.Messages.Create messageRequest = builder.build().conversations().messages() .create("conversations/" + conversationId, message); // Force usage of the fallback text messageRequest.setForceFallback(true); // Setup retries with exponential backoff HttpRequest httpRequest = ((AbstractGoogleClientRequest) messageRequest).buildHttpRequest(); httpRequest.setUnsuccessfulResponseHandler(new HttpBackOffUnsuccessfulResponseHandler( new ExponentialBackOff())); // Execute request httpRequest.execute(); } catch (Exception e) { e.printStackTrace(); } } }
Python
"""This code sends a text message to the user with a fallback text. Read more: https://developers.google.com/business-communications/business-messages/guides/how-to/message/send?hl=en#fallback_strategy This code is based on the https://github.com/google-business-communications/python-businessmessages Python Business Messages client library. """ import uuid from businessmessages import businessmessages_v1_client as bm_client from businessmessages.businessmessages_v1_messages import BusinessmessagesConversationsMessagesCreateRequest from businessmessages.businessmessages_v1_messages import BusinessMessagesMessage from businessmessages.businessmessages_v1_messages import BusinessMessagesRepresentative from oauth2client.service_account import ServiceAccountCredentials # Edit the values below: path_to_service_account_key = './service_account_key.json' conversation_id = 'EDIT_HERE' credentials = ServiceAccountCredentials.from_json_keyfile_name( path_to_service_account_key, scopes=['https://www.googleapis.com/auth/businessmessages']) client = bm_client.BusinessmessagesV1(credentials=credentials) representative_type_as_string = 'BOT' if representative_type_as_string == 'BOT': representative_type = BusinessMessagesRepresentative.RepresentativeTypeValueValuesEnum.BOT else: representative_type = BusinessMessagesRepresentative.RepresentativeTypeValueValuesEnum.HUMAN # Create message with fallback text message = BusinessMessagesMessage( messageId=str(uuid.uuid4().int), fallback='This is the fallback text', representative=BusinessMessagesRepresentative( representativeType=representative_type ), text='This is a sample text') # Create the message request, force usage of the fallback text create_request = BusinessmessagesConversationsMessagesCreateRequest( businessMessagesMessage=message, forceFallback=True, parent='conversations/' + conversation_id) # Send the message bm_client.BusinessmessagesV1.ConversationsMessagesService( client=client).Create(request=create_request)
자세한 내용은 Message
을 참고하세요.
하원의원
에이전트가 메시지를 보낼 때 대리인을 지정합니다(사람 또는
자동화를 통해 메시지를 구성했습니다. Business Messages는 HUMAN
및
BOT
담당자.
어떤 종류의 자동화든 메시지를 작성할 때 BOT
담당자를 지정합니다.
자동화가 사용자에게 현재 위치를 알려주는 자동 응답인지 여부
동적인 액세스 권한이 있는 복잡한 자연어 이해 에이전트인
사용자 세부정보 또는 그 사이에 있는 모든 정보를 포함할 수 있습니다. 담당자가 BOT
명인 메시지가 표시됨
깃발을 보고
사용자의 클라우드
서비스에 대한 예상되는 상호작용 유형에 대한
참여할 수 있게 됩니다.
실제 상담사가 메시지를 작성하는 경우에만 HUMAN
담당자를 지정합니다.
HUMAN
담당자로부터 메시지를 보내기 전에 먼저
REPRESENTATIVE_JOINED
event를
사용자는 더 자유 형식이나 복잡한 메시지를 보낼 수 있다는 것을 알고 있습니다.
HUMAN
담당자의 마지막 메시지, REPRESENTATIVE_LEFT
일정 전송
사용자의 기대치를
설정할 수 있습니다
예를 들어 사용자가 에이전트와 대화를 시작하고 상담사
2분 이내에 실제 상담사가 응대해야 한다는 자동 메시지 전송
BOT
담당자가 메시지를 보내 드립니다.
실제 상담사가 참여하면 REPRESENTATIVE_JOINED
이벤트를 전송합니다. 님이 보낸 모든 메일
실제 상담사는 HUMAN
담당자가 보낸 것으로 라벨이 지정되어야 합니다. 이
실제 상담사가 대화를 종료하고 REPRESENTATIVE_LEFT
이벤트를 전송합니다. 전체
이후에 받는 메시지는 BOT
담당자가 따로 발송해야 합니다.
상담사가 대화에 참여합니다.
봇에서 라이브로 핸드오프를 참조하세요.
상담사
BOT
및 HUMAN
간 전환을 위한 샘플 대화 및 코드
있습니다.
담당자가 BOT
인지 HUMAN
인지에 상관없이 대표를 지정할 수 있습니다.
표시 이름 및 아바타입니다. 표시 이름과 아바타가 모두 사용자에게 표시됩니다.
아바타 이미지는 1024x1024픽셀, 최대 50KB여야 하며 명시되어야 합니다.
URL로 사용합니다. 아바타 이미지를 제공하지 않으면 에이전트의
로고는 담당자의 아바타로 사용됩니다.
텍스트
가장 간단한 메시지는 텍스트로 구성되어 있습니다. 문자 메시지는 시각, 복잡한 상호작용, 있습니다.
예
다음 코드는 간단한 문자 메시지를 보냅니다. 자세한 내용은
conversations.messages.create
cURL
# Copyright 2021 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # https://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # This code sends a text message to the user. # Read more: https://developers.google.com/business-communications/business-messages/guides/how-to/message/send?hl=en#text # Replace the __CONVERSATION_ID__ with a conversation id that you can send messages to # Make sure a service account key file exists at ./service_account_key.json curl -X POST "https://businessmessages.googleapis.com/v1/conversations/__CONVERSATION_ID__/messages" \ -H "Content-Type: application/json" \ -H "User-Agent: curl/business-messages" \ -H "$(oauth2l header --json ./service_account_key.json businessmessages)" \ -d "{ 'messageId': '$(uuidgen)', 'text': 'Hello world!', 'representative': { 'avatarImage': 'https://developers.google.com/identity/images/g-logo.png', 'displayName': 'Chatbot', 'representativeType': 'BOT' } }"
Node.js
/** * This code sends a text message to the user. * Read more: https://developers.google.com/business-communications/business-messages/guides/how-to/message/send?hl=en#text * * This code is based on the https://github.com/google-business-communications/nodejs-businessmessages Node.js * Business Messages client library. */ /** * Edit the values below: */ const PATH_TO_SERVICE_ACCOUNT_KEY = './service_account_key.json'; const CONVERSATION_ID = 'EDIT_HERE'; const businessmessages = require('businessmessages'); const uuidv4 = require('uuid').v4; const {google} = require('googleapis'); // Initialize the Business Messages API const bmApi = new businessmessages.businessmessages_v1.Businessmessages({}); // Set the scope that we need for the Business Messages API const scopes = [ 'https://www.googleapis.com/auth/businessmessages', ]; // Set the private key to the service account file const privatekey = require(PATH_TO_SERVICE_ACCOUNT_KEY); /** * Posts a text message to the Business Messages API. * * @param {string} conversationId The unique id for this user and agent. * @param {string} message The message text to send the user. * @param {string} representativeType A value of BOT or HUMAN. */ async function sendMessage(conversationId, message, representativeType) { const authClient = await initCredentials(); // Create the payload for sending a message const apiParams = { auth: authClient, parent: 'conversations/' + conversationId, resource: { messageId: uuidv4(), representative: { representativeType: representativeType, }, text: message, }, }; // Call the message create function using the // Business Messages client library bmApi.conversations.messages.create(apiParams, {auth: authClient}, (err, response) => { console.log(err); console.log(response); }); } /** * Initializes the Google credentials for calling the * Business Messages API. */ async function initCredentials() { // configure a JWT auth client const authClient = new google.auth.JWT( privatekey.client_email, null, privatekey.private_key, scopes, ); return new Promise(function(resolve, reject) { // authenticate request authClient.authorize(function(err, tokens) { if (err) { reject(false); } else { resolve(authClient); } }); }); } sendMessage(CONVERSATION_ID, 'This is a test message', 'BOT');
자바
import com.google.api.client.googleapis.services.AbstractGoogleClientRequest; import com.google.api.client.http.HttpBackOffUnsuccessfulResponseHandler; import com.google.api.client.http.HttpRequest; import com.google.api.client.googleapis.auth.oauth2.GoogleCredential; import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport; import com.google.api.client.http.HttpTransport; import com.google.api.client.json.jackson2.JacksonFactory; import com.google.api.client.util.ExponentialBackOff; import com.google.api.services.businessmessages.v1.Businessmessages; import com.google.api.services.businessmessages.v1.model.*; import java.io.FileInputStream; import java.util.Arrays; import java.util.UUID; class SendTextMessageSnippet { /** * Initializes credentials used by the Business Messages API. */ private static Businessmessages.Builder getBusinessMessagesBuilder() { Businessmessages.Builder builder = null; try { GoogleCredential credential = GoogleCredential .fromStream(new FileInputStream("PATH_TO_SERVICE_ACCOUNT_KEY")); credential = credential.createScoped(Arrays.asList( "https://www.googleapis.com/auth/businessmessages")); credential.refreshToken(); HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport(); JacksonFactory jsonFactory = JacksonFactory.getDefaultInstance(); // Create instance of the Business Messages API builder = new Businessmessages .Builder(httpTransport, jsonFactory, null) .setApplicationName("Sample Application"); // Set the API credentials and endpoint builder.setHttpRequestInitializer(credential); } catch (Exception e) { e.printStackTrace(); } return builder; } public static void main(String args[]) { try { String conversationId = "CONVERSATION_ID"; // Create client library reference Businessmessages.Builder builder = getBusinessMessagesBuilder(); // Create a basic text message BusinessMessagesMessage message = new BusinessMessagesMessage() .setMessageId(UUID.randomUUID().toString()) .setText("MESSAGE_TEXT") .setRepresentative(new BusinessMessagesRepresentative() .setRepresentativeType("TYPE")); // Create message request Businessmessages.Conversations.Messages.Create messageRequest = builder.build().conversations().messages() .create("conversations/" + conversationId, message); // Setup retries with exponential backoff HttpRequest httpRequest = ((AbstractGoogleClientRequest) messageRequest).buildHttpRequest(); httpRequest.setUnsuccessfulResponseHandler(new HttpBackOffUnsuccessfulResponseHandler( new ExponentialBackOff())); // Execute request httpRequest.execute(); } catch (Exception e) { e.printStackTrace(); } } }
Python
"""This code sends a text message to the user. Read more: https://developers.google.com/business-communications/business-messages/guides/how-to/message/send?hl=en#text This code is based on the https://github.com/google-business-communications/python-businessmessages Python Business Messages client library. """ import uuid from businessmessages import businessmessages_v1_client as bm_client from businessmessages.businessmessages_v1_messages import BusinessmessagesConversationsMessagesCreateRequest from businessmessages.businessmessages_v1_messages import BusinessMessagesMessage from businessmessages.businessmessages_v1_messages import BusinessMessagesRepresentative from oauth2client.service_account import ServiceAccountCredentials # Edit the values below: path_to_service_account_key = './service_account_key.json' conversation_id = 'EDIT_HERE' credentials = ServiceAccountCredentials.from_json_keyfile_name( path_to_service_account_key, scopes=['https://www.googleapis.com/auth/businessmessages']) client = bm_client.BusinessmessagesV1(credentials=credentials) representative_type_as_string = 'BOT' if representative_type_as_string == 'BOT': representative_type = BusinessMessagesRepresentative.RepresentativeTypeValueValuesEnum.BOT else: representative_type = BusinessMessagesRepresentative.RepresentativeTypeValueValuesEnum.HUMAN # Create a text message message = BusinessMessagesMessage( messageId=str(uuid.uuid4().int), representative=BusinessMessagesRepresentative( representativeType=representative_type ), text='This is a sample text') # Create the message request create_request = BusinessmessagesConversationsMessagesCreateRequest( businessMessagesMessage=message, parent='conversations/' + conversation_id) # Send the message bm_client.BusinessmessagesV1.ConversationsMessagesService( client=client).Create(request=create_request)
서식 있는 텍스트
containsRichText
이(가) true
(으)로 설정된 문자 메시지에는 다음이 포함될 수 있습니다.
기본적인 마크다운 형식을 지원합니다. 하이퍼링크를 포함하거나 텍스트를 굵게 표시하거나
기울임꼴 표에는 몇 가지 유효한 예가 나와 있습니다.
형식 지정 | 문자 | 일반 텍스트 | 렌더링된 텍스트 |
---|---|---|---|
굵게 | ** |
**Some text** |
일부 텍스트 |
기울임꼴 | * |
*Some text* |
일부 텍스트 |
하이퍼링크 | []() |
[Click here](https://www.example.com) |
여기를 클릭하세요 |
줄바꿈 | \n
|
Line one\nLine two
|
첫 번째 줄 2행 |
형식은 몇 가지 추가 규칙을 따라야 합니다.
- 모든 링크는
https://
또는http://
(으)로 시작해야 합니다. - 다른 형식의 서식이 중첩될 수 있지만 중첩되지는 않을 수 있습니다.
\n
의 줄바꿈은 메일의 모든 곳에서 허용되지만 메시지의 끝이 표시되지 않습니다.- 예약 문자 (
*
,\
,[
또는]
)를 일반적으로 표시하려면 다음 안내를 따르세요. 백슬래시 문자 (\
)를 접두사로 붙여야 합니다.
형식이 잘못된 메일은 다음에 대한 오류 메시지와 함께 전송되지 않습니다. 잘못된 마크다운입니다. 표에는 다음을 기준으로 유효한 예와 잘못된 예가 표시됩니다. 다음 규칙을 따릅니다.
일반 텍스트 | 유효성 | 렌더링된 텍스트 |
---|---|---|
[Click here](www.example.com) |
잘못된 상태입니다. 링크가 http:// 또는 https:// (으)로 시작하지 않습니다. |
렌더링되지 않습니다. |
[**Click here**](https://www.example.com) |
올바른 쿼리입니다. 중첩이 허용됩니다. | 여기를 클릭 |
**This is [not** valid](https://www.example.com) |
잘못된 상태입니다. 중복된 형식은 허용되지 않습니다. | 렌더링되지 않습니다. |
** Some bold text ** |
잘못된 상태입니다. ** 내부에는 후행 공백이 허용되지 않습니다. |
렌더링되지 않습니다. |
Citation below\* |
올바른 쿼리입니다. * 문자는 이스케이프 처리됩니다. |
아래 인용* |
예
다음 코드는 서식 있는 텍스트 메시지를 보냅니다. 자세한 내용은
conversations.messages.create
cURL
# Copyright 2021 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # https://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # This code sends a rich text to the user with a fallback text. # Read more: https://developers.google.com/business-communications/business-messages/guides/how-to/message/send?hl=en#rich_text # Replace the __CONVERSATION_ID__ with a conversation id that you can send messages to # Make sure a service account key file exists at ./service_account_key.json curl -X POST "https://businessmessages.googleapis.com/v1/conversations/__CONVERSATION_ID__/messages" \ -H "Content-Type: application/json" \ -H "User-Agent: curl/business-messages" \ -H "$(oauth2l header --json ./service_account_key.json businessmessages)" \ -d "{ 'messageId': '$(uuidgen)', 'fallback': 'Hello, check out this link https://www.google.com.', 'text': 'Hello, here is some **bold text**, *italicized text*, and a [link](https://www.google.com).', 'containsRichText': 'true', 'representative': { 'avatarImage': 'https://developers.google.com/identity/images/g-logo.png', 'displayName': 'Chatbot', 'representativeType': 'BOT' } }"
Node.js
/** * This code sends a rich text to the user with a fallback text. * Read more: https://developers.google.com/business-communications/business-messages/guides/how-to/message/send?hl=en#rich_text * * This code is based on the https://github.com/google-business-communications/nodejs-businessmessages Node.js * Business Messages client library. */ /** * Edit the values below: */ const PATH_TO_SERVICE_ACCOUNT_KEY = './service_account_key.json'; const CONVERSATION_ID = 'EDIT_HERE'; const businessmessages = require('businessmessages'); const uuidv4 = require('uuid').v4; const {google} = require('googleapis'); // Initialize the Business Messages API const bmApi = new businessmessages.businessmessages_v1.Businessmessages({}); // Set the scope that we need for the Business Messages API const scopes = [ 'https://www.googleapis.com/auth/businessmessages', ]; // Set the private key to the service account file const privatekey = require(PATH_TO_SERVICE_ACCOUNT_KEY); /** * Posts a rich text message using markdown to the Business Messages API. * * @param {string} conversationId The unique id for this user and agent. * @param {string} representativeType A value of BOT or HUMAN. */ async function sendMessage(conversationId, message, representativeType) { const authClient = await initCredentials(); // Create the payload for sending a rich text message const apiParams = { auth: authClient, parent: 'conversations/' + conversationId, resource: { messageId: uuidv4(), representative: { representativeType: representativeType, }, containsRichText: true, // Force this message to be processed as rich text text: 'Hello, here is some **bold text**, *italicized text*, and a [link](https://www.google.com).', fallback: 'Hello, check out this link https://www.google.com.' }, }; // Call the message create function using the // Business Messages client library bmApi.conversations.messages.create(apiParams, {auth: authClient}, (err, response) => { console.log(err); console.log(response); }); } /** * Initializes the Google credentials for calling the * Business Messages API. */ async function initCredentials() { // configure a JWT auth client const authClient = new google.auth.JWT( privatekey.client_email, null, privatekey.private_key, scopes, ); return new Promise(function(resolve, reject) { // authenticate request authClient.authorize(function(err, tokens) { if (err) { reject(false); } else { resolve(authClient); } }); }); } sendMessage(CONVERSATION_ID, 'BOT');
자바
import com.google.api.client.googleapis.services.AbstractGoogleClientRequest; import com.google.api.client.http.HttpBackOffUnsuccessfulResponseHandler; import com.google.api.client.http.HttpRequest; import com.google.api.client.googleapis.auth.oauth2.GoogleCredential; import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport; import com.google.api.client.http.HttpTransport; import com.google.api.client.json.jackson2.JacksonFactory; import com.google.api.client.util.ExponentialBackOff; import com.google.api.services.businessmessages.v1.Businessmessages; import com.google.api.services.businessmessages.v1.model.*; import java.io.FileInputStream; import java.util.Arrays; import java.util.UUID; class SendRichTextMessageSnippet { /** * Initializes credentials used by the Business Messages API. */ private static Businessmessages.Builder getBusinessMessagesBuilder() { Businessmessages.Builder builder = null; try { GoogleCredential credential = GoogleCredential .fromStream(new FileInputStream("PATH_TO_SERVICE_ACCOUNT_KEY")); credential = credential.createScoped(Arrays.asList( "https://www.googleapis.com/auth/businessmessages")); credential.refreshToken(); HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport(); JacksonFactory jsonFactory = JacksonFactory.getDefaultInstance(); // Create instance of the Business Messages API builder = new Businessmessages .Builder(httpTransport, jsonFactory, null) .setApplicationName("Sample Application"); // Set the API credentials and endpoint builder.setHttpRequestInitializer(credential); } catch (Exception e) { e.printStackTrace(); } return builder; } public static void main(String args[]) { try { String conversationId = "CONVERSATION_ID"; // Create client library reference Businessmessages.Builder builder = getBusinessMessagesBuilder(); // Create a rich text message BusinessMessagesMessage message = new BusinessMessagesMessage() .setMessageId(UUID.randomUUID().toString()) .setContainsRichText(true) // Force this message to be processed as rich text .setText("Hello, here is some **bold text**, *italicized text*, and a [link](https://www.google.com).") .setFallback("Hello, check out this link https://www.google.com.") .setRepresentative(new BusinessMessagesRepresentative() .setRepresentativeType("TYPE")); // Create message request Businessmessages.Conversations.Messages.Create messageRequest = builder.build().conversations().messages() .create("conversations/" + conversationId, message); // Setup retries with exponential backoff HttpRequest httpRequest = ((AbstractGoogleClientRequest) messageRequest).buildHttpRequest(); httpRequest.setUnsuccessfulResponseHandler(new HttpBackOffUnsuccessfulResponseHandler( new ExponentialBackOff())); // Execute request httpRequest.execute(); } catch (Exception e) { e.printStackTrace(); } } }
Python
"""This code sends a rich text to the user with a fallback text. Read more: https://developers.google.com/business-communications/business-messages/guides/how-to/message/send?hl=en#rich_text This code is based on the https://github.com/google-business-communications/python-businessmessages Python Business Messages client library. """ import uuid from businessmessages import businessmessages_v1_client as bm_client from businessmessages.businessmessages_v1_messages import BusinessmessagesConversationsMessagesCreateRequest from businessmessages.businessmessages_v1_messages import BusinessMessagesMessage from businessmessages.businessmessages_v1_messages import BusinessMessagesRepresentative from oauth2client.service_account import ServiceAccountCredentials # Edit the values below: path_to_service_account_key = './service_account_key.json' conversation_id = 'EDIT_HERE' credentials = ServiceAccountCredentials.from_json_keyfile_name( path_to_service_account_key, scopes=['https://www.googleapis.com/auth/businessmessages']) client = bm_client.BusinessmessagesV1(credentials=credentials) representative_type_as_string = 'BOT' if representative_type_as_string == 'BOT': representative_type = BusinessMessagesRepresentative.RepresentativeTypeValueValuesEnum.BOT else: representative_type = BusinessMessagesRepresentative.RepresentativeTypeValueValuesEnum.HUMAN # Create a rich text message with fallback text message = BusinessMessagesMessage( messageId=str(uuid.uuid4().int), fallback='Hello, check out this link https://www.google.com.', containsRichText=True, # Force this message to be processed as rich text representative=BusinessMessagesRepresentative( representativeType=representative_type ), text='Hello, here is some **bold text**, *italicized text*, and a [link](https://www.google.com).') # Create the message request create_request = BusinessmessagesConversationsMessagesCreateRequest( businessMessagesMessage=message, parent='conversations/' + conversation_id) # Send the message bm_client.BusinessmessagesV1.ConversationsMessagesService( client=client).Create(request=create_request)
이미지
메시지로 사용자에게 이미지를 보냅니다.
이미지 및 이미지 썸네일의 URL과 함께 이미지 메시지를 보낼 수 있습니다.
예
다음 코드는 이미지를 전송합니다. 서식 지정 및
자세한 내용은
conversations.messages.create
드림
및
Image
cURL
# Copyright 2021 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # https://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # This code sends an image to the user with a fallback text. # Read more: https://developers.google.com/business-communications/business-messages/guides/how-to/message/send?hl=en#images # Replace the __CONVERSATION_ID__ with a conversation id that you can send messages to # Make sure a service account key file exists at ./service_account_key.json curl -X POST "https://businessmessages.googleapis.com/v1/conversations/__CONVERSATION_ID__/messages" \ -H "Content-Type: application/json" \ -H "User-Agent: curl/business-messages" \ -H "$(oauth2l header --json ./service_account_key.json businessmessages)" \ -d "{ 'messageId': '$(uuidgen)', 'representative': { 'avatarImage': 'https://developers.google.com/identity/images/g-logo.png', 'displayName': 'Chatbot', 'representativeType': 'BOT' }, 'fallback': 'Hello, world!\nAn image has been sent with Business Messages.', 'image': { 'contentInfo':{ 'altText': 'Image alternative text', 'fileUrl': 'https://storage.googleapis.com/kitchen-sink-sample-images/cute-dog.jpg', 'forceRefresh': 'false' } }, }"
Node.js
/** * This code sends an image to the user with a fallback text. * Read more: https://developers.google.com/business-communications/business-messages/guides/how-to/message/send?hl=en#images * * This code is based on the https://github.com/google-business-communications/nodejs-businessmessages Node.js * Business Messages client library. */ /** * Edit the values below: */ const PATH_TO_SERVICE_ACCOUNT_KEY = './service_account_key.json'; const CONVERSATION_ID = 'EDIT_HERE'; const businessmessages = require('businessmessages'); const uuidv4 = require('uuid').v4; const {google} = require('googleapis'); // Initialize the Business Messages API const bmApi = new businessmessages.businessmessages_v1.Businessmessages({}); // Set the scope that we need for the Business Messages API const scopes = [ 'https://www.googleapis.com/auth/businessmessages', ]; // Set the private key to the service account file const privatekey = require(PATH_TO_SERVICE_ACCOUNT_KEY); /** * Posts an image message to the Business Messages API. * * @param {string} conversationId The unique id for this user and agent. * @param {string} representativeType A value of BOT or HUMAN. */ async function sendMessage(conversationId, representativeType) { const authClient = await initCredentials(); if (authClient) { // Create the payload for sending an image message const apiParams = { auth: authClient, parent: 'conversations/' + conversationId, resource: { messageId: uuidv4(), representative: { representativeType: representativeType, }, fallback: 'Hello, world!\n An image has been sent with Business Messages.', image: { contentInfo: { altText: 'Some alternative text', fileUrl: 'https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png', forceRefresh: true, }, }, }, }; // Call the message create function using the // Business Messages client library bmApi.conversations.messages.create(apiParams, {auth: authClient}, (err, response) => { console.log(err); console.log(response); }); } else { console.log('Authentication failure.'); } } /** * Initializes the Google credentials for calling the * Business Messages API. */ async function initCredentials() { // configure a JWT auth client const authClient = new google.auth.JWT( privatekey.client_email, null, privatekey.private_key, scopes, ); return new Promise(function(resolve, reject) { // authenticate request authClient.authorize(function(err, tokens) { if (err) { reject(false); } else { resolve(authClient); } }); }); } sendMessage(CONVERSATION_ID, 'BOT');
자바
import com.google.api.client.googleapis.services.AbstractGoogleClientRequest; import com.google.api.client.http.HttpBackOffUnsuccessfulResponseHandler; import com.google.api.client.http.HttpRequest; import com.google.api.client.googleapis.auth.oauth2.GoogleCredential; import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport; import com.google.api.client.http.HttpTransport; import com.google.api.client.json.jackson2.JacksonFactory; import com.google.api.client.util.ExponentialBackOff; import com.google.api.services.businessmessages.v1.Businessmessages; import com.google.api.services.businessmessages.v1.model.*; import com.google.communications.businessmessages.v1.MediaHeight; import java.io.FileInputStream; import java.util.Arrays; import java.util.UUID; class SendImageMessageSnippet { /** * Initializes credentials used by the Business Messages API. */ private static Businessmessages.Builder getBusinessMessagesBuilder() { Businessmessages.Builder builder = null; try { GoogleCredential credential = GoogleCredential .fromStream(new FileInputStream("PATH_TO_SERVICE_ACCOUNT_KEY")); credential = credential.createScoped(Arrays.asList( "https://www.googleapis.com/auth/businessmessages")); credential.refreshToken(); HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport(); JacksonFactory jsonFactory = JacksonFactory.getDefaultInstance(); // Create instance of the Business Messages API builder = new Businessmessages .Builder(httpTransport, jsonFactory, null) .setApplicationName("Sample Application"); // Set the API credentials and endpoint builder.setHttpRequestInitializer(credential); } catch (Exception e) { e.printStackTrace(); } return builder; } public static void main(String args[]) { try { String conversationId = "CONVERSATION_ID"; // Create client library reference Businessmessages.Builder builder = getBusinessMessagesBuilder(); // Create an Image BusinessMessagesMessage message = new BusinessMessagesMessage() .setMessageId(UUID.randomUUID().toString()) .setRepresentative(representative) .setImage(new BusinessMessagesImage() .setContentInfo( new BusinessMessagesContentInfo() .setFileUrl("FILE_URL") .setAltText("ALT_TEXT") .setForceRefresh("FORCE_REFRESH") )); // Create message request Businessmessages.Conversations.Messages.Create messageRequest = builder.build().conversations().messages() .create("conversations/" + conversationId, message); // Setup retries with exponential backoff HttpRequest httpRequest = ((AbstractGoogleClientRequest) messageRequest).buildHttpRequest(); httpRequest.setUnsuccessfulResponseHandler(new HttpBackOffUnsuccessfulResponseHandler( new ExponentialBackOff())); // Execute request httpRequest.execute(); } catch (Exception e) { e.printStackTrace(); } } }
Python
"""This code sends an image to the user with a fallback text. Read more: https://developers.google.com/business-communications/business-messages/guides/how-to/message/send?hl=en#images This code is based on the https://github.com/google-business-communications/python-businessmessages Python Business Messages client library. """ import uuid from businessmessages import businessmessages_v1_client as bm_client from businessmessages.businessmessages_v1_messages import BusinessMessagesContentInfo from businessmessages.businessmessages_v1_messages import BusinessmessagesConversationsMessagesCreateRequest from businessmessages.businessmessages_v1_messages import BusinessMessagesImage from businessmessages.businessmessages_v1_messages import BusinessMessagesMessage from businessmessages.businessmessages_v1_messages import BusinessMessagesRepresentative from oauth2client.service_account import ServiceAccountCredentials # Edit the values below: path_to_service_account_key = './service_account_key.json' conversation_id = 'EDIT_HERE' image_file_url = 'EDIT_HERE' credentials = ServiceAccountCredentials.from_json_keyfile_name( path_to_service_account_key, scopes=['https://www.googleapis.com/auth/businessmessages']) client = bm_client.BusinessmessagesV1(credentials=credentials) representative_type_as_string = 'BOT' if representative_type_as_string == 'BOT': representative_type = BusinessMessagesRepresentative.RepresentativeTypeValueValuesEnum.BOT else: representative_type = BusinessMessagesRepresentative.RepresentativeTypeValueValuesEnum.HUMAN # Create an image message with fallback text message = BusinessMessagesMessage( messageId=str(uuid.uuid4().int), representative=BusinessMessagesRepresentative( representativeType=representative_type ), fallback='Hello, world!\nAn image has been sent with Business Messages.', image=BusinessMessagesImage( contentInfo=BusinessMessagesContentInfo( altText='Alternative text', fileUrl=image_file_url, forceRefresh=True ) )) # Create the message request create_request = BusinessmessagesConversationsMessagesCreateRequest( businessMessagesMessage=message, parent='conversations/' + conversation_id) # Send the message bm_client.BusinessmessagesV1.ConversationsMessagesService( client=client).Create(request=create_request)
권장 답변
추천 답장은 사용자에게 대화를 안내하는 대답을 제공하여 에이전트가 어떻게 대응하는지 알고 있을 것입니다
사용자가 추천 답장을 탭하면 에이전트는 응답의 텍스트 및 포스트백 데이터를 반환합니다.
추천 답장은 최대 25자(영문 기준), 메시지는 최대 자까지 입력할 수 있습니다. 13개 제안 중
예
다음 코드는 2개의 추천 답장과 함께 텍스트를 전송합니다. 서식 지정 및
자세한 내용은
conversations.messages.create
드림
및
SuggestedReply
cURL
# Copyright 2021 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # https://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # This code sends a text mesage to the user with suggested replies. # Read more: https://developers.google.com/business-communications/business-messages/guides/how-to/message/send?hl=en#suggested_replies # Replace the __CONVERSATION_ID__ with a conversation id that you can send messages to # Make sure a service account key file exists at ./service_account_key.json curl -X POST "https://businessmessages.googleapis.com/v1/conversations/__CONVERSATION_ID__/messages" \ -H "Content-Type: application/json" \ -H "User-Agent: curl/business-messages" \ -H "$(oauth2l header --json ./service_account_key.json businessmessages)" \ -d "{ 'messageId': '$(uuidgen)', 'text': 'Hello, world!', 'fallback': 'Hello, world!\n\nReply with \"Hello\" or \"Hi!\"', 'suggestions': [ { 'reply': { 'text': 'Hello', 'postbackData': 'hello-formal', }, }, { 'reply': { 'text': 'Hi!', 'postbackData': 'hello-informal', }, }, ], 'representative': { 'avatarImage': 'https://developers.google.com/identity/images/g-logo.png', 'displayName': 'Chatbot', 'representativeType': 'BOT' }, }"
Node.js
/** * This code sends a text mesage to the user with suggested replies. * Read more: https://developers.google.com/business-communications/business-messages/guides/how-to/message/send?hl=en#suggested_replies * * This code is based on the https://github.com/google-business-communications/nodejs-businessmessages Node.js * Business Messages client library. */ /** * Edit the values below: */ const PATH_TO_SERVICE_ACCOUNT_KEY = './service_account_key.json'; const CONVERSATION_ID = 'EDIT_HERE'; const businessmessages = require('businessmessages'); const uuidv4 = require('uuid').v4; const {google} = require('googleapis'); // Initialize the Business Messages API const bmApi = new businessmessages.businessmessages_v1.Businessmessages({}); // Set the scope that we need for the Business Messages API const scopes = [ 'https://www.googleapis.com/auth/businessmessages', ]; // Set the private key to the service account file const privatekey = require(PATH_TO_SERVICE_ACCOUNT_KEY); /** * Posts a message of "Hello, world!" to the Business Messages API along with two suggested replies. * * @param {string} conversationId The unique id for this user and agent. * @param {string} representativeType A value of BOT or HUMAN. */ async function sendMessage(conversationId, representativeType) { const authClient = await initCredentials(); // Create a text message with two suggested replies const apiParams = { auth: authClient, parent: 'conversations/' + conversationId, resource: { messageId: uuidv4(), representative: { representativeType: representativeType, }, fallback: 'Hello, world!\n\nReply with "Hello" or "Hi!"', text: 'Hello, world!', suggestions: [ { reply: { text: 'Hello', postbackData: 'hello-formal', }, }, { reply: { text: 'Hello', postbackData: 'hello-informal', }, }, ], }, }; // Call the message create function using the // Business Messages client library bmApi.conversations.messages.create(apiParams, {auth: authClient}, (err, response) => { console.log(err); console.log(response); }); } /** * Initializes the Google credentials for calling the * Business Messages API. */ async function initCredentials() { // configure a JWT auth client const authClient = new google.auth.JWT( privatekey.client_email, null, privatekey.private_key, scopes, ); return new Promise(function(resolve, reject) { // authenticate request authClient.authorize(function(err, tokens) { if (err) { reject(false); } else { resolve(authClient); } }); }); } sendMessage(CONVERSATION_ID, 'BOT');
자바
import com.google.api.client.googleapis.services.AbstractGoogleClientRequest; import com.google.api.client.http.HttpBackOffUnsuccessfulResponseHandler; import com.google.api.client.http.HttpRequest; import com.google.api.client.googleapis.auth.oauth2.GoogleCredential; import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport; import com.google.api.client.http.HttpTransport; import com.google.api.client.json.jackson2.JacksonFactory; import com.google.api.client.util.ExponentialBackOff; import com.google.api.services.businessmessages.v1.Businessmessages; import com.google.api.services.businessmessages.v1.model.*; import java.io.FileInputStream; import java.util.Arrays; import java.util.UUID; class SendSuggestedReplySnippet { /** * Initializes credentials used by the Business Messages API. */ private static Businessmessages.Builder getBusinessMessagesBuilder() { Businessmessages.Builder builder = null; try { GoogleCredential credential = GoogleCredential .fromStream(new FileInputStream("PATH_TO_SERVICE_ACCOUNT_KEY")); credential = credential.createScoped(Arrays.asList( "https://www.googleapis.com/auth/businessmessages")); credential.refreshToken(); HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport(); JacksonFactory jsonFactory = JacksonFactory.getDefaultInstance(); // Create instance of the Business Messages API builder = new Businessmessages .Builder(httpTransport, jsonFactory, null) .setApplicationName("Sample Application"); // Set the API credentials and endpoint builder.setHttpRequestInitializer(credential); } catch (Exception e) { e.printStackTrace(); } return builder; } public static void main(String args[]) { try { String conversationId = "CONVERSATION_ID"; // Create client library reference Businessmessages.Builder builder = getBusinessMessagesBuilder(); // Create a text message with two suggested replies BusinessMessagesMessage message = new BusinessMessagesMessage() .setMessageId(UUID.randomUUID().toString()) .setText("Hello, world!") .setFallback("Hello, world!\n\nReply with \"Hello\" or \"Hi!\"") .setSuggestions(Arrays.asList( new BusinessMessagesSuggestion() .setReply(new BusinessMessagesSuggestedReply() .setText("Hello").setPostbackData("hello-formal") ), new BusinessMessagesSuggestion() .setReply(new BusinessMessagesSuggestedReply() .setText("Hi!").setPostbackData("hello-informal") )) ) .setRepresentative(new BusinessMessagesRepresentative() .setRepresentativeType("TYPE")); // Create message request Businessmessages.Conversations.Messages.Create messageRequest = builder.build().conversations().messages() .create("conversations/" + conversationId, message); // Setup retries with exponential backoff HttpRequest httpRequest = ((AbstractGoogleClientRequest) messageRequest).buildHttpRequest(); httpRequest.setUnsuccessfulResponseHandler(new HttpBackOffUnsuccessfulResponseHandler( new ExponentialBackOff())); // Execute request httpRequest.execute(); } catch (Exception e) { e.printStackTrace(); } } }
Python
"""This code sends a text mesage to the user with suggested replies. Read more: https://developers.google.com/business-communications/business-messages/guides/how-to/message/send?hl=en#suggested_replies This code is based on the https://github.com/google-business-communications/python-businessmessages Python Business Messages client library. """ import uuid from businessmessages import businessmessages_v1_client as bm_client from businessmessages.businessmessages_v1_messages import BusinessmessagesConversationsMessagesCreateRequest from businessmessages.businessmessages_v1_messages import BusinessMessagesMessage from businessmessages.businessmessages_v1_messages import BusinessMessagesRepresentative from businessmessages.businessmessages_v1_messages import BusinessMessagesSuggestedReply from businessmessages.businessmessages_v1_messages import BusinessMessagesSuggestion from oauth2client.service_account import ServiceAccountCredentials # Edit the values below: path_to_service_account_key = './service_account_key.json' conversation_id = 'EDIT_HERE' credentials = ServiceAccountCredentials.from_json_keyfile_name( path_to_service_account_key, scopes=['https://www.googleapis.com/auth/businessmessages']) client = bm_client.BusinessmessagesV1(credentials=credentials) representative_type_as_string = 'BOT' if representative_type_as_string == 'BOT': representative_type = BusinessMessagesRepresentative.RepresentativeTypeValueValuesEnum.BOT else: representative_type = BusinessMessagesRepresentative.RepresentativeTypeValueValuesEnum.HUMAN # Create a text message with two suggested replies and fallback text message = BusinessMessagesMessage( messageId=str(uuid.uuid4().int), representative=BusinessMessagesRepresentative( representativeType=representative_type ), text='Hello, world!', fallback='Hello, world!\n\nReply with \"Hello\" or \"Hi!\"', suggestions=[ BusinessMessagesSuggestion( reply=BusinessMessagesSuggestedReply( text='Hello', postbackData='hello-formal') ), BusinessMessagesSuggestion( reply=BusinessMessagesSuggestedReply( text='Hi!', postbackData='hello-informal') ) ]) # Create the message request create_request = BusinessmessagesConversationsMessagesCreateRequest( businessMessagesMessage=message, parent='conversations/' + conversation_id) # Send the message bm_client.BusinessmessagesV1.ConversationsMessagesService( client=client).Create(request=create_request)
권장 작업
추천 작업은 기본 대화형 환경을 활용하여 사용자에게 대화를 안내합니다. 기기의 기능을 제한하지 않습니다. 사용자가 추천 작업을 탭하면 에이전트가 작업의 텍스트 및 포스트백 데이터가 포함된 메시지를 수신합니다.
추천 작업은 최대 25자(영문 기준), 메시지는 최대 자까지 입력할 수 있습니다. 13개 제안 중
형식 지정 및 값 옵션은 다음을 참고하세요.
conversations.messages.create
드림
및
SuggestedAction
URL 열기 작업
URL 열기 작업을 사용하면 에이전트는 사용자가 열 URL을 추천합니다. 만약 URL의 기본 핸들러로 등록되어 있으면 대신 앱이 열립니다. 작업의 아이콘은 앱의 아이콘입니다. URL 열기 작업은 URL만 지원 다른 프로토콜 (예: mailto)은 지원됩니다.
다음 코드는 URL 열기 작업을 사용하여 텍스트를 보냅니다. 형식 및 값
옵션은
OpenUrlAction
cURL
# Copyright 2021 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # https://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # This code sends a text mesage to the user with a suggestion action toopen a URL # and a fallback text. # Read more: https://developers.google.com/business-communications/business-messages/guides/how-to/message/send?hl=en#open_url_action # Replace the __CONVERSATION_ID__ with a conversation id that you can send messages to # Make sure a service account key file exists at ./service_account_key.json curl -X POST "https://businessmessages.googleapis.com/v1/conversations/__CONVERSATION_ID__/messages" \ -H "Content-Type: application/json" \ -H "User-Agent: curl/business-messages" \ -H "$(oauth2l header --json ./service_account_key.json businessmessages)" \ -d "{ 'messageId': '$(uuidgen)', 'text': 'Hello world!', 'fallback': 'Hello, world!\n\nSay \"Hello\" at https://www.growingtreebank.com', 'suggestions': [ { 'action': { 'text': 'Hello', 'postbackData': 'hello-formal', 'openUrlAction': { 'url': 'https://www.growingtreebank.com', } }, }, ], 'representative': { 'avatarImage': 'https://developers.google.com/identity/images/g-logo.png', 'displayName': 'Chatbot', 'representativeType': 'BOT' }, }"
Node.js
/** * This code sends a text mesage to the user with a suggestion action toopen a URL * and a fallback text. * Read more: https://developers.google.com/business-communications/business-messages/guides/how-to/message/send?hl=en#open_url_action * * This code is based on the https://github.com/google-business-communications/nodejs-businessmessages Node.js * Business Messages client library. */ /** * Edit the values below: */ const PATH_TO_SERVICE_ACCOUNT_KEY = './service_account_key.json'; const CONVERSATION_ID = 'EDIT_HERE'; const businessmessages = require('businessmessages'); const uuidv4 = require('uuid').v4; const {google} = require('googleapis'); // Initialize the Business Messages API const bmApi = new businessmessages.businessmessages_v1.Businessmessages({}); // Set the scope that we need for the Business Messages API const scopes = [ 'https://www.googleapis.com/auth/businessmessages', ]; // Set the private key to the service account file const privatekey = require(PATH_TO_SERVICE_ACCOUNT_KEY); /** * Posts a message with an open URL action to the Business Messages API. * * @param {string} conversationId The unique id for this user and agent. * @param {string} representativeType A value of BOT or HUMAN. */ async function sendMessage(conversationId, representativeType) { const authClient = await initCredentials(); if (authClient) { // Create the payload for sending a message along with an open url action const apiParams = { auth: authClient, parent: 'conversations/' + conversationId, resource: { messageId: uuidv4(), representative: { representativeType: representativeType, }, fallback: 'Hello, world!\n\nSay \"Hello\" at https://www.growingtreebank.com', text: 'Hello world!', suggestions: [ { action: { text: 'Hello', postbackData: 'hello-formal', openUrlAction: { url: 'https://www.growingtreebank.com', }, }, }, ], }, }; // Call the message create function using the // Business Messages client library bmApi.conversations.messages.create(apiParams, {auth: authClient}, (err, response) => { console.log(err); console.log(response); }); } else { console.log('Authentication failure.'); } } /** * Initializes the Google credentials for calling the * Business Messages API. */ async function initCredentials() { // configure a JWT auth client const authClient = new google.auth.JWT( privatekey.client_email, null, privatekey.private_key, scopes, ); return new Promise(function(resolve, reject) { // authenticate request authClient.authorize(function(err, tokens) { if (err) { reject(false); } else { resolve(authClient); } }); }); } sendMessage(CONVERSATION_ID, 'BOT');
자바
import com.google.api.client.googleapis.services.AbstractGoogleClientRequest; import com.google.api.client.http.HttpBackOffUnsuccessfulResponseHandler; import com.google.api.client.http.HttpRequest; import com.google.api.client.googleapis.auth.oauth2.GoogleCredential; import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport; import com.google.api.client.http.HttpTransport; import com.google.api.client.json.jackson2.JacksonFactory; import com.google.api.client.util.ExponentialBackOff; import com.google.api.services.businessmessages.v1.Businessmessages; import com.google.api.services.businessmessages.v1.model.*; import java.io.FileInputStream; import java.util.Arrays; import java.util.UUID; class SendSuggestedActionSnippet { /** * Initializes credentials used by the Business Messages API. */ private static Businessmessages.Builder getBusinessMessagesBuilder() { Businessmessages.Builder builder = null; try { GoogleCredential credential = GoogleCredential .fromStream(new FileInputStream("PATH_TO_SERVICE_ACCOUNT_KEY")); credential = credential.createScoped(Arrays.asList( "https://www.googleapis.com/auth/businessmessages")); credential.refreshToken(); HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport(); JacksonFactory jsonFactory = JacksonFactory.getDefaultInstance(); // Create instance of the Business Messages API builder = new Businessmessages .Builder(httpTransport, jsonFactory, null) .setApplicationName("Sample Application"); // Set the API credentials and endpoint builder.setHttpRequestInitializer(credential); } catch (Exception e) { e.printStackTrace(); } return builder; } public static void main(String args[]) { try { String conversationId = "CONVERSATION_ID"; // Create client library reference Businessmessages.Builder builder = getBusinessMessagesBuilder(); // Create a text message with an open url action BusinessMessagesMessage message = new BusinessMessagesMessage() .setMessageId(UUID.randomUUID().toString()) .setText("Hello world!") .setFallback("Hello, world!\n\nSay \"Hello\" at https://www.growingtreebank.com") .setSuggestions(Arrays.asList(new BusinessMessagesSuggestion() .setAction(new BusinessMessagesSuggestedAction() .setText("Hello").setPostbackData("hello-formal") .setOpenUrlAction( new BusinessMessagesOpenUrlAction().setUrl("https://www.growingtreebank.com")) )) ) .setRepresentative(new BusinessMessagesRepresentative() .setRepresentativeType("TYPE")); // Create message request Businessmessages.Conversations.Messages.Create messageRequest = builder.build().conversations().messages() .create("conversations/" + conversationId, message); // Setup retries with exponential backoff HttpRequest httpRequest = ((AbstractGoogleClientRequest) messageRequest).buildHttpRequest(); httpRequest.setUnsuccessfulResponseHandler(new HttpBackOffUnsuccessfulResponseHandler( new ExponentialBackOff())); // Execute request httpRequest.execute(); } catch (Exception e) { e.printStackTrace(); } } }
Python
"""This code sends a text mesage to the user with a suggestion action to open a URL. Read more: https://developers.google.com/business-communications/business-messages/guides/how-to/message/send?hl=en#open_url_action This code is based on the https://github.com/google-business-communications/python-businessmessages Python Business Messages client library. """ import uuid from businessmessages import businessmessages_v1_client as bm_client from businessmessages.businessmessages_v1_messages import BusinessmessagesConversationsMessagesCreateRequest from businessmessages.businessmessages_v1_messages import BusinessMessagesMessage from businessmessages.businessmessages_v1_messages import BusinessMessagesOpenUrlAction from businessmessages.businessmessages_v1_messages import BusinessMessagesRepresentative from businessmessages.businessmessages_v1_messages import BusinessMessagesSuggestedAction from businessmessages.businessmessages_v1_messages import BusinessMessagesSuggestion from oauth2client.service_account import ServiceAccountCredentials # Edit the values below: path_to_service_account_key = './service_account_key.json' conversation_id = 'EDIT_HERE' credentials = ServiceAccountCredentials.from_json_keyfile_name( path_to_service_account_key, scopes=['https://www.googleapis.com/auth/businessmessages']) client = bm_client.BusinessmessagesV1(credentials=credentials) representative_type_as_string = 'BOT' if representative_type_as_string == 'BOT': representative_type = BusinessMessagesRepresentative.RepresentativeTypeValueValuesEnum.BOT else: representative_type = BusinessMessagesRepresentative.RepresentativeTypeValueValuesEnum.HUMAN # Create a text message with an open url action and fallback text message = BusinessMessagesMessage( messageId=str(uuid.uuid4().int), representative=BusinessMessagesRepresentative( representativeType=representative_type ), text='Hello, world!', fallback='Hello, world!\n\nReply with \"Hello\" or \"Hi!\"', suggestions=[ BusinessMessagesSuggestion( action=BusinessMessagesSuggestedAction( text='Hello', postbackData='hello-formal', openUrlAction=BusinessMessagesOpenUrlAction( url='https://www.growingtreebank.com')) ), ]) # Create the message request create_request = BusinessmessagesConversationsMessagesCreateRequest( businessMessagesMessage=message, parent='conversations/' + conversation_id) # Send the message bm_client.BusinessmessagesV1.ConversationsMessagesService( client=client).Create(request=create_request)
전화 걸기 작업
다이얼 작업은 사용자가 전화를 걸 전화번호를 제안합니다. 사용자가 다이얼 작업 추천 칩을 사용하면 사용자의 기본 다이얼러 앱이 지정된 전화번호가 자동 입력됩니다.
다음 코드는 전화 걸기 작업을 사용하여 텍스트를 전송합니다. 형식 및 값
옵션은
DialAction
cURL
# Copyright 2021 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # https://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # This code sends a text mesage to the user with a suggestion action to dial # a phone number and a fallback text. # Read more: https://developers.google.com/business-communications/business-messages/guides/how-to/message/send?hl=en#dial_action # Replace the __CONVERSATION_ID__ with a conversation id that you can send messages to # Make sure a service account key file exists at ./service_account_key.json curl -X POST "https://businessmessages.googleapis.com/v1/conversations/__CONVERSATION_ID__/messages" \ -H "Content-Type: application/json" \ -H "User-Agent: curl/business-messages" \ -H "$(oauth2l header --json ./service_account_key.json businessmessages)" \ -d "{ 'messageId': '$(uuidgen)', 'text': 'Contact support for help with this issue.', 'fallback': 'Give us a call at +12223334444.', 'suggestions': [ { 'action': { 'text': 'Call support', 'postbackData': 'call-support', 'dialAction': { 'phoneNumber': '+12223334444', } }, }, ], 'representative': { 'avatarImage': 'https://developers.google.com/identity/images/g-logo.png', 'displayName': 'Chatbot', 'representativeType': 'BOT' }, }"
Node.js
/** * This code sends a text mesage to the user with a suggestion action to dial * a phone number and a fallback text. * Read more: https://developers.google.com/business-communications/business-messages/guides/how-to/message/send?hl=en#dial_action * * This code is based on the https://github.com/google-business-communications/nodejs-businessmessages Node.js * Business Messages client library. */ /** * Edit the values below: */ const PATH_TO_SERVICE_ACCOUNT_KEY = './service_account_key.json'; const CONVERSATION_ID = 'EDIT_HERE'; const businessmessages = require('businessmessages'); const uuidv4 = require('uuid').v4; const {google} = require('googleapis'); // Initialize the Business Messages API const bmApi = new businessmessages.businessmessages_v1.Businessmessages({}); // Set the scope that we need for the Business Messages API const scopes = [ 'https://www.googleapis.com/auth/businessmessages', ]; // Set the private key to the service account file const privatekey = require(PATH_TO_SERVICE_ACCOUNT_KEY); /** * Posts a message with a dial suggested action to the Business Messages API. * * @param {string} conversationId The unique id for this user and agent. * @param {string} representativeType A value of BOT or HUMAN. */ async function sendMessage(conversationId, representativeType) { const authClient = await initCredentials(); if (authClient) { // Create the payload for sending a message along with a dial action const apiParams = { auth: authClient, parent: 'conversations/' + conversationId, resource: { messageId: uuidv4(), representative: { representativeType: representativeType, }, fallback: 'Give us a call at +12223334444.', text: 'Contact support for help with this issue.', suggestions: [ { action: { text: 'Call support', postbackData: 'call-support', dialAction: { phoneNumber: '+12223334444', }, }, }, ], }, }; // Call the message create function using the // Business Messages client library bmApi.conversations.messages.create(apiParams, {auth: authClient}, (err, response) => { console.log(err); console.log(response); }); } else { console.log('Authentication failure.'); } } /** * Initializes the Google credentials for calling the * Business Messages API. */ async function initCredentials() { // configure a JWT auth client const authClient = new google.auth.JWT( privatekey.client_email, null, privatekey.private_key, scopes, ); return new Promise(function(resolve, reject) { // authenticate request authClient.authorize(function(err, tokens) { if (err) { reject(false); } else { resolve(authClient); } }); }); } sendMessage(CONVERSATION_ID, 'BOT');
자바
import com.google.api.client.googleapis.services.AbstractGoogleClientRequest; import com.google.api.client.http.HttpBackOffUnsuccessfulResponseHandler; import com.google.api.client.http.HttpRequest; import com.google.api.client.googleapis.auth.oauth2.GoogleCredential; import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport; import com.google.api.client.http.HttpTransport; import com.google.api.client.json.jackson2.JacksonFactory; import com.google.api.client.util.ExponentialBackOff; import com.google.api.services.businessmessages.v1.Businessmessages; import com.google.api.services.businessmessages.v1.model.*; import java.io.FileInputStream; import java.util.Arrays; import java.util.UUID; class SendDialActionSnippet { /** * Initializes credentials used by the Business Messages API. */ private static Businessmessages.Builder getBusinessMessagesBuilder() { Businessmessages.Builder builder = null; try { GoogleCredential credential = GoogleCredential .fromStream(new FileInputStream("PATH_TO_SERVICE_ACCOUNT_KEY")); credential = credential.createScoped(Arrays.asList( "https://www.googleapis.com/auth/businessmessages")); credential.refreshToken(); HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport(); JacksonFactory jsonFactory = JacksonFactory.getDefaultInstance(); // Create instance of the Business Messages API builder = new Businessmessages .Builder(httpTransport, jsonFactory, null) .setApplicationName("Sample Application"); // Set the API credentials and endpoint builder.setHttpRequestInitializer(credential); } catch (Exception e) { e.printStackTrace(); } return builder; } public static void main(String args[]) { try { String conversationId = "CONVERSATION_ID"; // Create client library reference Businessmessages.Builder builder = getBusinessMessagesBuilder(); // Create a text message with a dial action BusinessMessagesMessage message = new BusinessMessagesMessage() .setMessageId(UUID.randomUUID().toString()) .setText("Contact support for help with this issue.") .setFallback("Give us a call at +12223334444.") .setSuggestions(Arrays.asList(new BusinessMessagesSuggestion() .setAction(new BusinessMessagesSuggestedAction() .setText("Call support").setPostbackData("call-support") .setDialAction( new BusinessMessagesDialAction().setPhoneNumber("+12223334444")) ))) .setRepresentative(new BusinessMessagesRepresentative() .setRepresentativeType("TYPE")); // Create message request Businessmessages.Conversations.Messages.Create messageRequest = builder.build().conversations().messages() .create("conversations/" + conversationId, message); // Setup retries with exponential backoff HttpRequest httpRequest = ((AbstractGoogleClientRequest) messageRequest).buildHttpRequest(); httpRequest.setUnsuccessfulResponseHandler(new HttpBackOffUnsuccessfulResponseHandler( new ExponentialBackOff())); // Execute request httpRequest.execute(); } catch (Exception e) { e.printStackTrace(); } } }
Python
"""Sends a text mesage to the user with a suggestion action to dial a phone number. Read more: https://developers.google.com/business-communications/business-messages/guides/how-to/message/send?hl=en#dial_action This code is based on the https://github.com/google-business-communications/python-businessmessages Python Business Messages client library. """ import uuid from businessmessages import businessmessages_v1_client as bm_client from businessmessages.businessmessages_v1_messages import BusinessmessagesConversationsMessagesCreateRequest from businessmessages.businessmessages_v1_messages import BusinessMessagesDialAction from businessmessages.businessmessages_v1_messages import BusinessMessagesMessage from businessmessages.businessmessages_v1_messages import BusinessMessagesRepresentative from businessmessages.businessmessages_v1_messages import BusinessMessagesSuggestedAction from businessmessages.businessmessages_v1_messages import BusinessMessagesSuggestion from oauth2client.service_account import ServiceAccountCredentials # Edit the values below: path_to_service_account_key = './service_account_key.json' conversation_id = 'EDIT_HERE' credentials = ServiceAccountCredentials.from_json_keyfile_name( path_to_service_account_key, scopes=['https://www.googleapis.com/auth/businessmessages']) client = bm_client.BusinessmessagesV1(credentials=credentials) representative_type_as_string = 'BOT' if representative_type_as_string == 'BOT': representative_type = BusinessMessagesRepresentative.RepresentativeTypeValueValuesEnum.BOT else: representative_type = BusinessMessagesRepresentative.RepresentativeTypeValueValuesEnum.HUMAN # Create a text message with a dial action and fallback text message = BusinessMessagesMessage( messageId=str(uuid.uuid4().int), representative=BusinessMessagesRepresentative( representativeType=representative_type ), text='Contact support for help with this issue.', fallback='Give us a call at +12223334444.', suggestions=[ BusinessMessagesSuggestion( action=BusinessMessagesSuggestedAction( text='Call support', postbackData='call-support', dialAction=BusinessMessagesDialAction( phoneNumber='+12223334444')) ), ]) # Create the message request create_request = BusinessmessagesConversationsMessagesCreateRequest( businessMessagesMessage=message, parent='conversations/' + conversation_id) # Send the message bm_client.BusinessmessagesV1.ConversationsMessagesService( client=client).Create(request=create_request)
인증 요청 추천
인증 요청 제안에서 사용자에게 OAuth 2.0 호환 애플리케이션, 인증 코드를 전달하여 확인 맞춤화된 사용자 경험 및 자세한 대화 지원 있습니다 다음을 참조하세요. 인증: OAuth).
예
다음 코드는 인증 요청 제안과 함께 텍스트를 전송합니다. 대상
서식 및 값 옵션에 대한 자세한 내용은
conversations.messages.create
드림
및
Suggestion
cURL
# Copyright 2021 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # https://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # This code sends a text message to the user with an authentication request suggestion # that allows the user to authenticate with OAuth. It also has a fallback text. # Read more: https://developers.google.com/business-communications/business-messages/guides/how-to/message/send?hl=en#authentication-request-suggestion # Replace the __CONVERSATION_ID__ with a conversation id that you can send messages to # Make sure a service account key file exists at ./service_account_key.json # Replace the __CLIENT_ID__ # Replace the __CODE_CHALLENGE__ # Replace the __SCOPE__ curl -X POST "https://businessmessages.googleapis.com/v1/conversations/__CONVERSATION_ID__/messages" \ -H "Content-Type: application/json" \ -H "User-Agent: curl/business-messages" \ -H "$(oauth2l header --json ./service_account_key.json businessmessages)" \ -d "{ 'messageId': '$(uuidgen)', 'text': 'Sign in to continue the conversation.', 'fallback': 'Visit support.growingtreebank.com to continue.', 'suggestions': [ { 'authenticationRequest': { 'oauth': { 'clientId': '__CLIENT_ID__', 'codeChallenge': '__CODE_CHALLENGE__', 'scopes': [ '__SCOPE__', ], }, }, }, ], 'representative': { 'avatarImage': 'https://developers.google.com/identity/images/g-logo.png', 'displayName': 'Chatbot', 'representativeType': 'BOT' } }"
Node.js
/** * This code sends a text message to the user with an authentication request suggestion * that allows the user to authenticate with OAuth. It also has a fallback text. * Read more: https://developers.google.com/business-communications/business-messages/guides/how-to/message/send?hl=en#authentication-request-suggestion * * This code is based on the https://github.com/google-business-communications/nodejs-businessmessages Node.js * Business Messages client library. */ /** * Before continuing, learn more about the prerequisites for authenticating * with OAuth at: https://developers.google.com/business-communications/business-messages/guides/how-to/integrate/oauth?hl=en * * Edit the values below: */ const PATH_TO_SERVICE_ACCOUNT_KEY = './service_account_key.json'; const CONVERSATION_ID = 'EDIT_HERE'; const OAUTH_CLIENT_ID = 'EDIT_HERE'; const OAUTH_CODE_CHALLENGE = 'EDIT_HERE'; const OAUTH_SCOPE = 'EDIT_HERE'; const businessmessages = require('businessmessages'); const uuidv4 = require('uuid').v4; const {google} = require('googleapis'); // Initialize the Business Messages API const bmApi = new businessmessages.businessmessages_v1.Businessmessages({}); // Set the scope that we need for the Business Messages API const scopes = [ 'https://www.googleapis.com/auth/businessmessages', ]; // Set the private key to the service account file const privatekey = require(PATH_TO_SERVICE_ACCOUNT_KEY); /** * Posts a message to the Business Messages API along with an authentication request. * * @param {string} conversationId The unique id for this user and agent. * @param {string} representativeType A value of BOT or HUMAN. */ async function sendMessage(conversationId, representativeType) { const authClient = await initCredentials(); if (authClient) { // Create the payload for sending a message along with an authentication request const apiParams = { auth: authClient, parent: 'conversations/' + conversationId, resource: { messageId: uuidv4(), representative: { representativeType: representativeType, }, fallback: 'Visit support.growingtreebank.com to continue.', text: 'Sign in to continue the conversation.', suggestions: [ { authenticationRequest: { oauth: { clientId: OAUTH_CLIENT_ID, codeChallenge: OAUTH_CODE_CHALLENGE, scopes: [OAUTH_SCOPE] } } }, ], }, }; // Call the message create function using the // Business Messages client library bmApi.conversations.messages.create(apiParams, {auth: authClient}, (err, response) => { console.log(err); console.log(response); }); } else { console.log('Authentication failure.'); } } /** * Initializes the Google credentials for calling the * Business Messages API. */ async function initCredentials() { // configure a JWT auth client const authClient = new google.auth.JWT( privatekey.client_email, null, privatekey.private_key, scopes, ); return new Promise(function(resolve, reject) { // authenticate request authClient.authorize(function(err, tokens) { if (err) { reject(false); } else { resolve(authClient); } }); }); } sendMessage(CONVERSATION_ID, 'BOT');
자바
import com.google.api.client.googleapis.services.AbstractGoogleClientRequest; import com.google.api.client.http.HttpBackOffUnsuccessfulResponseHandler; import com.google.api.client.http.HttpRequest; import com.google.api.client.googleapis.auth.oauth2.GoogleCredential; import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport; import com.google.api.client.http.HttpTransport; import com.google.api.client.json.jackson2.JacksonFactory; import com.google.api.client.util.ExponentialBackOff; import com.google.api.services.businessmessages.v1.Businessmessages; import com.google.api.services.businessmessages.v1.model.*; import java.io.FileInputStream; import java.util.Arrays; import java.util.UUID; class SendAuthenticationRequestSuggestionSnippet { /** * Initializes credentials used by the Business Messages API. */ private static Businessmessages.Builder getBusinessMessagesBuilder() { Businessmessages.Builder builder = null; try { GoogleCredential credential = GoogleCredential .fromStream(new FileInputStream("PATH_TO_SERVICE_ACCOUNT_KEY")); credential = credential.createScoped(Arrays.asList( "https://www.googleapis.com/auth/businessmessages")); credential.refreshToken(); HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport(); JacksonFactory jsonFactory = JacksonFactory.getDefaultInstance(); // Create instance of the Business Messages API builder = new Businessmessages .Builder(httpTransport, jsonFactory, null) .setApplicationName("Sample Application"); // Set the API credentials and endpoint builder.setHttpRequestInitializer(credential); } catch (Exception e) { e.printStackTrace(); } return builder; } public static void main(String args[]) { try { String conversationId = "CONVERSATION_ID"; // Create client library reference Businessmessages.Builder builder = getBusinessMessagesBuilder(); // Create a text message with an authentication request BusinessMessagesMessage message = new BusinessMessagesMessage() .setMessageId(UUID.randomUUID().toString()) .setText("Would you like to chat with a live agent?") .setFallback("Would you like to chat with a live agent?") .setSuggestions(Arrays.asList(new BusinessMessagesSuggestion() .setAuthenticationRequest(new BusinessMessagesAuthenticationRequest() .setOauth(new BusinessMessagesAuthenticationRequestOauth() .setClientId("CLIENT_ID") .setCodeChallenge("CODE_CHALLENGE") .setScopes(Arrays.asList("SCOPE")) ))) ) .setRepresentative(new BusinessMessagesRepresentative() .setRepresentativeType("TYPE")); // Create message request Businessmessages.Conversations.Messages.Create messageRequest = builder.build().conversations().messages() .create("conversations/" + conversationId, message); // Setup retries with exponential backoff HttpRequest httpRequest = ((AbstractGoogleClientRequest) messageRequest).buildHttpRequest(); httpRequest.setUnsuccessfulResponseHandler(new HttpBackOffUnsuccessfulResponseHandler( new ExponentialBackOff())); // Execute request httpRequest.execute(); } catch (Exception e) { e.printStackTrace(); } } }
Python
"""Sends a text message to the user with an authentication request suggestion. It allows the user to authenticate with OAuth and has a fallback text. Read more: https://developers.google.com/business-communications/business-messages/guides/how-to/message/send?hl=en#authentication-request-suggestion This code is based on the https://github.com/google-business-communications/python-businessmessages Python Business Messages client library. """ import uuid from businessmessages import businessmessages_v1_client as bm_client from businessmessages.businessmessages_v1_messages import BusinessMessagesAuthenticationRequest from businessmessages.businessmessages_v1_messages import BusinessMessagesAuthenticationRequestOauth from businessmessages.businessmessages_v1_messages import BusinessmessagesConversationsMessagesCreateRequest from businessmessages.businessmessages_v1_messages import BusinessMessagesMessage from businessmessages.businessmessages_v1_messages import BusinessMessagesRepresentative from businessmessages.businessmessages_v1_messages import BusinessMessagesSuggestion from oauth2client.service_account import ServiceAccountCredentials # Before continuing, learn more about the prerequisites for authenticating # with OAuth at: https://developers.google.com/business-communications/business-messages/guides/how-to/integrate/oauth?hl=en # Edit the values below: path_to_service_account_key = './service_account_key.json' conversation_id = 'EDIT_HERE' oauth_client_id = 'EDIT_HERE' oauth_code_challenge = 'EDIT_HERE' oauth_scope = 'EDIT_HERE' credentials = ServiceAccountCredentials.from_json_keyfile_name( path_to_service_account_key, scopes=['https://www.googleapis.com/auth/businessmessages']) client = bm_client.BusinessmessagesV1(credentials=credentials) representative_type_as_string = 'BOT' if representative_type_as_string == 'BOT': representative_type = BusinessMessagesRepresentative.RepresentativeTypeValueValuesEnum.BOT else: representative_type = BusinessMessagesRepresentative.RepresentativeTypeValueValuesEnum.HUMAN # Create a text message with an authentication request message = BusinessMessagesMessage( messageId=str(uuid.uuid4().int), representative=BusinessMessagesRepresentative( representativeType=representative_type ), text='Sign in to continue the conversation.', fallback='Visit support.growingtreebank.com to continue.', suggestions=[ BusinessMessagesSuggestion( authenticationRequest=BusinessMessagesAuthenticationRequest( oauth=BusinessMessagesAuthenticationRequestOauth( clientId=oauth_client_id, codeChallenge=oauth_code_challenge, scopes=[oauth_scope]) ) ), ] ) # Create the message request create_request = BusinessmessagesConversationsMessagesCreateRequest( businessMessagesMessage=message, parent='conversations/' + conversation_id) # Send the message bm_client.BusinessmessagesV1.ConversationsMessagesService( client=client).Create(request=create_request)
실시간 상담사 요청 추천
실시간 상담사 요청 추천을 사용하면 사용자가 복잡한 상호작용 중 또는 자동화가 불가능한 경우 사용자 요청을 처리합니다
사용자는 오버플로우에서 대화 중 언제든지 실제 상담사를 요청할 수 있습니다. 선택합니다. 이 추천을 통해 상담사는 프로그래매틱 방식으로 맥락에 따라 인간 대리인과 있습니다. 상담사는 항상 실제 상담사에게 응답할 준비가 되어 있어야 합니다. 실제 상담사 요청 추천을 전송하지 않은 경우에도 마찬가지입니다.
사용자가 실시간 상담사 요청 추천을 탭하면 실시간 상담사가 트리거됩니다. 요청됨 이벤트로 이동합니다.
예
다음 코드는 실시간 상담사 요청 제안과 함께 텍스트를 전송합니다. 대상
서식 및 값 옵션에 대한 자세한 내용은
conversations.messages.create
드림
및
Suggestion
cURL
# Copyright 2021 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # https://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # This code sends a text message to the user with a Live agent request suggestion # that allows the user to connect with a Live agent. # Read more: https://developers.google.com/business-communications/business-messages/guides/how-to/message/send?hl=en#live_agent_request_suggestion # Replace the __CONVERSATION_ID__ with a conversation id that you can send messages to # Make sure a service account key file exists at ./service_account_key.json curl -X POST "https://businessmessages.googleapis.com/v1/conversations/__CONVERSATION_ID__/messages" \ -H "Content-Type: application/json" \ -H "User-Agent: curl/business-messages" \ -H "$(oauth2l header --json ./service_account_key.json businessmessages)" \ -d "{ 'messageId': '$(uuidgen)', 'text': 'Would you like to chat with a live agent?', 'fallback': 'Would you like to chat with a live agent?', 'suggestions': [ { 'liveAgentRequest': {}, }, ], 'representative': { 'avatarImage': 'https://developers.google.com/identity/images/g-logo.png', 'displayName': 'Chatbot', 'representativeType': 'BOT' }, }"
Node.js
/** * This code sends a text message to the user with a Live agent request suggestion * that allows the user to connect with a Live agent. * Read more: https://developers.google.com/business-communications/business-messages/guides/how-to/message/send?hl=en#live_agent_request_suggestion * * This code is based on the https://github.com/google-business-communications/nodejs-businessmessages Node.js * Business Messages client library. */ /** * Edit the values below: */ const PATH_TO_SERVICE_ACCOUNT_KEY = './service_account_key.json'; const CONVERSATION_ID = 'EDIT_HERE'; const businessmessages = require('businessmessages'); const uuidv4 = require('uuid').v4; const {google} = require('googleapis'); // Initialize the Business Messages API const bmApi = new businessmessages.businessmessages_v1.Businessmessages({}); // Set the scope that we need for the Business Messages API const scopes = [ 'https://www.googleapis.com/auth/businessmessages', ]; // Set the private key to the service account file const privatekey = require(PATH_TO_SERVICE_ACCOUNT_KEY); /** * Posts a message with a live agent request action to the Business Messages API. * * @param {string} conversationId The unique id for this user and agent. */ async function sendMessage(conversationId) { const authClient = await initCredentials(); if (authClient) { // Create the payload for sending a message along with a request for live agent action const apiParams = { auth: authClient, parent: 'conversations/' + conversationId, resource: { messageId: uuidv4(), representative: { representativeType: 'BOT', // Must be sent from a BOT representative }, fallback: 'Would you like to chat with a live agent?', text: 'Would you like to chat with a live agent?', suggestions: [ { liveAgentRequest: {} }, ], }, }; // Call the message create function using the // Business Messages client library bmApi.conversations.messages.create(apiParams, {auth: authClient}, (err, response) => { console.log(err); console.log(response); }); } else { console.log('Authentication failure.'); } } /** * Initializes the Google credentials for calling the * Business Messages API. */ async function initCredentials() { // configure a JWT auth client const authClient = new google.auth.JWT( privatekey.client_email, null, privatekey.private_key, scopes, ); return new Promise(function(resolve, reject) { // authenticate request authClient.authorize(function(err, tokens) { if (err) { reject(false); } else { resolve(authClient); } }); }); } sendMessage(CONVERSATION_ID);
자바
import com.google.api.client.googleapis.services.AbstractGoogleClientRequest; import com.google.api.client.http.HttpBackOffUnsuccessfulResponseHandler; import com.google.api.client.http.HttpRequest; import com.google.api.client.googleapis.auth.oauth2.GoogleCredential; import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport; import com.google.api.client.http.HttpTransport; import com.google.api.client.json.jackson2.JacksonFactory; import com.google.api.client.util.ExponentialBackOff; import com.google.api.services.businessmessages.v1.Businessmessages; import com.google.api.services.businessmessages.v1.model.*; import java.io.FileInputStream; import java.util.Arrays; import java.util.UUID; class SendLiveAgentRequestSuggestionSnippet { /** * Initializes credentials used by the Business Messages API. */ private static Businessmessages.Builder getBusinessMessagesBuilder() { Businessmessages.Builder builder = null; try { GoogleCredential credential = GoogleCredential .fromStream(new FileInputStream("PATH_TO_SERVICE_ACCOUNT_KEY")); credential = credential.createScoped(Arrays.asList( "https://www.googleapis.com/auth/businessmessages")); credential.refreshToken(); HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport(); JacksonFactory jsonFactory = JacksonFactory.getDefaultInstance(); // Create instance of the Business Messages API builder = new Businessmessages .Builder(httpTransport, jsonFactory, null) .setApplicationName("Sample Application"); // Set the API credentials and endpoint builder.setHttpRequestInitializer(credential); } catch (Exception e) { e.printStackTrace(); } return builder; } public static void main(String args[]) { try { String conversationId = "CONVERSATION_ID"; // Create client library reference Businessmessages.Builder builder = getBusinessMessagesBuilder(); // Create a text message with a live request action BusinessMessagesMessage message = new BusinessMessagesMessage() .setMessageId(UUID.randomUUID().toString()) .setText("Would you like to chat with a live agent?") .setFallback("Would you like to chat with a live agent?") .setSuggestions(Arrays.asList(new BusinessMessagesSuggestion() .setLiveAgentRequest(new BusinessMessagesLiveAgentRequest())) ) .setRepresentative(new BusinessMessagesRepresentative() .setRepresentativeType("BOT")); // Must be sent from a BOT representative // Create message request Businessmessages.Conversations.Messages.Create messageRequest = builder.build().conversations().messages() .create("conversations/" + conversationId, message); // Setup retries with exponential backoff HttpRequest httpRequest = ((AbstractGoogleClientRequest) messageRequest).buildHttpRequest(); httpRequest.setUnsuccessfulResponseHandler(new HttpBackOffUnsuccessfulResponseHandler( new ExponentialBackOff())); // Execute request httpRequest.execute(); } catch (Exception e) { e.printStackTrace(); } } }
Python
"""Sends a text message to the user with a Live agent request suggestion. It allows the user to connect with a Live agent. Read more: https://developers.google.com/business-communications/business-messages/guides/how-to/message/send?hl=en#live_agent_request_suggestion This code is based on the https://github.com/google-business-communications/python-businessmessages Python Business Messages client library. """ import uuid from businessmessages import businessmessages_v1_client as bm_client from businessmessages.businessmessages_v1_messages import BusinessmessagesConversationsMessagesCreateRequest from businessmessages.businessmessages_v1_messages import BusinessMessagesLiveAgentRequest from businessmessages.businessmessages_v1_messages import BusinessMessagesMessage from businessmessages.businessmessages_v1_messages import BusinessMessagesRepresentative from businessmessages.businessmessages_v1_messages import BusinessMessagesSuggestion from oauth2client.service_account import ServiceAccountCredentials # Edit the values below: path_to_service_account_key = './service_account_key.json' conversation_id = 'EDIT_HERE' credentials = ServiceAccountCredentials.from_json_keyfile_name( path_to_service_account_key, scopes=['https://www.googleapis.com/auth/businessmessages']) client = bm_client.BusinessmessagesV1(credentials=credentials) # Create a text message with a live agent request action and fallback text # Follow instructions at https://developers.google.com/business-communications/business-messages/guides/how-to/message/send?hl=en#live_agent_request_suggestion message = BusinessMessagesMessage( messageId=str(uuid.uuid4().int), representative=BusinessMessagesRepresentative( # Must be sent from a BOT representative representativeType=BusinessMessagesRepresentative.RepresentativeTypeValueValuesEnum.BOT ), text='Would you like to chat with a live agent?', fallback='Would you like to chat with a live agent?', suggestions=[ BusinessMessagesSuggestion( liveAgentRequest=BusinessMessagesLiveAgentRequest() ) ]) # Create the message request create_request = BusinessmessagesConversationsMessagesCreateRequest( businessMessagesMessage=message, parent='conversations/' + conversation_id) # Send the message bm_client.BusinessmessagesV1.ConversationsMessagesService( client=client).Create(request=create_request)
리치 카드
관련 정보, 미디어, 제안을 대량으로 전송해야 하는 경우 리치 카드를 전송해야 합니다. 리치 카드를 사용하면 에이전트가 포함할 수 있습니다
리치 카드에는 다음 항목이 포함될 수 있습니다.
- 미디어 (JPG, JPEG 또는 PNG, 최대 5MB)
- 미디어 썸네일 이미지 (JPG, JPEG 또는 PNG, 최대 25KB)
- 제목 (영문 기준 최대 200자)
- 설명 (영문 기준 최대 2,000자)
- 추천 답장 목록 및 추천 작업 (최대 4개)
리치 카드에는 나열된 항목의 일부 또는 전부를 포함할 수 있지만, 카드에는 최소 10개의 미디어 또는 제목이 있어야 합니다. 리치 카드에는 최대 4개의 추천 작업 및 추천 답장
에이전트는 리치 카드에 여러 개의 리치 카드를 함께 보낼 수 있습니다. 캐러셀을 사용하세요.
예
다음 코드는 이미지와 추천 답장이 포함된 리치 카드를 전송합니다. 대상
서식 및 값 옵션에 대한 자세한 내용은
conversations.messages.create
드림
및
RichCard
cURL
# Copyright 2021 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # https://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # This code sends a rich card to the user with a fallback text. # Read more: https://developers.google.com/business-communications/business-messages/guides/how-to/message/send?hl=en#rich-cards # Replace the __CONVERSATION_ID__ with a conversation id that you can send messages to # Make sure a service account key file exists at ./service_account_key.json curl -X POST "https://businessmessages.googleapis.com/v1/conversations/__CONVERSATION_ID__/messages" \ -H "Content-Type: application/json" \ -H "User-Agent: curl/business-messages" \ -H "$(oauth2l header --json ./service_account_key.json businessmessages)" \ -d "{ 'messageId': '$(uuidgen)', 'representative': { 'avatarImage': 'https://developers.google.com/identity/images/g-logo.png', 'displayName': 'Chatbot', 'representativeType': 'BOT' }, 'fallback': 'Hello, world!\nSent with Business Messages\n\nReply with \"Suggestion #1\" or \"Suggestion #2\"', 'richCard': { 'standaloneCard': { 'cardContent': { 'title': 'Hello, world!', 'description': 'Sent with Business Messages.', 'media': { 'height': 'TALL', 'contentInfo':{ 'altText': 'Google logo', 'fileUrl': 'https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png', 'forceRefresh': 'false' } }, 'suggestions': [ { 'reply': { 'text': 'Suggestion #1', 'postbackData': 'suggestion_1' } }, { 'reply': { 'text': 'Suggestion #2', 'postbackData': 'suggestion_2' } } ] } } } }"
Node.js
/** * This code sends a rich card to the user with a fallback text. * Read more: https://developers.google.com/business-communications/business-messages/guides/how-to/message/send?hl=en#rich-cards * * This code is based on the https://github.com/google-business-communications/nodejs-businessmessages Node.js * Business Messages client library. */ /** * Edit the values below: */ const PATH_TO_SERVICE_ACCOUNT_KEY = './service_account_key.json'; const CONVERSATION_ID = 'EDIT_HERE'; const businessmessages = require('businessmessages'); const uuidv4 = require('uuid').v4; const {google} = require('googleapis'); // Initialize the Business Messages API const bmApi = new businessmessages.businessmessages_v1.Businessmessages({}); // Set the scope that we need for the Business Messages API const scopes = [ 'https://www.googleapis.com/auth/businessmessages', ]; // Set the private key to the service account file const privatekey = require(PATH_TO_SERVICE_ACCOUNT_KEY); /** * Posts a rich card message to the Business Messages API. * * @param {string} conversationId The unique id for this user and agent. * @param {string} representativeType A value of BOT or HUMAN. */ async function sendMessage(conversationId, representativeType) { const authClient = await initCredentials(); if (authClient) { // Create the payload for sending a rich card message with two suggested replies const apiParams = { auth: authClient, parent: 'conversations/' + conversationId, resource: { messageId: uuidv4(), representative: { representativeType: representativeType, }, fallback: 'Hello, world!\nSent with Business Messages\n\nReply with \"Suggestion #1\" or \"Suggestion #2\"', richCard: { standaloneCard: { cardContent: { title: 'Hello, world!', description: 'Sent with Business Messages.', media: { height: 'TALL', contentInfo: { altText: 'Google logo', fileUrl: 'https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png', forceRefresh: false, }, }, suggestions: [ { reply: { text: 'Suggestion #1', postbackData: 'suggestion_1', }, }, { reply: { text: 'Suggestion #2', postbackData: 'suggestion_2', }, }, ], }, }, }, }, }; // Call the message create function using the // Business Messages client library bmApi.conversations.messages.create(apiParams, {auth: authClient}, (err, response) => { console.log(err); console.log(response); }); } else { console.log('Authentication failure.'); } } /** * Initializes the Google credentials for calling the * Business Messages API. */ async function initCredentials() { // configure a JWT auth client const authClient = new google.auth.JWT( privatekey.client_email, null, privatekey.private_key, scopes, ); return new Promise(function(resolve, reject) { // authenticate request authClient.authorize(function(err, tokens) { if (err) { reject(false); } else { resolve(authClient); } }); }); } sendMessage(CONVERSATION_ID, 'BOT');
자바
import com.google.api.client.googleapis.services.AbstractGoogleClientRequest; import com.google.api.client.http.HttpBackOffUnsuccessfulResponseHandler; import com.google.api.client.http.HttpRequest; import com.google.api.client.googleapis.auth.oauth2.GoogleCredential; import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport; import com.google.api.client.http.HttpTransport; import com.google.api.client.json.jackson2.JacksonFactory; import com.google.api.client.util.ExponentialBackOff; import com.google.api.services.businessmessages.v1.Businessmessages; import com.google.api.services.businessmessages.v1.model.*; import com.google.communications.businessmessages.v1.MediaHeight; import java.io.FileInputStream; import java.util.Arrays; import java.util.UUID; class SendRichCardMessageSnippet { /** * Initializes credentials used by the Business Messages API. */ private static Businessmessages.Builder getBusinessMessagesBuilder() { Businessmessages.Builder builder = null; try { GoogleCredential credential = GoogleCredential .fromStream(new FileInputStream("PATH_TO_SERVICE_ACCOUNT_KEY")); credential = credential.createScoped(Arrays.asList( "https://www.googleapis.com/auth/businessmessages")); credential.refreshToken(); HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport(); JacksonFactory jsonFactory = JacksonFactory.getDefaultInstance(); // Create instance of the Business Messages API builder = new Businessmessages .Builder(httpTransport, jsonFactory, null) .setApplicationName("Sample Application"); // Set the API credentials and endpoint builder.setHttpRequestInitializer(credential); } catch (Exception e) { e.printStackTrace(); } return builder; } public static void main(String args[]) { try { String conversationId = "CONVERSATION_ID"; // Create client library reference Businessmessages.Builder builder = getBusinessMessagesBuilder(); // Create a rich card with two suggested replies BusinessMessagesMessage message = new BusinessMessagesMessage() .setMessageId(UUID.randomUUID().toString()) .setFallback("Hello, world!\nSent with Business Messages\n\nReply with \"Suggestion #1\" or \"Suggestion #2\"") .setRichCard(new BusinessMessagesRichCard() .setStandaloneCard(new BusinessMessagesStandaloneCard() .setCardContent( new BusinessMessagesCardContent() .setTitle("Hello, world!") .setDescription("Sent with Business Messages.") .setSuggestions(Arrays.asList( new BusinessMessagesSuggestion() .setReply(new BusinessMessagesSuggestedReply() .setText("Suggestion #1").setPostbackData("suggestion_1") ), new BusinessMessagesSuggestion() .setReply(new BusinessMessagesSuggestedReply() .setText("Suggestion #2").setPostbackData("suggestion_2") )) ) .setMedia(new BusinessMessagesMedia() .setHeight(MediaHeight.MEDIUM.toString()) .setContentInfo( new BusinessMessagesContentInfo() .setAltText("Google logo") .setFileUrl("https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png") .setForceRefresh(false) )) ))) .setRepresentative(new BusinessMessagesRepresentative() .setRepresentativeType("TYPE")); // Create message request Businessmessages.Conversations.Messages.Create messageRequest = builder.build().conversations().messages() .create("conversations/" + conversationId, message); // Setup retries with exponential backoff HttpRequest httpRequest = ((AbstractGoogleClientRequest) messageRequest).buildHttpRequest(); httpRequest.setUnsuccessfulResponseHandler(new HttpBackOffUnsuccessfulResponseHandler( new ExponentialBackOff())); // Execute request httpRequest.execute(); } catch (Exception e) { e.printStackTrace(); } } }
Python
"""This code sends a rich card to the user with a fallback text. Read more: https://developers.google.com/business-communications/business-messages/guides/how-to/message/send?hl=en#rich-cards This code is based on the https://github.com/google-business-communications/python-businessmessages Python Business Messages client library. """ import uuid from businessmessages import businessmessages_v1_client as bm_client from businessmessages.businessmessages_v1_messages import BusinessMessagesCardContent from businessmessages.businessmessages_v1_messages import BusinessMessagesContentInfo from businessmessages.businessmessages_v1_messages import BusinessmessagesConversationsMessagesCreateRequest from businessmessages.businessmessages_v1_messages import BusinessMessagesMedia from businessmessages.businessmessages_v1_messages import BusinessMessagesMessage from businessmessages.businessmessages_v1_messages import BusinessMessagesRepresentative from businessmessages.businessmessages_v1_messages import BusinessMessagesRichCard from businessmessages.businessmessages_v1_messages import BusinessMessagesStandaloneCard from businessmessages.businessmessages_v1_messages import BusinessMessagesSuggestedReply from businessmessages.businessmessages_v1_messages import BusinessMessagesSuggestion from oauth2client.service_account import ServiceAccountCredentials # Edit the values below: path_to_service_account_key = './service_account_key.json' conversation_id = 'EDIT_HERE' credentials = ServiceAccountCredentials.from_json_keyfile_name( path_to_service_account_key, scopes=['https://www.googleapis.com/auth/businessmessages']) client = bm_client.BusinessmessagesV1(credentials=credentials) representative_type_as_string = 'BOT' if representative_type_as_string == 'BOT': representative_type = BusinessMessagesRepresentative.RepresentativeTypeValueValuesEnum.BOT else: representative_type = BusinessMessagesRepresentative.RepresentativeTypeValueValuesEnum.HUMAN # Create a rich card message with two suggested replies and fallback text message = BusinessMessagesMessage( messageId=str(uuid.uuid4().int), representative=BusinessMessagesRepresentative( representativeType=representative_type ), fallback='Hello, world!\nSent with Business Messages\n\nReply with \"Suggestion #1\" or \"Suggestion #2\"', richCard=BusinessMessagesRichCard( standaloneCard=BusinessMessagesStandaloneCard( cardContent=BusinessMessagesCardContent( title='Hello, world!', description='Sent with Business Messages.', suggestions=[ BusinessMessagesSuggestion( reply=BusinessMessagesSuggestedReply( text='Suggestion #1', postbackData='suggestion_1') ), BusinessMessagesSuggestion( reply=BusinessMessagesSuggestedReply( text='Suggestion #2', postbackData='suggestion_2') ) ], media=BusinessMessagesMedia( height=BusinessMessagesMedia.HeightValueValuesEnum.TALL, contentInfo=BusinessMessagesContentInfo( altText='Google logo', fileUrl='https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png', forceRefresh=False )) )))) # Create the message request create_request = BusinessmessagesConversationsMessagesCreateRequest( businessMessagesMessage=message, parent='conversations/' + conversation_id) # Send the message bm_client.BusinessmessagesV1.ConversationsMessagesService( client=client).Create(request=create_request)
리치 카드 캐러셀
사용자에게 선택할 수 있는 여러 옵션을 제시해야 하는 경우 리치 카드 캐러셀입니다. 캐러셀 문자열 여러 리치 포함 카드를 사용하면 사용자가 항목을 비교하고 각 항목에 반응할 수 있습니다. 각 단계마다 다릅니다
캐러셀에는 최소 2개에서 최대 10개의 리치 카드가 포함될 수 있습니다. 리치 캐러셀 내의 카드는 일반 리치 카드 요구사항을 준수해야 합니다. 지정할 수 있습니다.
예
다음 코드는 리치 카드 캐러셀을 전송합니다. 서식 지정 및
자세한 내용은
conversations.messages.create
드림
및
RichCard
cURL
# Copyright 2021 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # https://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # This code sends to the user a carousel with rich cards and a fallback text. # Read more: https://developers.google.com/business-communications/business-messages/guides/how-to/message/send?hl=en#rich-card-carousels # Replace the __CONVERSATION_ID__ with a conversation id that you can send messages to # Make sure a service account key file exists at ./service_account_key.json curl -X POST "https://businessmessages.googleapis.com/v1/conversations/__CONVERSATION_ID__/messages" \ -H "Content-Type: application/json" \ -H "User-Agent: curl/business-messages" \ -H "$(oauth2l header --json ./service_account_key.json businessmessages)" \ -d "{ 'messageId': '$(uuidgen)', 'representative': { 'avatarImage': 'https://developers.google.com/identity/images/g-logo.png', 'displayName': 'Chatbot', 'representativeType': 'BOT' }, 'fallback': 'Card #1\nThe description for card #1\n\nCard #2\nThe description for card #2\n\nReply with \"Card #1\" or \"Card #2\"', 'richCard': { 'carouselCard': { 'cardWidth': 'MEDIUM', 'cardContents': [ { 'title': 'Card #1', 'description': 'The description for card #1', 'suggestions': [ { 'reply': { 'text': 'Card #1', 'postbackData': 'card_1' } } ], 'media': { 'height': 'MEDIUM', 'contentInfo': { 'fileUrl': 'https://storage.googleapis.com/kitchen-sink-sample-images/cute-dog.jpg', 'forceRefresh': 'false', } } }, { 'title': 'Card #2', 'description': 'The description for card #2', 'suggestions': [ { 'reply': { 'text': 'Card #2', 'postbackData': 'card_2' } } ], 'media': { 'height': 'MEDIUM', 'contentInfo': { 'fileUrl': 'https://storage.googleapis.com/kitchen-sink-sample-images/elephant.jpg', 'forceRefresh': 'false', } } } ] } } }"
Node.js
/** * This code sends to the user a carousel with rich cards and a fallback text. * Read more: https://developers.google.com/business-communications/business-messages/guides/how-to/message/send?hl=en#rich-card-carousels * * This code is based on the https://github.com/google-business-communications/nodejs-businessmessages Node.js * Business Messages client library. */ /** * Edit the values below: */ const PATH_TO_SERVICE_ACCOUNT_KEY = './service_account_key.json'; const CONVERSATION_ID = 'EDIT_HERE'; const businessmessages = require('businessmessages'); const uuidv4 = require('uuid').v4; const {google} = require('googleapis'); // Initialize the Business Messages API const bmApi = new businessmessages.businessmessages_v1.Businessmessages({}); // Set the scope that we need for the Business Messages API const scopes = [ 'https://www.googleapis.com/auth/businessmessages', ]; // Set the private key to the service account file const privatekey = require(PATH_TO_SERVICE_ACCOUNT_KEY); /** * Posts a carousel card message to the Business Messages API. * * @param {string} conversationId The unique id for this user and agent. * @param {string} representativeType A value of BOT or HUMAN. */ async function sendMessage(conversationId, representativeType) { const authClient = await initCredentials(); if (authClient) { // Create the payload for sending carousel message // with two cards and a suggested reply for each card const apiParams = { auth: authClient, parent: 'conversations/' + conversationId, resource: { messageId: uuidv4(), representative: { representativeType: representativeType, }, fallback: 'Card #1\nThe description for card #1\n\nCard #2\nThe description for card #2\n\nReply with \"Card #1\" or \"Card #2\"', richCard: { carouselCard: { cardWidth: 'MEDIUM', cardContents: [ { title: 'Card #1', description: 'The description for card #1', suggestions: [ { reply: { text: 'Card #1', postbackData: 'card_1' } } ], media: { height: 'MEDIUM', contentInfo: { fileUrl: 'https://storage.googleapis.com/kitchen-sink-sample-images/cute-dog.jpg', forceRefresh: 'false', } } }, { title: 'Card #2', description: 'The description for card #2', suggestions: [ { reply: { text: 'Card #2', postbackData: 'card_2' } } ], media: { height: 'MEDIUM', contentInfo: { fileUrl: 'https://storage.googleapis.com/kitchen-sink-sample-images/elephant.jpg', forceRefresh: 'false', } } } ] } } }, }; // Call the message create function using the // Business Messages client library bmApi.conversations.messages.create(apiParams, {auth: authClient}, (err, response) => { console.log(err); console.log(response); }); } else { console.log('Authentication failure.'); } } /** * Initializes the Google credentials for calling the * Business Messages API. */ async function initCredentials() { // configure a JWT auth client const authClient = new google.auth.JWT( privatekey.client_email, null, privatekey.private_key, scopes, ); return new Promise(function(resolve, reject) { // authenticate request authClient.authorize(function(err, tokens) { if (err) { reject(false); } else { resolve(authClient); } }); }); } sendMessage(CONVERSATION_ID, 'BOT');
자바
import com.google.api.client.googleapis.services.AbstractGoogleClientRequest; import com.google.api.client.http.HttpBackOffUnsuccessfulResponseHandler; import com.google.api.client.http.HttpRequest; import com.google.api.client.googleapis.auth.oauth2.GoogleCredential; import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport; import com.google.api.client.http.HttpTransport; import com.google.api.client.json.jackson2.JacksonFactory; import com.google.api.client.util.ExponentialBackOff; import com.google.api.services.businessmessages.v1.Businessmessages; import com.google.api.services.businessmessages.v1.model.*; import com.google.communications.businessmessages.v1.MediaHeight; import java.io.FileInputStream; import java.util.Arrays; import java.util.UUID; class SendRichCardCarouselMessage { /** * Initializes credentials used by the Business Messages API. */ private static Businessmessages.Builder getBusinessMessagesBuilder() { Businessmessages.Builder builder = null; try { GoogleCredential credential = GoogleCredential .fromStream(new FileInputStream("PATH_TO_SERVICE_ACCOUNT_KEY")); credential = credential.createScoped(Arrays.asList( "https://www.googleapis.com/auth/businessmessages")); credential.refreshToken(); HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport(); JacksonFactory jsonFactory = JacksonFactory.getDefaultInstance(); // Create instance of the Business Messages API builder = new Businessmessages .Builder(httpTransport, jsonFactory, null) .setApplicationName("Sample Application"); // Set the API credentials and endpoint builder.setHttpRequestInitializer(credential); } catch (Exception e) { e.printStackTrace(); } return builder; } public static void main(String args[]) { try { String conversationId = "CONVERSATION_ID"; // Create client library reference Businessmessages.Builder builder = getBusinessMessagesBuilder(); // Create a rich card with two suggested replies BusinessMessagesMessage message = new BusinessMessagesMessage() .setMessageId(UUID.randomUUID().toString()) .setFallback("Hello, world!\nSent with Business Messages\n\nReply with \"Suggestion #1\" or \"Suggestion #2\"") .setRichCard(new BusinessMessagesRichCard() .setCarouselCard(new BusinessMessagesCarouselCard().setCardWidth("MEDIUM") .setCardContents(Arrays.asList( new BusinessMessagesCardContent() .setTitle("Card #1") .setDescription("The description for card #1") .setSuggestions(Arrays.asList(new BusinessMessagesSuggestion() .setReply(new BusinessMessagesSuggestedReply() .setText("Card #1").setPostbackData("card_1") ))) .setMedia(new BusinessMessagesMedia() .setHeight(MediaHeight.MEDIUM.toString()) .setContentInfo(new BusinessMessagesContentInfo() .setFileUrl("https://storage.googleapis.com/kitchen-sink-sample-images/cute-dog.jpg"))), new BusinessMessagesCardContent() .setTitle("Card #2") .setDescription("The description for card #2") .setSuggestions(Arrays.asList(new BusinessMessagesSuggestion() .setReply(new BusinessMessagesSuggestedReply() .setText("Card #2").setPostbackData("card_2") ))) .setMedia(new BusinessMessagesMedia() .setHeight(MediaHeight.MEDIUM.toString()) .setContentInfo(new BusinessMessagesContentInfo() .setFileUrl("https://storage.googleapis.com/kitchen-sink-sample-images/elephant.jpg"))) ) ))) .setRepresentative(new BusinessMessagesRepresentative() .setRepresentativeType("TYPE")); // Create message request Businessmessages.Conversations.Messages.Create messageRequest = builder.build().conversations().messages() .create("conversations/" + conversationId, message); // Setup retries with exponential backoff HttpRequest httpRequest = ((AbstractGoogleClientRequest) messageRequest).buildHttpRequest(); httpRequest.setUnsuccessfulResponseHandler(new HttpBackOffUnsuccessfulResponseHandler( new ExponentialBackOff())); // Execute request httpRequest.execute(); } catch (Exception e) { e.printStackTrace(); } } }
Python
"""This code sends to the user a carousel with rich cards and a fallback text. Read more: https://developers.google.com/business-communications/business-messages/guides/how-to/message/send?hl=en#rich-card-carousels This code is based on the https://github.com/google-business-communications/python-businessmessages Python Business Messages client library. """ import uuid from businessmessages import businessmessages_v1_client as bm_client from businessmessages.businessmessages_v1_messages import BusinessMessagesCardContent from businessmessages.businessmessages_v1_messages import BusinessMessagesCarouselCard from businessmessages.businessmessages_v1_messages import BusinessMessagesContentInfo from businessmessages.businessmessages_v1_messages import BusinessmessagesConversationsMessagesCreateRequest from businessmessages.businessmessages_v1_messages import BusinessMessagesMedia from businessmessages.businessmessages_v1_messages import BusinessMessagesMessage from businessmessages.businessmessages_v1_messages import BusinessMessagesRepresentative from businessmessages.businessmessages_v1_messages import BusinessMessagesRichCard from businessmessages.businessmessages_v1_messages import BusinessMessagesSuggestedReply from businessmessages.businessmessages_v1_messages import BusinessMessagesSuggestion from oauth2client.service_account import ServiceAccountCredentials # Edit the values below: path_to_service_account_key = './service_account_key.json' conversation_id = 'EDIT_HERE' credentials = ServiceAccountCredentials.from_json_keyfile_name( path_to_service_account_key, scopes=['https://www.googleapis.com/auth/businessmessages']) client = bm_client.BusinessmessagesV1(credentials=credentials) representative_type_as_string = 'BOT' if representative_type_as_string == 'BOT': representative_type = BusinessMessagesRepresentative.RepresentativeTypeValueValuesEnum.BOT else: representative_type = BusinessMessagesRepresentative.RepresentativeTypeValueValuesEnum.HUMAN # Create a carousel message with two cards and a suggested reply for each card # and fallback text message = BusinessMessagesMessage( messageId=str(uuid.uuid4().int), representative=BusinessMessagesRepresentative( representativeType=representative_type ), fallback='Card #1\nThe description for card #1\n\nCard #2\nThe description for card #2\n\nReply with \"Card #1\" or \"Card #2\"', richCard=BusinessMessagesRichCard( carouselCard=BusinessMessagesCarouselCard( cardWidth=BusinessMessagesCarouselCard.CardWidthValueValuesEnum.MEDIUM, cardContents=[ BusinessMessagesCardContent( title='Card #1', description='The description for card #1', suggestions=[ BusinessMessagesSuggestion( reply=BusinessMessagesSuggestedReply( text='Card #1', postbackData='card_1') ) ], media=BusinessMessagesMedia( height=BusinessMessagesMedia.HeightValueValuesEnum.MEDIUM, contentInfo=BusinessMessagesContentInfo( fileUrl='https://storage.googleapis.com/kitchen-sink-sample-images/cute-dog.jpg', forceRefresh=False))), BusinessMessagesCardContent( title='Card #2', description='The description for card #2', suggestions=[ BusinessMessagesSuggestion( reply=BusinessMessagesSuggestedReply( text='Card #2', postbackData='card_2') ) ], media=BusinessMessagesMedia( height=BusinessMessagesMedia.HeightValueValuesEnum.MEDIUM, contentInfo=BusinessMessagesContentInfo( fileUrl='https://storage.googleapis.com/kitchen-sink-sample-images/elephant.jpg', forceRefresh=False))) ]))) # Create the message request create_request = BusinessmessagesConversationsMessagesCreateRequest( businessMessagesMessage=message, parent='conversations/' + conversation_id) # Send the message bm_client.BusinessmessagesV1.ConversationsMessagesService( client=client).Create(request=create_request)