註冊合作夥伴後,您可以為所管理的品牌建立 Business Messages 服務專員,啟用對話功能。
服務專員是使用者互動的對話實體。您可以為管理的每個品牌建立一個代理程式。您可以使用 Business Communications API 建立及管理服務專員,並使用 Business Messages API 控管服務專員的訊息。
代理商涵蓋品牌的業務功能,例如線上支援服務和實體位置 (如有)。每則訊息都包含使用者發起對話的背景資訊。您的訊息轉送基礎架構可偵測使用者是否查看特定商家位置或尋求一般支援服務,並將訊息轉送至正確的目的地。
舉例來說,如果您管理 Growing Tree Bank 品牌,該品牌有一個網站和兩個地點,您就會建立一個「Growing Tree Bank」代理商。使用者可以透過一般搜尋或以位置為依據的搜尋找到服務專員,而使用者找到服務專員的內容會隨每則訊息傳送至 Webhook。您可以使用該背景資訊,將訊息轉送給某地點的員工或網站支援團隊,讓他們建立回應,並繼續與使用者對話。
期望
建立服務專員前,請先瞭解 Business Messages 服務專員的預期用途。
- 服務專員應遵循「Business Messages 的對話設計」一文中所述的設計指南。
如果自動化系統無法滿足要求,或使用者提出要求,服務專員應提供人工代表來回答問題。
如指標所述,服務專員應維持至少 80% 的顧客滿意度評分 (CSAT),以及至少 95% 的商家回應率 (MRR)。
建立虛擬服務專員
如要建立服務專員,您必須收集並提交品牌相關資訊,以及希望服務專員向使用者顯示的樣貌。
如果您管理多個品牌,請重複執行這些步驟,為每個品牌建立代理人。
必要條件
為所管理的品牌建立代理人前,您必須先收集一些資訊:
開發環境
開發環境相關資訊。
啟用 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_IOS_MAPS
。在已安裝 Google 地圖應用程式的 iOS 裝置上開啟網址,即可與服務專員進行完整的對話。
Android 裝置有兩個測試網址。surface
值為 SURFACE_ANDROID_MAPS
的網址會在 Google 地圖中開啟對話,並代表 Google 地圖中顯示的對話入口。surface
值為 SURFACE_ANDROID_WEB
的網址會在疊加對話視圖中開啟對話,並代表所有其他進入點。
對話介面開啟後,對話內容會包含使用者會看到的所有品牌資訊。當您傳送訊息給代理程式時,您的 webhook 會接收訊息,包括與使用者通訊時可預期的完整 JSON 酬載。
如要開啟代理程式的測試網址,請輕觸連結或在行動裝置上使用 Business Messages 代理程式啟動器。
取得服務專員資訊
如要取得服務專員的相關資訊 (例如 agentTestUrl
),只要您有服務專員的 name
值,就可以從 Business Communications API 取得資訊。
取得單一服務專員的資訊
如要取得代理人資訊,請執行下列指令。將 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
。
後續步驟
有了服務專員,您可以採取下列步驟: