注册成为合作伙伴后,您可以为自己管理的品牌创建 Business Messages 代理,从而为这些品牌启用对话功能。
代理是一个会与用户互动的对话实体。您可以为所管理的每个品牌创建一个代理。您可以使用 Business Communications API 创建和管理代理,并可使用 Business Messages API 控制代理的消息功能。
代理涵盖品牌的业务职能(例如在线支持)和实体营业地点(如有)。每条消息都包含用户从中发起对话的上下文。您的消息传输基础架构可以检测用户是否查看了特定营业地点或寻求一般支持,并且可以将消息传输到正确的目的地。
例如,如果您管理 Growing Tree Bank 品牌(它有一个网站和两个营业地点),则可以创建一个“Growing Tree Bank”代理。用户可以通过常规搜索或基于地点的搜索发现该代理,用户找到该代理的情况信息会与每条消息一起传递到您的 webhook。您可以根据这些情况信息将消息传输给某个营业地点的员工或网站支持团队,后者会创建响应并继续与用户对话。
预期
在创建代理之前,请了解代理对 Business Messages 的预期。
- 代理应遵循 Business Messages 的对话设计中所述的设计指南。
在自动化程序无法完成请求或用户请求对话人工代表时,代理应安排人工代表解答问题。
代理应保持客户满意度评分 (CSAT) 至少为 80%,且商家回复率 (MRR) 至少为 95%,如指标中所述。
创建代理
若要创建代理,您需要收集并提交品牌的相关信息,以及您希望以何种方式将代理显示给用户。
如果您管理多个品牌,请重复上述步骤,为每个品牌创建一个代理。
前提条件
在为您管理的品牌创建代理之前,您需要收集一些信息:
开发环境
您的开发环境的相关信息。
启用了 Business Communications API 的 GCP 项目
如需启用该 API,请参阅在 Business Messages 中注册。
开发机器上的 GCP 项目的服务账号密钥的路径
品牌详细信息
代理所代表的品牌的相关信息。
- 品牌名称
- 品牌网站
- 网站上的联系方式(如
OPTION
中所定义) - 面向消费者的电话号码
- 启用了呼叫转移功能的电话号码
代理外观和政策
有关代理以何种方式向用户显示及其运营方式的信息。
- 代理名称,您希望在与用户的对话中显示该名称
- 隐私权政策(以“https://”开头的可公开访问的网址)
(推荐)代理徽标(1024x1024 像素),以可公开访问的网址形式提供
在对话中,徽标显示为直径为 1024 像素的圆形。确保您的徽标显示为圆形时效果良好。
(可选)自定义代理 ID,用于标识 webhook 收到的消息中的品牌
代理互动
有关代理如何与用户互动的信息。
您的代理在一般情况下使用的语言区域,由两个字符的 ISO 639-1 语言代码指定
代理欢迎辞
代理问候用户时说什么?
代理对话开场白
对话条状标签形式的一系列建议(如 SuggestedReply 中所定义),供用户与代理互动
- 在条状标签中向用户显示的文本
- 回传数据,在用户点按条状标签时,在消息载荷中发回给 webhook 的字符串
自动和实时聊天时间
每日开始时间,以
TimeOfDay
对象的形式表示例如,上午 8:15 这样表示
{ "hours": 8, "minutes": 15, }
每日结束时间,以
TimeOfDay
对象的形式表示例如,晚上 7:30 这样表示
{ "hours": 19, "minutes": 30, }
开始日,即代理可与客户聊天的一周的第一天(如
DayOfWeek
中所定义)结束日,即代理可与客户聊天的一周的最后一天(如
DayOfWeek
中所定义)代理使用的时区(如 IANA 时区数据库中所定义,例如“America/Los_Angeles”)
代理入口点
有关用户可以在何处发起与代理的对话的信息。
允许的代理入口点,用户可以在其中发起与代理的对话(
NON_LOCAL
和/或LOCATION
)
有关 NON_LOCAL
入口点的信息(不适用于 Google Ads 入口点)。
允许的区域(采用 CLDR 区域代码),用以限制对
NON_LOCAL
入口点的区域性访问。无论位于哪个区域,代理都只能关联一个电话号码。如果您需要基于区域使用不同的电话号码,则必须为每个区域创建不同的代理。
如需在所有可用区域中启用
NON_LOCAL
入口点,请使用001
作为世界区域代码。
安装并测试 oauth2l
此网站文档中的所有 curl 请求都使用 oauth2l 进行身份验证。如果您想使用命令行与 Business Communications 和 Business Messages API 建立连接,请安装 oauth2l。
如需通过 Python 3 安装 oauth2l,请按以下步骤操作:
下载 oauth2l。
将目录更改为“./oauth2l/python”。
使用以下命令安装 oauth2l。
sudo python setup.sh build && sudo python setup.py install
测试 oauth2l 是否可以生成授权令牌。
oauth2l header --json resources/bm-agent-service-account-credentials.json businesscommunications
验证输出是否会创建以下形式的授权令牌:
Authorization: Bearer AUTHORIZATION_BEARER_TOKEN
您还可以通过其他方式为不同的操作系统安装 oauth2l。无论您使用哪种安装方法,都请确保可以基于服务账号 JSON 凭据生成授权令牌,然后再继续。
创建代理
收集完信息后,您就可以创建代理了。
创建代理所代表的品牌。如果该品牌已存在,请获取该品牌的
name
并跳至下一步。在终端运行以下命令:
cURL
# This code creates a brand. # Read more: https://developers.google.com/business-communications/business-messages/reference/business-communications/rest/v1/brands/create # Make sure a service account key file exists at ./service_account_key.json curl -X POST "https://businesscommunications.googleapis.com/v1/brands" \ -H "Content-Type: application/json" \ -H "User-Agent: curl/business-communications" \ -H "$(oauth2l header --json ./service_account_key.json businesscommunications)" \ -d '{ "displayName": "My first brand curl" }'
Node.js
/** * This code snippet creates a brand. * Read more: https://developers.google.com/business-communications/business-messages/reference/business-communications/rest/v1/brands/create * * This code is based on the https://github.com/google-business-communications/nodejs-businesscommunications Node.js * Business Communications client library. */ /** * Edit the values below: */ const PATH_TO_SERVICE_ACCOUNT_KEY = './service_account_key.json'; const businesscommunications = require('businesscommunications'); const {google} = require('googleapis'); // Initialize the Business Communications API const bcApi = new businesscommunications.businesscommunications_v1.Businesscommunications({}); // Set the scope that we need for the Business Communications API const scopes = [ 'https://www.googleapis.com/auth/businesscommunications', ]; // Set the private key to the service account file const privatekey = require(PATH_TO_SERVICE_ACCOUNT_KEY); async function main() { const authClient = await initCredentials(); if (authClient) { // Setup the parameters for the API call const apiParams = { auth: authClient, resource: { displayName: 'My first brand', }, }; bcApi.brands.create(apiParams, {}, (err, response) => { if (err !== undefined && err !== null) { console.dir(err); } else { // Brand created console.log(response.data); } }); } else { console.log('Authentication failure.'); } } /** * Initializes the Google credentials for calling the * Business Communcations 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('Failed to connect'); } else { resolve(authClient); } }); }) } main();
Java
此代码基于 Java Business Communications 客户端库。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.services.businesscommunications.v1.BusinessCommunications; import com.google.api.services.businesscommunications.v1.model.Brand; import java.io.FileInputStream; import java.util.Arrays; import java.util.UUID; class Main { /** * Initializes credentials used by the Business Communications API. */ private static BusinessCommunications.Builder getBusinessCommunicationsBuilder() { BusinessCommunications.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/businesscommunications")); credential.refreshToken(); HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport(); JacksonFactory jsonFactory = JacksonFactory.getDefaultInstance(); // Create instance of the Business Communications API builder = new BusinessCommunications .Builder(httpTransport, jsonFactory, null) .setApplicationName(credential.getServiceAccountProjectId()); // Set the API credentials and endpoint builder.setHttpRequestInitializer(credential); } catch (Exception e) { e.printStackTrace(); } return builder; } public static void main(String args[]) { try { // Create client library reference BusinessCommunications.Builder builder = getBusinessCommunicationsBuilder(); // Create a request to create a new brand BusinessCommunications.Brands.Create request = builder .build().brands().create(new Brand().setDisplayName("BRAND_NAME")); Brand brand = request.execute(); // Print newly created brand object System.out.println(brand.toPrettyString()); } catch (Exception e) { e.printStackTrace(); } } }
Python
"""This code creates a brand. Read more: https://developers.google.com/business-communications/business-messages/reference/business-communications/rest/v1/brands/create This code is based on the https://github.com/google-business-communications/python-businessmessages Python Business Messages client library. """ from oauth2client.service_account import ServiceAccountCredentials from businesscommunications.businesscommunications_v1_client import BusinesscommunicationsV1 from businesscommunications.businesscommunications_v1_messages import ( Brand) # Edit the values below: SCOPES = ['https://www.googleapis.com/auth/businesscommunications'] SERVICE_ACCOUNT_FILE = './service_account_key.json' credentials = ServiceAccountCredentials.from_json_keyfile_name( SERVICE_ACCOUNT_FILE, scopes=SCOPES) client = BusinesscommunicationsV1(credentials=credentials) brands_service = BusinesscommunicationsV1.BrandsService(client) brand = brands_service.Create(Brand(displayName='My first brand')) print(brand)
存储 API 返回的
name
值。您需要使用它来进行更新或创建代理。如需更新或查询品牌,请参阅
brands
。创建代理。将 BRAND_ID 替换为相应品牌
name
值中紧随“brands/”后面的部分。例如,如果name
为“brands/12345”,那么品牌 ID 为“12345”。在终端运行以下命令:
cURL
# This code creates a Business Messages agent. # Read more: https://developers.google.com/business-communications/business-messages/guides/how-to/agents?method=api#create_the_agent # Replace the __BRAND_ID__ with a brand id that you can create agents for # Make sure a service account key file exists at ./service_account_key.json curl -X POST "https://businesscommunications.googleapis.com/v1/brands/__BRAND_ID__/agents" \ -H "Content-Type: application/json" \ -H "User-Agent: curl/business-communications" \ -H "$(oauth2l header --json ./service_account_key.json businesscommunications)" \ -d '{ "displayName": "My first agent", "businessMessagesAgent": { "logoUrl": "https://developers.google.com/identity/images/g-logo.png", "entryPointConfigs": [ { "allowedEntryPoint": "NON_LOCAL" } ], "customAgentId": "'$(uuidgen)'", "nonLocalConfig": { "regionCodes": [ "US", "CA" ], "contactOption": { "url": "https://www.your-company-website.com", "options": [ "EMAIL", "PHONE" ] }, "enabledDomains": [ "your-company-website.com" ], "phoneNumber": { "number": "+10000000000" }, "callDeflectionPhoneNumbers": [ { "number": "+10000000000" }, { "number": "+10000000000" } ] }, "conversationalSettings": { "en": { "welcomeMessage": { "text": "This is a sample welcome message" }, "privacyPolicy": { "url": "https://www.your-company-website.com/privacy" }, "conversationStarters": [ { "suggestion": { "reply": { "text": "Option 1", "postbackData": "postback_option_1" } } } ] } }, "defaultLocale": "en", "primaryAgentInteraction": { "interactionType": "HUMAN", "humanRepresentative": { "humanMessagingAvailability": { "hours": [ { "startTime": { "hours": 8, "minutes": 30 }, "endTime": { "hours": 20, "minutes": 0 }, "timeZone": "America/Los_Angeles", "startDay": "MONDAY", "endDay": "SATURDAY" } ] } } } } }'
Node.js
/** * This code snippet creates a Business Messages agent. * Read more: https://developers.google.com/business-communications/business-messages/guides/how-to/agents?method=api#create_the_agent * * This code is based on the https://github.com/google-business-communications/nodejs-businesscommunications Node.js * Business Communications client library. */ /** * Edit the values below: */ const BRAND_ID = 'EDIT_HERE'; const PATH_TO_SERVICE_ACCOUNT_KEY = './service_account_key.json'; const businesscommunications = require('businesscommunications'); const {google} = require('googleapis'); const uuidv4 = require('uuid').v4; // Initialize the Business Communications API const bcApi = new businesscommunications.businesscommunications_v1.Businesscommunications({}); // Set the scope that we need for the Business Communications API const scopes = [ 'https://www.googleapis.com/auth/businesscommunications', ]; // Set the private key to the service account file const privatekey = require(PATH_TO_SERVICE_ACCOUNT_KEY); async function main() { const authClient = await initCredentials(); const brandName = 'brands/' + BRAND_ID; if (authClient) { const agentObject = { displayName: 'My first agent', businessMessagesAgent: { customAgentId: uuidv4(), // Optional logoUrl: 'https://developers.google.com/identity/images/g-logo.png', entryPointConfigs: [ { allowedEntryPoint: 'NON_LOCAL', } ], nonLocalConfig: { // Configuration options for launching on non-local entry points // List of phone numbers for call deflection, values must be globally unique callDeflectionPhoneNumbers: [ { number: '+10000000000' }, { number: '+10000000001' }, ], // Contact information for the agent that displays with the messaging button contactOption: { options: [ 'EMAIL', 'PHONE' ], url: 'https://www.your-company-website.com', }, // Domains enabled for messaging within Search, values must be globally unique enabledDomains: [ 'your-company-website.com' ], // Agent's phone number. Overrides the `phone` field // for conversations started from non-local entry points phoneNumber: { number: '+10000000000' }, // List of CLDR region codes for countries where the agent is allowed to launch `NON_LOCAL` entry points regionCodes: [ 'US', 'CA' ] }, // Must match a conversational setting locale defaultLocale: 'en', conversationalSettings: { en: { privacyPolicy: { url: 'https://www.your-company-website.com/privacy' }, welcomeMessage: { text: 'This is a sample welcome message' }, conversationStarters: [ { suggestion: { reply: { text: 'Option 1', postbackData: 'postback_option_1', }, }, }, ], }, }, primaryAgentInteraction: { interactionType: 'HUMAN', humanRepresentative: { humanMessagingAvailability: { hours: [ { startTime: { hours: 8, minutes: 30 }, startDay: 'MONDAY', endDay: 'SATURDAY', endTime: { hours: 20, minutes: 0 }, timeZone: 'America/Los_Angeles', }, ], }, }, }, }, }; // Setup the parameters for the API call const apiParams = { auth: authClient, parent: brandName, resource: agentObject }; bcApi.brands.agents.create(apiParams, {}, (err, response) => { if (err !== undefined && err !== null) { console.dir(err); } else { // Agent created console.log(response.data); } }); } 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); } }); }); } main();
Java
此代码基于 Java Business Communications 客户端库。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.services.businesscommunications.v1.BusinessCommunications; import com.google.api.services.businesscommunications.v1.model.Brand; import com.google.common.collect.ImmutableMap; import java.io.FileInputStream; import java.util.Arrays; import java.util.UUID; class Main { /** * Initializes credentials used by the Business Communications API. */ private static BusinessCommunications.Builder getBusinessCommunicationsBuilder() { BusinessCommunications.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/businesscommunications")); credential.refreshToken(); HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport(); JacksonFactory jsonFactory = JacksonFactory.getDefaultInstance(); // Create instance of the Business Communications API builder = new BusinessCommunications .Builder(httpTransport, jsonFactory, null) .setApplicationName(credential.getServiceAccountProjectId()); // Set the API credentials and endpoint builder.setHttpRequestInitializer(credential); } catch (Exception e) { e.printStackTrace(); } return builder; } public static void main(String args[]) { try { // Create client library reference BusinessCommunications.Builder builder = getBusinessCommunicationsBuilder(); String brandName = "BRAND_ID"; BusinessCommunications.Brands.Agents.Create request = builder .build().brands().agents().create(brandName, new Agent() .setDisplayName("AGENT_NAME") .setBusinessMessagesAgent(new BusinessMessagesAgent() .setCustomAgentId("CUSTOM_ID") // Optional .setLogoUrl("LOGO_URL") .setEntryPointConfigs(Arrays.asList( new BusinessMessagesEntryPointConfig() .setAllowedEntryPoint( "ENTRY_POINT_1"), new BusinessMessagesEntryPointConfig() .setAllowedEntryPoint( "ENTRY_POINT_2") )) // Configuration options for launching on non-local entry points .setNonLocalConfig(new NonLocalConfig() // List of phone numbers for call deflection, values must be globally unique .setCallDeflectionPhoneNumbers(Arrays.asList(new Phone().setNumber("DEFLECTION_PHONE_NUMBER_1"), new Phone().setNumber("DEFLECTION_PHONE_NUMBER_2"))) // Contact information for the agent that displays with the messaging button .setContactOption(new ContactOption().setOptions(Arrays.asList( "CONTACT_OPTION_1", "CONTACT_OPTION_2") ).setUrl("WEBSITE_URL")) // Domains enabled for messaging within Search, values must be globally unique .setEnabledDomains(Arrays.asList("ENABLED_DOMAIN_1", "ENABLED_DOMAIN_2")) // Agent's phone number. Overrides the `phone` field for // conversations started from non-local entry points .setPhoneNumber(new Phone().setNumber("CONTACT_PHONE_NUMBER")) // List of regions where this agent will be available .setRegionCodes(Arrays.asList("REGION_CODE"))) .setDefaultLocale("LOCALE") // Create a map between the language code and the initial conversation settings .setConversationalSettings(ImmutableMap.of("LOCALE", new ConversationalSetting() .setPrivacyPolicy(new PrivacyPolicy().setUrl("PRIVACY_POLICY_URL")) .setWelcomeMessage(new WelcomeMessage().setText("WELCOME_MESSAGE")) .setConversationStarters(Arrays.asList( new ConversationStarters().setSuggestion(new Suggestion() .setReply(new SuggestedReply().setText("SUGGESTION_TEXT").setPostbackData("SUGGESTION_POSTBACK_DATA"))) )))) .setPrimaryAgentInteraction(new SupportedAgentInteraction() .setInteractionType(InteractionType.HUMAN.toString()) .setHumanRepresentative(new HumanRepresentative() .setHumanMessagingAvailability(new MessagingAvailability() // Create a list of available hours .setHours(Arrays.asList(new Hours() .setStartTime(new TimeOfDay().setHours(START_TIME_HOURS).setMinutes(START_TIME_MINUTES)) .setStartDay("BEGINNING_DAY_OF_WEEK") .setEndDay("END_DAY_OF_WEEK") .setEndTime(new TimeOfDay().setHours(END_TIME_HOURS).setMinutes(END_TIME_MINUTES)) .setTimeZone("TIME_ZONE")))))) )); Agent agent = request.execute(); System.out.println(agent.toPrettyString()); } catch (Exception e) { e.printStackTrace(); } } }
Python
"""This code creates a Business Messages agent. Read more: https://developers.google.com/business-communications/business-messages/guides/how-to/agents?method=api#create_the_agent This code is based on the https://github.com/google-business-communications/python-businessmessages Python Business Messages client library. """ from oauth2client.service_account import ServiceAccountCredentials from businesscommunications.businesscommunications_v1_client import BusinesscommunicationsV1 from businesscommunications.businesscommunications_v1_messages import ( Agent, BusinesscommunicationsBrandsAgentsCreateRequest, BusinessMessagesAgent, BusinessMessagesEntryPointConfig, ContactOption, ConversationalSetting, ConversationStarters, Hours, HumanRepresentative, MessagingAvailability, NonLocalConfig, Phone, PrivacyPolicy, Suggestion, SuggestedReply, SupportedAgentInteraction, TimeOfDay, WelcomeMessage ) # Edit the values below: BRAND_ID = 'EDIT_HERE' SCOPES = ['https://www.googleapis.com/auth/businesscommunications'] SERVICE_ACCOUNT_FILE = './service_account_key.json' credentials = ServiceAccountCredentials.from_json_keyfile_name( SERVICE_ACCOUNT_FILE, scopes=SCOPES) client = BusinesscommunicationsV1(credentials=credentials) agents_service = BusinesscommunicationsV1.BrandsAgentsService(client) brand_name = 'brands/ '+ BRAND_ID agent = Agent( displayName='My first agent', businessMessagesAgent=BusinessMessagesAgent( customAgentId='CUSTOM_ID', # Optional logoUrl='https://developers.google.com/identity/images/g-logo.png', entryPointConfigs=[BusinessMessagesEntryPointConfig( allowedEntryPoint=BusinessMessagesEntryPointConfig.AllowedEntryPointValueValuesEnum.LOCATION ), BusinessMessagesEntryPointConfig( allowedEntryPoint=BusinessMessagesEntryPointConfig.AllowedEntryPointValueValuesEnum.NON_LOCAL )], nonLocalConfig=NonLocalConfig( # List of phone numbers for call deflection, values must be globally unique # Generating a random phone number for demonstration purposes # This should be replaced with a real brand phone number callDeflectionPhoneNumbers=[Phone(number='+10000000000'), Phone(number='+10000000001')], # Contact information for the agent that displays with the messaging button contactOption=ContactOption( options=[ContactOption.OptionsValueListEntryValuesEnum.EMAIL, ContactOption.OptionsValueListEntryValuesEnum.PHONE], url='https://www.your-company-website.com' ), # Domains enabled for messaging within Search, values must be globally unique # Generating a random URL for demonstration purposes # This should be replaced with a real brand URL enabledDomains=['your-company-website.com'], # Agent's phone number. Overrides the `phone` field for conversations started from non-local entry points phoneNumber=Phone(number='+10000000000'), # List of CLDR region codes for countries where the agent is allowed to launch `NON_LOCAL` entry points. # Example is for launching in Canada and the USA regionCodes=['US', 'CA'] ), defaultLocale='en', conversationalSettings=BusinessMessagesAgent.ConversationalSettingsValue( additionalProperties=[BusinessMessagesAgent.ConversationalSettingsValue.AdditionalProperty( key='en', value=ConversationalSetting( privacyPolicy=PrivacyPolicy(url='https://www.your-company-website.com/privacy'), welcomeMessage=WelcomeMessage(text='This is a sample welcome message'), conversationStarters=[ ConversationStarters( suggestion=Suggestion( reply=SuggestedReply(text='Option 1', postbackData='postback_option_1') ) ) ] ) )] ), primaryAgentInteraction=SupportedAgentInteraction( interactionType=SupportedAgentInteraction.InteractionTypeValueValuesEnum.HUMAN, humanRepresentative=HumanRepresentative( humanMessagingAvailability=MessagingAvailability(hours=[ Hours( startTime=TimeOfDay(hours=8, minutes=30), startDay=Hours.StartDayValueValuesEnum.MONDAY, endDay=Hours.EndDayValueValuesEnum.SATURDAY, endTime=TimeOfDay(hours=20, minutes=0), timeZone='America/Los_Angeles' ) ]) ) ), ) ) new_agent = agents_service.Create( BusinesscommunicationsBrandsAgentsCreateRequest( agent=agent, parent=brand_name ) ) print(new_agent)
如需了解格式设置和值选项,请参阅
brands.agents
。如果该品牌有您希望与代理相关联的营业地点,请参阅添加营业地点。
示例:为 Growing Tree Bank 创建代理
curl -X POST "https://businesscommunications.googleapis.com/v1/brands" \ -H "Content-Type: application/json" \ -H "User-Agent: curl/business-communications" \ -H "$(oauth2l header --json /path/to/service/account/key.json businesscommunications)" \ -d "{ 'displayName': 'Growing Tree Bank' }" # Fetch returned brand name value of "brands/12345" curl -X POST "https://businesscommunications.googleapis.com/v1/brands/12345/agents" \ -H "Content-Type: application/json" \ -H "User-Agent: curl/business-communications" \ -H "$(oauth2l header --json /path/to/service/account/key.json businesscommunications)" \ -d "{ 'displayName': 'Growing Tree Bank', 'businessMessagesAgent': { 'logoUrl': 'https://www.growingtreebank.com/images/logo.png', 'entryPointConfigs': [ { 'allowedEntryPoint': 'NON_LOCAL', }, { 'allowedEntryPoint': 'LOCATION', }, ], 'customAgentId': 'growing-tree-bank', 'nonLocalConfig': { 'regionCodes': ['001'], 'contactOption': { 'url': 'https://www.growingtreebank.com', 'options': [ 'EMAIL', 'PHONE', ], }, 'enabledDomains': [ 'https://www.growingtreebank.com', ], 'phoneNumber': { 'number': '+12223334444', }, 'callDeflectionPhoneNumbers': [ { 'number': '+12223334444', }, { 'number': '+56667778888', }, ], }, 'conversationalSettings': { 'en': { 'welcomeMessage': { 'text': 'Thanks for contacting Growing Tree Bank. What can I help with today?', }, 'privacyPolicy': { 'url': 'https://www.growingtreebank.com/privacy', }, 'conversationStarters': [ { 'suggestion': { 'reply': { 'text': 'Set up an account', 'postbackData': 'new-account', }, }, }, ], }, }, 'defaultLocale': 'en', 'primaryAgentInteraction': { 'interactionType': 'BOT', 'botRepresentative': { 'botMessagingAvailability': { 'hours': [ { 'startTime': { 'hours': '8', 'minutes': '00', }, 'endTime': { 'hours': '17', 'minutes': '30', }, 'timeZone': 'America/Los_Angeles', 'startDay': 'MONDAY', 'endDay': 'FRIDAY', }, ], }, }, }, }, }"
存储重要信息
当您创建代理时,Business Communications API 会返回该代理的值,包括 name
和 testUrls
。
设置代理级 webhook
您会在 webhook 中收到发送给代理的消息。如果您希望特定代理的消息到达其他 webhook,可以设置代理级 webhook。
如需设置代理级 webhook,请使用开发者控制台。
测试代理
每个客服人员都有测试网址,可让您查看与该客服人员的对话会以何种方式显示给用户,并让您有机会验证消息功能基础架构。
TestUrl 具有 url
和 surface
属性。如需使用 iOS 设备进行测试,请使用 Surface 值为 SURFACE_IOS_MAPS
的测试网址。使用已安装 Google 地图应用的 iOS 设备打开网址,即可在与代理对话时享用全面的功能。
Android 设备有两个测试网址。surface
值为 SURFACE_ANDROID_MAPS
的网址会在 Google 地图中会打开对话,并代表在 Google 地图中显示的对话入口点。surface
值为 SURFACE_ANDROID_WEB
的网址会在叠加对话视图中打开对话,并代表所有其他入口点。
对话界面打开后,对话会包含用户会看到的所有品牌信息,当您向代理发送消息时,webhook 会收到消息,包括您与用户沟通时会遇到的完整 JSON 载荷。
如需打开某个代理的测试网址,请在移动设备上点按链接或使用 Business Messages 代理启动器。
获取代理信息
若要获取有关代理的信息(例如 agentTestUrl
),您可以从 Business Communications API 获取该信息,前提是您设置了代理的 name
值。
获取单个代理的信息
如需获取代理信息,请运行以下命令。将 BRAND_ID 和 AGENT_ID 替换为该代理的 name
中的唯一值。
cURL
# This code gets the agent. # Read more: https://developers.google.com/business-communications/business-messages/reference/business-communications/rest/v1/brands.agents/get # Replace the __BRAND_ID__ and __AGENT_ID__ # Make sure a service account key file exists at ./service_account_key.json curl -X GET \ "https://businesscommunications.googleapis.com/v1/brands/__BRAND_ID__/agents/__AGENT_ID__" \ -H "Content-Type: application/json" \ -H "User-Agent: curl/business-communications" \ -H "$(oauth2l header --json ./service_account_key.json businesscommunications)"
Node.js
/** * This code snippet gets an agent. * Read more: https://developers.google.com/business-communications/business-messages/reference/business-communications/rest/v1/brands.agents/get * * This code is based on the https://github.com/google-business-communications/nodejs-businesscommunications Node.js * Business Communications client library. */ /** * Edit the values below: */ const BRAND_ID = 'EDIT_HERE'; const AGENT_ID = 'EDIT_HERE'; const PATH_TO_SERVICE_ACCOUNT_KEY = './service_account_key.json'; const businesscommunications = require('businesscommunications'); const {google} = require('googleapis'); // Initialize the Business Communications API const bcApi = new businesscommunications.businesscommunications_v1.Businesscommunications({}); // Set the scope that we need for the Business Communications API const scopes = [ 'https://www.googleapis.com/auth/businesscommunications', ]; // Set the private key to the service account file const privatekey = require(PATH_TO_SERVICE_ACCOUNT_KEY); async function main() { const authClient = await initCredentials(); const agentName = 'brands/' + BRAND_ID + '/agents/' + AGENT_ID; if (authClient) { // Setup the parameters for the API call const apiParams = { auth: authClient, name: agentName, }; bcApi.brands.agents.get(apiParams, {}, (err, response) => { if (err !== undefined && err !== null) { console.dir(err); } else { // Agent found console.log(response.data); } }); } 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); } }); }); } main();
Java
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.services.businesscommunications.v1.BusinessCommunications; import com.google.api.services.businesscommunications.v1.model.Agent; import java.io.FileInputStream; import java.util.Arrays; class Main { /** * Initializes credentials used by the Business Communications API. */ private static BusinessCommunications.Builder getBusinessCommunicationsBuilder() { BusinessCommunications.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/businesscommunications")); credential.refreshToken(); HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport(); JacksonFactory jsonFactory = JacksonFactory.getDefaultInstance(); // Create instance of the Business Communications API builder = new BusinessCommunications .Builder(httpTransport, jsonFactory, null) .setApplicationName(credential.getServiceAccountProjectId()); // Set the API credentials and endpoint builder.setHttpRequestInitializer(credential); } catch (Exception e) { e.printStackTrace(); } return builder; } public static void main(String args[]) { try { // Create client library reference BusinessCommunications.Builder builder = getBusinessCommunicationsBuilder(); String agentName = "brands/BRAND_ID/agents/AGENT_ID"; BusinessCommunications.Brands.Agents.Get request = builder .build().brands().agents().get(agentName); Agent agent = request.execute(); System.out.println(agent.toPrettyString()); } catch (Exception e) { e.printStackTrace(); } } }
Python
"""This code gets the agent. Read more: https://developers.google.com/business-communications/business-messages/reference/business-communications/rest/v1/brands.agents/get This code is based on the https://github.com/google-business-communications/python-businessmessages Python Business Messages client library. """ from oauth2client.service_account import ServiceAccountCredentials from businesscommunications.businesscommunications_v1_client import BusinesscommunicationsV1 from businesscommunications.businesscommunications_v1_messages import ( Agent, BusinesscommunicationsBrandsAgentsGetRequest, ) # Edit the values below: BRAND_ID = 'EDIT_HERE' AGENT_ID = 'EDIT_HERE' SCOPES = ['https://www.googleapis.com/auth/businesscommunications'] SERVICE_ACCOUNT_FILE = './service_account_key.json' credentials = ServiceAccountCredentials.from_json_keyfile_name( SERVICE_ACCOUNT_FILE, scopes=SCOPES) client = BusinesscommunicationsV1(credentials=credentials) agents_service = BusinesscommunicationsV1.BrandsAgentsService(client) agent_name = 'brands/' + BRAND_ID + '/agents/' + AGENT_ID agent = agents_service.Get(BusinesscommunicationsBrandsAgentsGetRequest( name=agent_name )) print(agent)
列出品牌的所有代理
如果您不知道代理的 name
,则可以通过省略 GET 请求网址中的 AGENT_ID 值来获取与品牌关联的所有代理的信息。
cURL
# This code lists all agents from a brand. # Read more: https://developers.google.com/business-communications/business-messages/reference/business-communications/rest/v1/brands.agents/list # Replace the __BRAND_ID__ # Make sure a service account key file exists at ./service_account_key.json curl -X GET \ "https://businesscommunications.googleapis.com/v1/brands/__BRAND_ID__/agents/" \ -H "Content-Type: application/json" \ -H "User-Agent: curl/business-communications" \ -H "$(oauth2l header --json ./service_account_key.json businesscommunications)"
Node.js
/** * This code snippet lists the agents of a brand. * Read more: https://developers.google.com/business-communications/business-messages/reference/business-communications/rest/v1/brands.agents/list * * This code is based on the https://github.com/google-business-communications/nodejs-businesscommunications Node.js * Business Communications client library. */ /** * Edit the values below: */ const BRAND_ID = 'EDIT_HERE'; const PATH_TO_SERVICE_ACCOUNT_KEY = './service_account_key.json'; const businesscommunications = require('businesscommunications'); const {google} = require('googleapis'); // Initialize the Business Communications API const bcApi = new businesscommunications.businesscommunications_v1.Businesscommunications({}); // Set the scope that we need for the Business Communications API const scopes = [ 'https://www.googleapis.com/auth/businesscommunications', ]; // Set the private key to the service account file const privatekey = require(PATH_TO_SERVICE_ACCOUNT_KEY); async function main() { const authClient = await initCredentials(); const brandName = 'brands/' + BRAND_ID; if (authClient) { // Setup the parameters for the API call const apiParams = { auth: authClient, parent: brandName, }; bcApi.brands.agents.list(apiParams, {}, (err, response) => { if (err !== undefined && err !== null) { console.dir(err); } else { // Agent found console.log(response.data); } }); } 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); } }); }); } main();
Java
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.services.businesscommunications.v1.BusinessCommunications; import com.google.api.services.businesscommunications.v1.model.Agent; import java.io.FileInputStream; import java.io.IOException; import java.util.Arrays; import java.util.List; class Main { /** * Initializes credentials used by the Business Communications API. */ private static BusinessCommunications.Builder getBusinessCommunicationsBuilder() { BusinessCommunications.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/businesscommunications")); credential.refreshToken(); HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport(); JacksonFactory jsonFactory = JacksonFactory.getDefaultInstance(); // Create instance of the Business Communications API builder = new BusinessCommunications .Builder(httpTransport, jsonFactory, null) .setApplicationName(credential.getServiceAccountProjectId()); // Set the API credentials and endpoint builder.setHttpRequestInitializer(credential); } catch (Exception e) { e.printStackTrace(); } return builder; } public static void main(String args[]) { try { // Create client library reference BusinessCommunications.Builder builder = getBusinessCommunicationsBuilder(); String brandName = "brands/BRAND_ID"; BusinessCommunications.Brands.Agents.List request = builder .build().brands().agents().list(brandName); Listagents = request.execute().getAgents(); agents.stream().forEach(agent -> { try { System.out.println(agent.toPrettyString()); } catch (IOException e) { e.printStackTrace(); } }); } catch (Exception e) { e.printStackTrace(); } } }
Python
"""This code lists all agents from a brand. Read more: https://developers.google.com/business-communications/business-messages/reference/business-communications/rest/v1/brands.agents/list This code is based on the https://github.com/google-business-communications/python-businessmessages Python Business Messages client library. """ from oauth2client.service_account import ServiceAccountCredentials from businesscommunications.businesscommunications_v1_client import BusinesscommunicationsV1 from businesscommunications.businesscommunications_v1_messages import ( Agent, BusinesscommunicationsBrandsAgentsGetRequest, ) # Edit the values below: BRAND_ID = 'EDIT_HERE' SCOPES = ['https://www.googleapis.com/auth/businesscommunications'] SERVICE_ACCOUNT_FILE = './service_account_key.json' credentials = ServiceAccountCredentials.from_json_keyfile_name( SERVICE_ACCOUNT_FILE, scopes=SCOPES) client = BusinesscommunicationsV1(credentials=credentials) agents_service = BusinesscommunicationsV1.BrandsAgentsService(client) brand_name = 'brands/' + BRAND_ID agents = agents_service.List(BusinesscommunicationsBrandsAgentsListRequest( parent=brand_name )) print(agents)
更新代理信息
如需更新代理,您可以使用 Business Communications API 执行 PATCH 请求。进行 API 调用时,您可以将要修改字段的名称添加为“updateMask”网址参数的值。
例如,如果您更新 displayName
和 customAgentId
字段,那么“updateMask”网址参数为“updateMask=displayName,businessMessagesAgent.customAgentId”。
如需了解格式设置和值选项,请参阅 brands.agents.patch
。
如果您不知道代理的 name
,请参阅列出品牌的所有代理。
验证代理后,您只能更新以下字段:
conversationalSetting
customAgentId
defaultLocale
primaryAgentInteraction
additionalAgentInteractions
phone
如果您在验证代理后需要更新其他字段,请与我们联系。(您必须先使用 Business Messages Google 账号登录。如需注册账号,请参阅在 Business Messages 中注册。)
示例:更新显示名称
cURL
curl -X PATCH \ "https://businesscommunications.googleapis.com/v1/brands/BRAND_ID/agents/AGENT_ID?updateMask=displayName" \ -H "Content-Type: application/json" \ -H "User-Agent: curl/business-communications" \ -H "$(oauth2l header --json PATH_TO_SERVICE_ACCOUNT_KEY businesscommunications)" \ -d "{ 'displayName': 'Growing Tree Bank', }"
Node.js
const businesscommunications = require('businesscommunications'); const {google} = require('googleapis'); // Initialize the Business Communications API let bcApi = new businesscommunications.businesscommunications_v1.Businesscommunications({}); // Set the scope that we need for the Business Communications API const scopes = [ 'https://www.googleapis.com/auth/businesscommunications', ]; // Set the private key to the service account file const privatekey = require('PATH_TO_SERVICE_ACCOUNT_KEY'); /** * Initializes the Google credentials for calling the * Business Messages API. */ async function initCredentials() { // Configure a JWT auth client let 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); } }); }); } async function main() { let authClient = await initCredentials(); let agentName = 'brands/BRAND_ID/agents/AGENT_ID'; if (authClient) { // Setup the parameters for the API call const apiParams = { auth: authClient, name: agentName, updateMask: 'displayName', resource: { displayName: 'Growing Tree Bank', } }; bcApi.brands.agents.patch(apiParams, {}, (err, response) => { if (err !== undefined && err !== null) { console.dir(err); } else { // Agent found console.log(response.data); } }); } else { console.log('Authentication failure.'); } } main();
Java
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.services.businesscommunications.v1.BusinessCommunications; import com.google.api.services.businesscommunications.v1.model.Agent; import java.io.FileInputStream; import java.util.Arrays; class Main { /** * Initializes credentials used by the Business Communications API. */ private static BusinessCommunications.Builder getBusinessCommunicationsBuilder() { BusinessCommunications.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/businesscommunications")); credential.refreshToken(); HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport(); JacksonFactory jsonFactory = JacksonFactory.getDefaultInstance(); // Create instance of the Business Communications API builder = new BusinessCommunications .Builder(httpTransport, jsonFactory, null) .setApplicationName(credential.getServiceAccountProjectId()); // Set the API credentials and endpoint builder.setHttpRequestInitializer(credential); } catch (Exception e) { e.printStackTrace(); } return builder; } public static void main(String args[]) { try { // Create client library reference BusinessCommunications.Builder builder = getBusinessCommunicationsBuilder(); String agentName = "brands/BRAND_ID/agents/AGENT_ID"; Agent agent = new Agent().setDisplayName("Growing Tree Bank"); BusinessCommunications.Brands.Agents.Patch request = builder .build().brands().agents().patch(agentName, agent); request.setUpdateMask("displayName"); Agent updatedAgent = request.execute(); System.out.println(updatedAgent.toPrettyString()); } catch (Exception e) { e.printStackTrace(); } } }
Python
from oauth2client.service_account import ServiceAccountCredentials from businesscommunications.businesscommunications_v1_client import ( BusinesscommunicationsV1 ) from businesscommunications.businesscommunications_v1_messages import ( Agent, BusinesscommunicationsBrandsAgentsPatchRequest, ) SCOPES = ['https://www.googleapis.com/auth/businesscommunications'] SERVICE_ACCOUNT_FILE = 'PATH_TO_SERVICE_ACCOUNT_KEY' credentials = ServiceAccountCredentials.from_json_keyfile_name( SERVICE_ACCOUNT_FILE, scopes=SCOPES) client = BusinesscommunicationsV1(credentials=credentials) agents_service = BusinesscommunicationsV1.BrandsAgentsService(client) agent_name = 'brands/BRAND_ID/agents/AGENT_ID' agent=Agent( displayName='Growing Tree Bank' ) updated_agent = agents_service.Patch( BusinesscommunicationsBrandsAgentsPatchRequest( agent=agent, name=agent_name, updateMask='displayName' ) ) print(updated_agent)
示例:指定 NON_LOCAL
和 LOCATION
入口点组
cURL
curl -X PATCH \ "https://businesscommunications.googleapis.com/v1/brands/BRAND_ID/agents/AGENT_ID?updateMask=businessMessagesAgent.entryPointConfigs" \ -H "Content-Type: application/json" \ -H "User-Agent: curl/business-communications" \ -H "$(oauth2l header --json PATH_TO_SERVICE_ACCOUNT_KEY businesscommunications)" \ -d "{ 'businessMessagesAgent': { 'entryPointConfigs': [ { 'allowedEntryPoint': 'NON_LOCAL', }, { 'allowedEntryPoint': 'LOCATION', }, ], }, }"
Node.js
const businesscommunications = require('businesscommunications'); const {google} = require('googleapis'); // Initialize the Business Communications API let bcApi = new businesscommunications.businesscommunications_v1.Businesscommunications({}); // Set the scope that we need for the Business Communications API const scopes = [ 'https://www.googleapis.com/auth/businesscommunications', ]; // Set the private key to the service account file const privatekey = require('PATH_TO_SERVICE_ACCOUNT_KEY'); /** * Initializes the Google credentials for calling the * Business Messages API. */ async function initCredentials() { // Configure a JWT auth client let 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); } }); }); } async function main() { let authClient = await initCredentials(); let agentName = 'brands/BRAND_ID/agents/AGENT_ID'; if (authClient) { // Setup the parameters for the API call const apiParams = { auth: authClient, name: agentName, updateMask: 'businessMessagesAgent.entryPointConfigs', resource: { businessMessagesAgent: { entryPointConfigs: [ { allowedEntryPoint: 'LOCATION', }, { allowedEntryPoint: 'NON_LOCAL', }, ], } } }; bcApi.brands.agents.patch(apiParams, {}, (err, response) => { if (err !== undefined && err !== null) { console.dir(err); } else { // Agent found console.log(response.data); } }); } else { console.log('Authentication failure.'); } } main();
Java
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.services.businesscommunications.v1.BusinessCommunications; import com.google.api.services.businesscommunications.v1.model.*; import java.io.FileInputStream; import java.util.Arrays; class Main { /** * Initializes credentials used by the Business Communications API. */ private static BusinessCommunications.Builder getBusinessCommunicationsBuilder() { BusinessCommunications.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/businesscommunications")); credential.refreshToken(); HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport(); JacksonFactory jsonFactory = JacksonFactory.getDefaultInstance(); // Create instance of the Business Communications API builder = new BusinessCommunications .Builder(httpTransport, jsonFactory, null) .setApplicationName(credential.getServiceAccountProjectId()); // Set the API credentials and endpoint builder.setHttpRequestInitializer(credential); } catch (Exception e) { e.printStackTrace(); } return builder; } public static void main(String args[]) { try { // Create client library reference BusinessCommunications.Builder builder = getBusinessCommunicationsBuilder(); String agentName = "brands/BRAND_ID/agents/AGENT_ID"; Agent agent = new Agent().setBusinessMessagesAgent( new BusinessMessagesAgent().setEntryPointConfigs(Arrays.asList( new BusinessMessagesEntryPointConfig() .setAllowedEntryPoint( "NON_LOCAL"), new BusinessMessagesEntryPointConfig() .setAllowedEntryPoint( "LOCATION")))); BusinessCommunications.Brands.Agents.Patch request = builder .build().brands().agents().patch(agentName, agent); request.setUpdateMask("businessMessagesAgent.entryPointConfigs"); Agent updatedAgent = request.execute(); System.out.println(updatedAgent.toPrettyString()); } catch (Exception e) { e.printStackTrace(); } } }
Python
from oauth2client.service_account import ServiceAccountCredentials from businesscommunications.businesscommunications_v1_client import ( BusinesscommunicationsV1 ) from businesscommunications.businesscommunications_v1_messages import ( Agent, BusinessMessagesAgent, BusinessMessagesEntryPointConfig, BusinesscommunicationsBrandsAgentsPatchRequest, ) SCOPES = ['https://www.googleapis.com/auth/businesscommunications'] SERVICE_ACCOUNT_FILE = 'PATH_TO_SERVICE_ACCOUNT_KEY' credentials = ServiceAccountCredentials.from_json_keyfile_name( SERVICE_ACCOUNT_FILE, scopes=SCOPES) client = BusinesscommunicationsV1(credentials=credentials) agents_service = BusinesscommunicationsV1.BrandsAgentsService(client) agent_name = 'brands/BRAND_ID/agents/AGENT_ID' agent=Agent( businessMessagesAgent=BusinessMessagesAgent( entryPointConfigs=[BusinessMessagesEntryPointConfig( allowedEntryPoint=BusinessMessagesEntryPointConfig.AllowedEntryPointValueValuesEnum.NON_LOCAL ), BusinessMessagesEntryPointConfig( allowedEntryPoint=BusinessMessagesEntryPointConfig.AllowedEntryPointValueValuesEnum.LOCATION )] ) ) updated_agent = agents_service.Patch( BusinesscommunicationsBrandsAgentsPatchRequest( agent=agent, name=agent_name, updateMask='businessMessagesAgent.entryPointConfigs' ) ) print(updated_agent)
示例:更新欢迎辞
如果您更新 conversationalSettings
中的任何字段(例如 welcomeMessage
),则必须更新该对象中的所有字段,并且必须指定相关设置的语言区域(以两个字符的 ISO 639-1 语言代码表示)。
cURL
curl -X PATCH \ "https://businesscommunications.googleapis.com/v1/brands/BRAND_ID/agents/AGENT_ID?updateMask=businessMessagesAgent.conversationalSettings.en" \ -H "Content-Type: application/json" \ -H "User-Agent: curl/business-communications" \ -H "$(oauth2l header --json PATH_TO_SERVICE_ACCOUNT_KEY businesscommunications)" \ -d "{ 'businessMessagesAgent': { 'conversationalSettings': { 'en': { 'welcomeMessage': { 'text': 'Thanks for contacting Growing Tree Bank. What can I help with today?', }, 'offlineMessage': { 'text': 'We\'re closed for the night. Please reach out to us again tomorrow.', }, 'privacyPolicy': { 'url': 'https://www.growingtreebank.com/privacy', }, 'conversationStarters': [ { 'suggestion': { 'reply': { 'text': 'Set up an account', 'postbackData': 'new-account', }, }, }, { 'suggestion': { 'reply': { 'text': 'Look up account information', 'postbackData': 'account-lookup', }, }, }, ], }, }, }, }"
Node.js
const businesscommunications = require('businesscommunications'); const {google} = require('googleapis'); // Initialize the Business Communications API let bcApi = new businesscommunications.businesscommunications_v1.Businesscommunications({}); // Set the scope that we need for the Business Communications API const scopes = [ 'https://www.googleapis.com/auth/businesscommunications', ]; // Set the private key to the service account file const privatekey = require('PATH_TO_SERVICE_ACCOUNT_KEY'); /** * Initializes the Google credentials for calling the * Business Messages API. */ async function initCredentials() { // Configure a JWT auth client let 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); } }); }); } async function main() { let authClient = await initCredentials(); let agentName = 'brands/BRAND_ID/agents/AGENT_ID'; if (authClient) { // Setup the parameters for the API call const apiParams = { auth: authClient, name: agentName, updateMask: 'businessMessagesAgent.conversationalSettings.en', resource: { businessMessagesAgent: { conversationalSettings: { en: { privacyPolicy: { url: 'https://www.growingtreebank.com/privacy' }, welcomeMessage: { text: 'Thanks for contacting Growing Tree Bank. What can I help with today?' }, offlineMessage: { text: 'We\'re closed for the night. Please reach out to us again tomorrow.' }, conversationStarters: [ { suggestion: { reply: { text: 'Set up an account', postbackData: 'new-account', }, }, }, { suggestion: { reply: { text: 'Look up account information', postbackData: 'account-lookup', }, }, }, ], }, } } } }; bcApi.brands.agents.patch(apiParams, {}, (err, response) => { if (err !== undefined && err !== null) { console.dir(err); } else { // Agent found console.log(response.data); } }); } else { console.log('Authentication failure.'); } } main();
Java
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.services.businesscommunications.v1.BusinessCommunications; import com.google.api.services.businesscommunications.v1.model.*; import com.google.common.collect.ImmutableMap; import java.io.FileInputStream; import java.util.Arrays; class Main { /** * Initializes credentials used by the Business Communications API. */ private static BusinessCommunications.Builder getBusinessCommunicationsBuilder() { BusinessCommunications.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/businesscommunications")); credential.refreshToken(); HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport(); JacksonFactory jsonFactory = JacksonFactory.getDefaultInstance(); // Create instance of the Business Communications API builder = new BusinessCommunications .Builder(httpTransport, jsonFactory, null) .setApplicationName(credential.getServiceAccountProjectId()); // Set the API credentials and endpoint builder.setHttpRequestInitializer(credential); } catch (Exception e) { e.printStackTrace(); } return builder; } public static void main(String args[]) { try { // Create client library reference BusinessCommunications.Builder builder = getBusinessCommunicationsBuilder(); String agentName = "brands/BRAND_ID/agents/AGENT_ID"; Agent agent = new Agent().setBusinessMessagesAgent( new BusinessMessagesAgent().setConversationalSettings(ImmutableMap.of("en", new ConversationalSetting() .setPrivacyPolicy(new PrivacyPolicy().setUrl("https://www.growingtreebank.com/privacy")) .setWelcomeMessage(new WelcomeMessage().setText("Thanks for contacting Growing Tree Bank. What can I help with today?")) .setOfflineMessage(new OfflineMessage().setText("We're closed for the night. Please reach out to us again tomorrow.")) .setConversationStarters(Arrays.asList( new ConversationStarters().setSuggestion(new Suggestion() .setReply(new SuggestedReply() .setText("Set up an account") .setPostbackData("new-account"))), new ConversationStarters().setSuggestion(new Suggestion() .setReply(new SuggestedReply() .setText("Look up account information") .setPostbackData("account-lookup"))) ))))); BusinessCommunications.Brands.Agents.Patch request = builder .build().brands().agents().patch(agentName, agent); request.setUpdateMask("businessMessagesAgent.conversationalSettings.en"); Agent updatedAgent = request.execute(); System.out.println(updatedAgent.toPrettyString()); } catch (Exception e) { e.printStackTrace(); } } }
Python
from oauth2client.service_account import ServiceAccountCredentials from businesscommunications.businesscommunications_v1_client import ( BusinesscommunicationsV1 ) from businesscommunications.businesscommunications_v1_messages import ( Agent, BusinessMessagesAgent, ConversationStarters, ConversationalSetting, OfflineMessage, PrivacyPolicy, WelcomeMessage, BusinesscommunicationsBrandsAgentsPatchRequest, ) SCOPES = ['https://www.googleapis.com/auth/businesscommunications'] SERVICE_ACCOUNT_FILE = 'PATH_TO_SERVICE_ACCOUNT_KEY' credentials = ServiceAccountCredentials.from_json_keyfile_name( SERVICE_ACCOUNT_FILE, scopes=SCOPES) client = BusinesscommunicationsV1(credentials=credentials) agents_service = BusinesscommunicationsV1.BrandsAgentsService(client) agent_name = 'brands/BRAND_ID/agents/AGENT_ID' agent=Agent( businessMessagesAgent=BusinessMessagesAgent( conversationalSettings=BusinessMessagesAgent.ConversationalSettingsValue( additionalProperties=[BusinessMessagesAgent.ConversationalSettingsValue.AdditionalProperty( key='en', value=ConversationalSetting( privacyPolicy=PrivacyPolicy(url='https://www.growingtreebank.com/privacy'), welcomeMessage=WelcomeMessage(text='Thanks for contacting Growing Tree Bank. What can I help with today?'), offlineMessage=OfflineMessage(text='We\'re closed for the night. Please reach out to us again tomorrow.'), conversationStarters=[ ConversationStarters( suggestion=Suggestion( reply=SuggestedReply(text='Set up an account', postbackData='new-account') ) ), ConversationStarters( suggestion=Suggestion( reply=SuggestedReply(text='Look up account information', postbackData='account-lookup') ) )] ) ) ] ) ) ) updated_agent = agents_service.Patch( BusinesscommunicationsBrandsAgentsPatchRequest( agent=agent, name=agent_name, updateMask='businessMessagesAgent.conversationalSettings.en' ) ) print(updated_agent)
删除代理
在您删除代理后,Business Messages 会删除所有代理数据。Business Messages 不会删除代理所发送的消息,这些消息将传输至用户设备或存储在用户设备上。发送给用户的消息不是代理数据。
如果代理具有关联的营业地点,或者您已尝试对代理进行一次或多次验证,删除请求将失败。如需更新营业地点,请参阅添加营业地点。
您无法删除经过验证的客服人员。如需删除您已验证或尝试验证的代理,请与我们联系。(您必须先使用 Business Messages Google 账号登录。如需注册账号,请参阅在 Business Messages 中注册。)
如需删除代理,请运行以下命令。将 BRAND_ID 和 AGENT_ID 替换为该代理的 name
中的唯一值。
cURL
# This code deletes an agent. # Read more: https://developers.google.com/business-communications/business-messages/reference/business-communications/rest/v1/brands.agents/delete # Replace the __BRAND_ID__ and __AGENT_ID__ # Make sure a service account key file exists at ./service_account_key.json curl -X DELETE "https://businesscommunications.googleapis.com/v1/brands/__BRAND_ID__/agents/__AGENT_ID__" \ -H "Content-Type: application/json" \ -H "User-Agent: curl/business-communications" \ -H "$(oauth2l header --json ./service_account_key.json businesscommunications)"
Node.js
/** * This code snippet deletes an agent. * Read more: https://developers.google.com/business-communications/business-messages/reference/business-communications/rest/v1/brands.agents/delete * * This code is based on the https://github.com/google-business-communications/nodejs-businesscommunications Node.js * Business Communications client library. */ /** * Edit the values below: */ const BRAND_ID = 'EDIT_HERE'; const AGENT_ID = 'EDIT_HERE'; const PATH_TO_SERVICE_ACCOUNT_KEY = './service_account_key.json'; const businesscommunications = require('businesscommunications'); const {google} = require('googleapis'); // Initialize the Business Communications API const bcApi = new businesscommunications.businesscommunications_v1.Businesscommunications({}); // Set the scope that we need for the Business Communications API const scopes = [ 'https://www.googleapis.com/auth/businesscommunications', ]; // Set the private key to the service account file const privatekey = require(PATH_TO_SERVICE_ACCOUNT_KEY); async function main() { const authClient = await initCredentials(); const agentName = 'brands/' + BRAND_ID + '/agents/' + AGENT_ID; if (authClient) { // Setup the parameters for the API call const apiParams = { auth: authClient, name: agentName, }; bcApi.brands.agents.delete(apiParams, {}, (err, response) => { if (err !== undefined && err !== null) { console.dir(err); } else { // Agent removed console.log(response.data); } }); } 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); } }); }); } main();
Java
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.services.businesscommunications.v1.BusinessCommunications; import com.google.api.services.businesscommunications.v1.model.*; import java.io.FileInputStream; import java.util.Arrays; class Main { /** * Initializes credentials used by the Business Communications API. */ private static BusinessCommunications.Builder getBusinessCommunicationsBuilder() { BusinessCommunications.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/businesscommunications")); credential.refreshToken(); HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport(); JacksonFactory jsonFactory = JacksonFactory.getDefaultInstance(); // Create instance of the Business Communications API builder = new BusinessCommunications .Builder(httpTransport, jsonFactory, null) .setApplicationName(credential.getServiceAccountProjectId()); // Set the API credentials and endpoint builder.setHttpRequestInitializer(credential); } catch (Exception e) { e.printStackTrace(); } return builder; } public static void main(String args[]) { try { // Create client library reference BusinessCommunications.Builder builder = getBusinessCommunicationsBuilder(); String agentName = "brands/BRAND_ID/agents/AGENT_ID"; BusinessCommunications.Brands.Agents.Delete request = builder.build().brands().agents().delete(agentName); System.out.println(request.execute()); } catch (Exception e) { e.printStackTrace(); } } }
Python
"""This code deletes an agent. Read more: https://developers.google.com/business-communications/business-messages/reference/business-communications/rest/v1/brands.agents/delete This code is based on the https://github.com/google-business-communications/python-businessmessages Python Business Messages client library. """ from oauth2client.service_account import ServiceAccountCredentials from businesscommunications.businesscommunications_v1_client import BusinesscommunicationsV1 from businesscommunications.businesscommunications_v1_messages import ( Agent, BusinesscommunicationsBrandsAgentsDeleteRequest, ) # Edit the values below: BRAND_ID = 'EDIT_HERE' AGENT_ID = 'EDIT_HERE' SCOPES = ['https://www.googleapis.com/auth/businesscommunications'] SERVICE_ACCOUNT_FILE = './service_account_key.json' credentials = ServiceAccountCredentials.from_json_keyfile_name( SERVICE_ACCOUNT_FILE, scopes=SCOPES) client = BusinesscommunicationsV1(credentials=credentials) agents_service = BusinesscommunicationsV1.BrandsAgentsService(client) agent_name = 'brands/' + BRAND_ID + '/agents/' + AGENT_ID agent = agents_service.Delete(BusinesscommunicationsBrandsAgentsDeleteRequest( name=agent_name )) print(agent)
如需了解格式设置和值选项,请参阅 brands.agents.delete
。
删除品牌
删除品牌时,您可以通过 Business Communications API 执行 DELETE 请求。如果您有一个或多个与品牌相关联的代理或营业地点,即使这些代理属于不同商品,删除请求也会失败。
如需删除品牌,请运行以下命令。将 BRAND_ID 替换为该品牌的 name
中的唯一值。
cURL
# This code deletes a brand. # Read more: https://developers.google.com/business-communications/business-messages/reference/business-communications/rest/v1/brands/delete # Replace the __BRAND_ID__ # Make sure a service account key file exists at ./service_account_key.json curl -X DELETE "https://businesscommunications.googleapis.com/v1/brands/__BRAND_ID__" \ -H "Content-Type: application/json" \ -H "User-Agent: curl/business-communications" \ -H "$(oauth2l header --json ./service_account_key.json businesscommunications)"
Node.js
/** * This code snippet deletes a brand. * Read more: https://developers.google.com/business-communications/business-messages/reference/business-communications/rest/v1/brands/delete * * This code is based on the https://github.com/google-business-communications/nodejs-businesscommunications Node.js * Business Communications client library. */ /** * Edit the values below: */ const BRAND_ID = 'EDIT_HERE'; const PATH_TO_SERVICE_ACCOUNT_KEY = './service_account_key.json'; const businesscommunications = require('businesscommunications'); const {google} = require('googleapis'); // Initialize the Business Communications API const bcApi = new businesscommunications.businesscommunications_v1.Businesscommunications({}); // Set the scope that we need for the Business Communications API const scopes = [ 'https://www.googleapis.com/auth/businesscommunications', ]; // Set the private key to the service account file const privatekey = require(PATH_TO_SERVICE_ACCOUNT_KEY); async function main() { const authClient = await initCredentials(); const brandName = 'brands/' + BRAND_ID; if (authClient) { // Setup the parameters for the API call const apiParams = { auth: authClient, name: brandName, }; bcApi.brands.delete(apiParams, {}, (err, response) => { if (err !== undefined && err !== null) { console.dir(err); } else { // Brand removed console.log(response.data); } }); } 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); } }); }); } main();
Java
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.services.businesscommunications.v1.BusinessCommunications; import com.google.api.services.businesscommunications.v1.model.*; import java.io.FileInputStream; import java.util.Arrays; class Main { /** * Initializes credentials used by the Business Communications API. */ private static BusinessCommunications.Builder getBusinessCommunicationsBuilder() { BusinessCommunications.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/businesscommunications")); credential.refreshToken(); HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport(); JacksonFactory jsonFactory = JacksonFactory.getDefaultInstance(); // Create instance of the Business Communications API builder = new BusinessCommunications .Builder(httpTransport, jsonFactory, null) .setApplicationName(credential.getServiceAccountProjectId()); // Set the API credentials and endpoint builder.setHttpRequestInitializer(credential); } catch (Exception e) { e.printStackTrace(); } return builder; } public static void main(String args[]) { try { // Create client library reference BusinessCommunications.Builder builder = getBusinessCommunicationsBuilder(); String brandName = "brands/BRAND_ID"; BusinessCommunications.Brands.Delete request = builder.build().brands().delete(brandName); System.out.println(request.execute()); } catch (Exception e) { e.printStackTrace(); } } }
Python
"""This code deletes a brand. Read more: https://developers.google.com/business-communications/business-messages/reference/business-communications/rest/v1/brands/delete This code is based on the https://github.com/google-business-communications/python-businessmessages Python Business Messages client library. """ from oauth2client.service_account import ServiceAccountCredentials from businesscommunications.businesscommunications_v1_client import BusinesscommunicationsV1 from businesscommunications.businesscommunications_v1_messages import ( BusinesscommunicationsBrandsAgentsDeleteRequest ) # Edit the values below: BRAND_ID = 'EDIT_HERE' SCOPES = ['https://www.googleapis.com/auth/businesscommunications'] SERVICE_ACCOUNT_FILE = './service_account_key.json' credentials = ServiceAccountCredentials.from_json_keyfile_name( SERVICE_ACCOUNT_FILE, scopes=SCOPES) client = BusinesscommunicationsV1(credentials=credentials) agents_service = BusinesscommunicationsV1.BrandsAgentsService(client) brand_name = 'brands/' + BRAND_ID agent = agents_service.Delete(BusinesscommunicationsBrandsAgentsDeleteRequest( name=brand_name )) print(agent)
如需了解格式设置和值选项,请参阅 brands.delete
。
后续步骤
现在您有了代理,可以执行以下步骤: