ส่งข้อความ

หลังจากที่คุณได้รับข้อความจากผู้ใช้ คุณจะส่งการตอบกลับเพื่อสนทนาต่อได้ คุณส่งข้อความถึงผู้ใช้ได้สูงสุด 30 วันหลังจากข้อความล่าสุดของผู้ใช้

ตัวแทนจะสื่อสารกับผู้ใช้ด้วยการส่งและรับข้อความ ตัวแทนจะส่งคำขอแชทไปยัง Business Messages เพื่อส่งข้อความให้ผู้ใช้

หากต้องการส่งข้อความ คุณต้องส่งคำขอ HTTP POST ไปยัง Business Messages API ที่มี

  • รหัสข้อความที่ไม่ซ้ำกัน
  • รหัสการสนทนา
  • เนื้อหาของข้อความ

เมื่อ Business Messages API ส่งข้อความของคุณไปยังผู้ใช้ จะมีการแสดงผล 200 OK หากข้อความมีค่าที่จำเป็นขาดหายไป API จะแสดงข้อผิดพลาด 400 หากข้อความใช้ข้อมูลเข้าสู่ระบบที่ไม่ถูกต้อง API จะแสดงข้อผิดพลาด 401

ใช้หน้าบันทึกของคอนโซลของนักพัฒนาซอฟต์แวร์ Business Communications เพื่อแก้ไขปัญหาการส่งข้อความ

กลยุทธ์สำรอง

หากอุปกรณ์ของผู้ใช้ไม่รองรับข้อความที่คุณพยายามส่ง เช่น หากผู้ใช้ไม่รองรับการตอบกลับที่แนะนำ API จะแสดงข้อผิดพลาด 400 (FAILED PRECONDITION) แต่คุณสามารถแก้ไขประเภทข้อความที่ไม่รองรับได้โดยระบุข้อความ fallback สำหรับแต่ละข้อความที่คุณส่ง หากคุณระบุข้อความ fallback แล้ว API จะแสดงผลการตอบกลับ 200 OK แม้ว่าอุปกรณ์ของผู้ใช้จะไม่รองรับประเภทข้อความดังกล่าวก็ตาม

หากผู้ใช้ได้รับข้อความว่าอุปกรณ์ไม่รองรับแต่มีข้อความ fallback อยู่ อุปกรณ์ของผู้ใช้จะแสดงข้อความ fallback แทน วิธีนี้จะช่วยให้คุณสนทนาต่อได้ในลักษณะที่เชิงรุกโดยไม่รบกวนการสนทนา หรือใช้เวลาเพิ่มเติมในการประมวลผลข้อผิดพลาด 400 (FAILED PRECONDITION) และระบุข้อความสำรอง

ข้อความ fallback สำหรับข้อความที่ระบุควรตรงตามฟังก์ชันของข้อความดังกล่าว ตัวอย่างเช่น

  • สำหรับข้อความที่มีการตอบกลับหรือการดำเนินการที่แนะนำ ให้ใส่เนื้อหาในข้อความ fallback และใส่คำแนะนำเกี่ยวกับตัวเลือกที่ผู้ใช้มีเพื่อดำเนินการสนทนาต่อ
  • สำหรับการ์ดริชมีเดียหรือภาพสไลด์ ให้ใส่ชื่อและคำอธิบายในข้อความ fallback และมีลิงก์ไปยังรูปภาพหรือเว็บไซต์

หากต้องการแทรกตัวแบ่งบรรทัดในข้อความ fallback ให้ใช้ \n หรือ \r\n

ทดสอบข้อความสำรอง

ก่อนการเปิดตัว Agent คุณสามารถทดสอบว่าข้อความสำรองจะปรากฏในการสนทนาอย่างไร โดยการส่งข้อความที่มีการตั้งค่าพารามิเตอร์ของ URL forceFallback เป็น true เมื่อคุณบังคับใช้ข้อความสำรอง การสนทนาจะไม่สนใจเนื้อหาข้อความหลัก (ข้อความและคำแนะนำของ 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');

Java

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 เพื่อแจ้งให้ผู้ใช้ทราบว่าสามารถส่งข้อความรูปแบบอิสระหรือข้อความที่ซับซ้อนมากขึ้นได้ หลังจากที่คุณส่งข้อความสุดท้ายจากตัวแทนของ HUMAN ให้ส่งเหตุการณ์ REPRESENTATIVE_LEFT เพื่อกำหนดความคาดหวังของผู้ใช้อีกครั้ง

เช่น หากผู้ใช้เริ่มการสนทนากับตัวแทนของคุณ และคุณส่งข้อความอัตโนมัติว่าผู้ใช้ควรจะทราบว่าจะมีตัวแทนแบบเรียลไทม์ภายใน 2 นาที ข้อความดังกล่าวควรส่งจากตัวแทนของ BOT ก่อนที่ตัวแทนแบบเรียลไทม์จะเข้าร่วม ให้ส่งกิจกรรม REPRESENTATIVE_JOINED ข้อความทั้งหมดจากตัวแทนแบบเรียลไทม์ควรติดป้ายกำกับว่ามาจากตัวแทนของ HUMAN เมื่อตัวแทนแบบเรียลไทม์ออกจากการสนทนา ให้ส่งเหตุการณ์ REPRESENTATIVE_LEFT ข้อความที่ตามมาทั้งหมดควรมาจากตัวแทนของ BOT เว้นแต่ตัวแทนแบบเรียลไทม์รายอื่นจะเข้าร่วมการสนทนา

ดู Handoff จากบ็อตเป็น Agent แบบสด สำหรับตัวอย่างการสนทนาและโค้ดสำหรับการเปลี่ยนระหว่างตัวแทน BOT กับ HUMAN

ไม่ว่าตัวแทนจะเป็น BOT หรือ HUMAN คุณก็ระบุชื่อที่แสดงและรูปโปรไฟล์ของตัวแทนได้ ผู้ใช้จะเห็นทั้งชื่อที่แสดงและรูปโปรไฟล์ รูปโปรไฟล์ต้องมีขนาด 1024x1024 พิกเซลและมีขนาดไม่เกิน 50 KB และต้องระบุเป็น URL ที่เผยแพร่ต่อสาธารณะ หากคุณไม่ได้ใส่รูปโปรไฟล์ ระบบจะใช้โลโก้ของตัวแทน เป็นรูปโปรไฟล์ของตัวแทน

ข้อความ

ข้อความประเภทข้อความ

โดยข้อความที่ง่ายที่สุดจะประกอบด้วยข้อความตัวอักษร SMS เหมาะที่สุดในการสื่อสารข้อมูลโดยไม่ต้องใช้ภาพ การโต้ตอบที่ซับซ้อน หรือการตอบสนอง

ตัวอย่าง

โค้ดต่อไปนี้จะส่ง SMS ทั่วไป โปรดดูข้อมูลอ้างอิงที่ 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');

Java

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)

Rich Text

ประเภทข้อความแบบ Rich Text

SMS ที่มีการตั้งค่า containsRichText เป็น true อาจมีการจัดรูปแบบมาร์กดาวน์พื้นฐาน คุณสามารถใส่ไฮเปอร์ลิงก์ หรือทำให้ข้อความเป็นตัวหนาหรือตัวเอียงได้ ตารางแสดงตัวอย่างที่ถูกต้อง

การจัดรูปแบบ อักขระ ข้อความธรรมดา ข้อความที่แสดงผลแล้ว
ตัวหนา ** **Some text** ข้อความบางส่วน
ตัวเอียง * *Some text* ข้อความบางส่วน
ไฮเปอร์ลิงก์ []() [Click here](https://www.example.com) คลิกที่นี่
ขึ้นบรรทัดใหม่ \n Line one\nLine two บรรทัดที่ 1
บรรทัดที่ 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\* ถูกต้อง อักขระ * ถูกตัดออก การอ้างอิงด้านล่าง*

ตัวอย่าง

โค้ดต่อไปนี้จะส่งข้อความ Rich Text โปรดดูข้อมูลอ้างอิงที่ 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');

Java

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');

Java

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)

คำตอบที่แนะนำ

คำตอบที่แนะนำ

การตอบกลับที่แนะนำจะแนะนำผู้ใช้ในการสนทนาโดยตอบกลับว่าตัวแทนของคุณรู้ว่าควรตอบสนองอย่างไร

เมื่อผู้ใช้แตะการตอบกลับที่แนะนำ ตัวแทนของคุณจะได้รับข้อความที่มีข้อความตอบกลับและข้อมูลระบบรายงานผล Conversion

การตอบกลับที่แนะนำมีอักขระได้สูงสุด 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');

Java

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)

การดำเนินการที่แนะนำ

การดำเนินการที่แนะนำ

การดำเนินการที่แนะนำจะแนะนำผู้ใช้ในการสนทนาโดยใช้ประโยชน์จากฟังก์ชันดั้งเดิมของอุปกรณ์ เมื่อผู้ใช้แตะการดำเนินการที่แนะนำ ตัวแทนของคุณจะได้รับข้อความซึ่งประกอบด้วยข้อความของการดำเนินการและข้อมูลระบบรายงานผล Conversion

การดำเนินการที่แนะนำมีอักขระได้สูงสุด 25 ตัว และข้อความจะมีคำแนะนำได้สูงสุด 13 ตัว

ดูตัวเลือกการจัดรูปแบบและค่าได้ที่ conversations.messages.create และ SuggestedAction

การดำเนินการ OpenURL

เมื่อใช้การทำงานของ Open URL ตัวแทนจะแนะนำ URL ให้ผู้ใช้เปิด หากมีการลงทะเบียนแอปเป็นตัวแฮนเดิลเริ่มต้นสำหรับ URL แอปจะเปิดขึ้นแทน และไอคอนสำหรับการดำเนินการจะเป็นไอคอนของแอป การดำเนินการเปิด URL รองรับเฉพาะ URL ที่มีโปรโตคอล HTTP และ HTTPS แต่ไม่รองรับโปรโตคอลอื่นๆ (เช่น 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');

Java

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');

Java

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');

Java

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)

คำแนะนำสำหรับคำขอตัวแทนแบบเรียลไทม์

คำแนะนำสำหรับคำขอตัวแทนแบบเรียลไทม์

คำแนะนำสำหรับคำขอของตัวแทนแบบเรียลไทม์ช่วยให้คุณแนะนำผู้ใช้ให้โต้ตอบกับตัวแทนที่เป็นมนุษย์ในระหว่างการโต้ตอบที่ซับซ้อนหรือเมื่อระบบอัตโนมัติจัดการคำขอของผู้ใช้ไม่ได้

ผู้ใช้สามารถขอ Agent แบบสดได้ทุกเมื่อในการสนทนาจากเมนูรายการเพิ่มเติม คำแนะนำนี้ช่วยให้ตัวแทนมีวิธีแนะนำวิธีโต้ตอบกับตัวแทนที่เป็นมนุษย์ทางโปรแกรม โดยอิงตามบริบทของการสนทนา ตัวแทนของคุณควรพร้อมตอบกลับกิจกรรมที่ตัวแทนแบบเรียลไทม์ขอเสมอ แม้ว่าตัวแทนจะไม่ได้ส่งคำแนะนำคำขอของตัวแทนแบบเรียลไทม์ก็ตาม

เมื่อผู้ใช้แตะคำแนะนำคำขอของตัวแทนแบบเรียลไทม์ ระบบจะทริกเกอร์เหตุการณ์ที่ตัวแทนแบบเรียลไทม์ขอ

ตัวอย่าง

โค้ดต่อไปนี้จะส่งข้อความพร้อมคำแนะนำคำขอจากตัวแทนแบบเรียลไทม์ ดูตัวเลือกการจัดรูปแบบและค่าได้ที่ 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);

Java

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)

การ์ดริชมีเดีย

Rich Card

เมื่อคุณต้องส่งข้อมูล สื่อ หรือคำแนะนำที่เกี่ยวข้องเป็นกลุ่ม คุณควรส่งการ์ดริชมีเดีย Rich Card จะช่วยให้ตัวแทนของคุณส่งข้อมูลหลายหน่วยได้ในข้อความเดียว

Rich Card อาจมีรายการต่อไปนี้

การ์ดริชมีเดียอาจมีรายการบางส่วนหรือทั้งหมดก็ได้ แต่การ์ดต้องมีสื่อหรือชื่อเป็นอย่างน้อยจึงจะใช้งานได้ การ์ดริชมีเดียจะมีการดำเนินการที่แนะนำและการตอบกลับที่แนะนำได้สูงสุด 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');

Java

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)

ภาพสไลด์ Rich Card

ภาพสไลด์ Rich Card

เมื่อคุณต้องการนำเสนอตัวเลือกหลายรายการให้แก่ผู้ใช้ ให้ใช้ภาพสไลด์การ์ดที่สมบูรณ์ ภาพสไลด์จะเรียงการ์ดสื่อสมบูรณ์หลายใบเข้าด้วยกัน ช่วยให้ผู้ใช้เปรียบเทียบรายการและแสดงความรู้สึกต่อการ์ดแต่ละรายการได้

ภาพสไลด์อาจมีการ์ดริชมีเดียอย่างน้อย 2 รายการและได้สูงสุด 10 รายการ การ์ดริชมีเดียภายในภาพสไลด์ต้องเป็นไปตามข้อกำหนดทั่วไปของการ์ดริชมีเดียสำหรับเนื้อหาและความสูง

ตัวอย่าง

โค้ดต่อไปนี้จะส่งภาพสไลด์ Rich Card สำหรับตัวเลือกการจัดรูปแบบและค่า โปรดดู 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');

Java

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)