发送消息

收到用户的消息后,您可以发送回复以继续对话。您可以在用户收到上一条消息后的 30 天内向其发送消息。

代理通过发送和接收消息与用户通信。如需向用户发送消息,您的代理会向 Business Messages 发送消息请求。

如需发送消息,您需要向 Business Messages API 发送 HTTP POST 请求,其中包含

  • 唯一消息 ID
  • 对话 ID
  • 消息内容

当 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

测试后备文字

在发布代理之前,您可以发送将网址参数 forceFallback 设置为 true 的消息,以测试后备文本在对话中的显示方式。当您强制使用后备文字时,对话会忽略主消息内容(以下示例中的文字和“打开网址”建议),并改为显示后备文字。

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 支持 HUMANBOT 代表。

在任何类型的自动化功能撰写消息时,应指定 BOT 代表,无论自动化操作是自动回复(告知用户其在队列中的位置)、可动态访问用户详细信息的复杂自然语言理解代理,还是介于两者之间的任何功能。有 BOT 代表的消息会显示小图标 ,有助于设置用户对可能会参与的互动类型的预期。

仅在人工客服撰写消息时,才指定 HUMAN 代表。 在从 HUMAN 代表发送任何消息之前,请先发送 REPRESENTATIVE_JOINED 事件,让用户知道他们可以发送更自由格式或更复杂的消息。在您发送来自 HUMAN 代表的上一条消息后,请发送 REPRESENTATIVE_LEFT 事件以再次设定用户预期。

例如,如果用户开始与您的代理对话,而您向对方发送自动消息,告知他们应该会在两分钟内收到人工客服,该消息应由 BOT 代表发送。在人工客服加入之前,请发送 REPRESENTATIVE_JOINED 事件。来自人工客服的所有消息都应标记为来自 HUMAN 代表。当人工客服退出对话时,发送 REPRESENTATIVE_LEFT 事件。后续的所有消息都应由 BOT 代表发出,除非其他人工客服加入对话。

如需查看在 BOTHUMAN 代表之间转换的示例对话和代码,请参阅从聊天机器人转移到人工客服

无论代表是 BOT 还是 HUMAN,您都可以指定代表性显示名和头像。用户可以看到显示名称和头像。 头像图片必须为 1024x1024 像素,大小不得超过 50 KB,并且必须指定为可公开访问的网址。如果您未提供头像图片,则系统会将代理的徽标用作代表的头像。

文字

消息类型:文字

最简单的消息由文本组成。文本消息最适合无需视觉效果、复杂互动或响应即可交流信息。

示例

以下代码会发送一条简单的文本消息。如需了解参考信息,请参阅 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)

富文本

消息类型:富文本

containsRichText 设置为 true 的短信可能包含基本的 Markdown 格式。您可以添加超链接,也可以将文本设为粗体或斜体。下表显示了一些有效示例:

格式设置 字符 纯文本 渲染后的文本
粗体 ** **Some text** 部分文字
斜体 * *Some text* 部分文字
超链接 []() [Click here](https://www.example.com) 点击此处
换行符 \n Line one\nLine two 第 1 行
第 2 行

格式设置必须遵循一些额外的规则:

  • 所有链接都必须以 https://http:// 开头
  • 不同类型的格式设置可以嵌套,但不能重叠。
  • 您可以在消息的任何位置使用包含 \n 的换行符,但不会显示在消息末尾的换行符。
  • 为了正常显示任何预留字符(*\[]),您必须在这些字符前面添加反斜杠字符 (\)。

格式无效的消息无法发送,并显示有关无效 Markdown 的错误消息。下表根据上述规则显示了更多有效和无效示例:

纯文本 有效性 渲染后的文本
[Click here](www.example.com) 无效。链接不以 http://https:// 开头 无法呈现。
[**Click here**](https://www.example.com) 有效。允许嵌套。 点击此处
**This is [not** valid](https://www.example.com) 无效。不允许重叠格式。 无法呈现。
** Some bold text ** 无效。** 内不得有任何尾随空格。 无法呈现。
Citation below\* 有效。* 字符已转义。 引用低于*

示例

以下代码用于发送一条富文本消息。如需了解参考信息,请参阅 conversations.messages.create

cURL

# Copyright 2021 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at

#     https://www.apache.org/licenses/LICENSE-2.0

# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

# This code sends a rich text to the user with a fallback text.
# Read more: https://developers.google.com/business-communications/business-messages/guides/how-to/message/send?hl=en#rich_text

# Replace the __CONVERSATION_ID__ with a conversation id that you can send messages to
# Make sure a service account key file exists at ./service_account_key.json

curl -X POST "https://businessmessages.googleapis.com/v1/conversations/__CONVERSATION_ID__/messages" \
-H "Content-Type: application/json" \
-H "User-Agent: curl/business-messages" \
-H "$(oauth2l header --json ./service_account_key.json businessmessages)" \
-d "{
  'messageId': '$(uuidgen)',
  'fallback': 'Hello, check out this link https://www.google.com.',
  'text': 'Hello, here is some **bold text**, *italicized text*, and a [link](https://www.google.com).',
  'containsRichText': 'true',
  'representative': {
    'avatarImage': 'https://developers.google.com/identity/images/g-logo.png',
    'displayName': 'Chatbot',
    'representativeType': 'BOT'
  }
}"

Node.js


/**
 * This code sends a rich text to the user with a fallback text.
 * Read more: https://developers.google.com/business-communications/business-messages/guides/how-to/message/send?hl=en#rich_text
 *
 * This code is based on the https://github.com/google-business-communications/nodejs-businessmessages Node.js
 * Business Messages client library.
 */

/**
 * Edit the values below:
 */
const PATH_TO_SERVICE_ACCOUNT_KEY = './service_account_key.json';
const CONVERSATION_ID = 'EDIT_HERE';

const businessmessages = require('businessmessages');
const uuidv4 = require('uuid').v4;
const {google} = require('googleapis');

// Initialize the Business Messages API
const bmApi = new businessmessages.businessmessages_v1.Businessmessages({});

// Set the scope that we need for the Business Messages API
const scopes = [
  'https://www.googleapis.com/auth/businessmessages',
];

// Set the private key to the service account file
const privatekey = require(PATH_TO_SERVICE_ACCOUNT_KEY);

/**
 * Posts a rich text message using markdown to the Business Messages API.
 *
 * @param {string} conversationId The unique id for this user and agent.
 * @param {string} representativeType A value of BOT or HUMAN.
 */
async function sendMessage(conversationId, message, representativeType) {
  const authClient = await initCredentials();

  // Create the payload for sending a rich text message
  const apiParams = {
    auth: authClient,
    parent: 'conversations/' + conversationId,
    resource: {
      messageId: uuidv4(),
      representative: {
        representativeType: representativeType,
      },
      containsRichText: true, // Force this message to be processed as rich text
      text: 'Hello, here is some **bold text**, *italicized text*, and a [link](https://www.google.com).',
      fallback: 'Hello, check out this link https://www.google.com.'
    },
  };

  // Call the message create function using the
  // Business Messages client library
  bmApi.conversations.messages.create(apiParams,
    {auth: authClient}, (err, response) => {
    console.log(err);
    console.log(response);
  });
}

/**
 * Initializes the Google credentials for calling the
 * Business Messages API.
 */
 async function initCredentials() {
  // configure a JWT auth client
  const authClient = new google.auth.JWT(
    privatekey.client_email,
    null,
    privatekey.private_key,
    scopes,
  );

  return new Promise(function(resolve, reject) {
    // authenticate request
    authClient.authorize(function(err, tokens) {
      if (err) {
        reject(false);
      } else {
        resolve(authClient);
      }
    });
  });
}

sendMessage(CONVERSATION_ID, 'BOT');

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)

图像

消息类型(图片)

在消息中向用户发送图片。

您可以发送包含图片和图片缩略图网址的图片消息。

示例

以下代码会发送一张图片。如需了解格式设置和值选项,请参阅 conversations.messages.createImage

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)

建议的回复

建议的回复

建议的回复提供您的代理知道如何回应的响应,从而引导用户完成对话。

当用户点按建议的回复时,您的代理会收到一条包含回复的文本和回传数据的消息。

建议的回复最多包含 25 个字符,一条消息最多包含 13 条建议。

示例

以下代码会发送包含两条建议的回复的文本。如需了解格式设置和值选项,请参阅 conversations.messages.createSuggestedReply

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)

建议操作

建议操作

推荐操作利用用户设备的原生功能来引导用户完成对话。当用户点按建议的操作时,您的代理会收到一条包含该操作的文本和回传数据的消息。

建议的操作最多包含 25 个字符,一条消息最多包含 13 条建议。

如需了解格式设置和值选项,请参阅 conversations.messages.createSuggestedAction

打开网址操作

对于“打开网址”操作,代理会建议用户打开的网址。如果应用已注册为网址的默认处理程序,则改为打开该应用,并且操作的图标是应用的图标。打开网址操作仅支持使用 HTTP 和 HTTPS 协议的网址,不支持其他协议(例如 mailto)。

以下代码用于发送包含“打开网址”操作的文本。如需了解格式设置和值选项,请参阅 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)

身份验证请求建议

身份验证请求建议

Authentication 请求建议会提示用户登录与 OAuth 2.0 兼容的应用,传递身份验证代码以确认帐号数据,并启用自定义用户体验和详细的对话流程。请参阅使用 OAuth 进行身份验证

示例

以下代码会发送包含 Authentication 请求建议的文本。如需了解格式设置和值选项,请参阅 conversations.messages.createSuggestion

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)

人工客服请求建议

人工客服请求建议

借助实时代理请求建议,您可以引导用户在复杂互动期间或当自动化程序无法处理用户请求时与人工代表互动。

用户可以在对话过程中随时通过溢出菜单请求实时代理。此建议为代理提供了一种方法,能够根据对话的上下文以编程方式提出与人类代表的互动建议。您的代理应始终准备好响应人工客服请求的活动,即使它未发送人工客服请求建议也是如此。

当用户点按某个人工客服请求建议时,就会触发一个人工客服请求的事件

示例

以下代码会发送包含人工客服请求建议的文本。如需了解格式设置和值选项,请参阅 conversations.messages.createSuggestion

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)

复合信息卡

复合信息卡

当您需要发送大量相关信息、媒体或建议时,您应该发送一张复合信息卡。复合信息卡让您的代理可以在单条消息中发送多个单位的信息。

复合信息卡可以包含以下内容:

  • 媒体(JPG、JPEG 或 PNG,最大 5 MB)
  • 媒体缩略图(JPG、JPEG 或 PNG,最大 25 KB)
  • 标题(最多 200 个字符)
  • 说明(最多 2000 个字符)
  • 建议的回复建议的操作列表(最多 4 个)

复合信息卡可以包含所列的任何项或所有项,但卡必须至少包含媒体内容或标题才有效。复合信息卡最多可包含四项建议操作和建议回复。

您的代理可以在复合搜索卡轮播界面中同时发送多张复合搜索卡。

示例

以下代码会发送一张包含图片和建议的回复的复合搜索卡。如需了解格式设置和值选项,请参阅 conversations.messages.createRichCard

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)

复合信息卡轮播界面

复合信息卡轮播界面

如果您需要向用户展示多个选项,请使用复合信息卡轮播界面。轮播界面可将多张复合搜索卡串联起来,以便用户比较各项内容并分别作出回应。

轮播界面可以包含 2 到 10 个复合信息卡。轮播界面中的复合搜索卡必须符合内容和高度的常规复合搜索卡要求。

示例

以下代码会发送复合信息卡轮播界面。如需了解格式设置和值选项,请参阅 conversations.messages.createRichCard

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)