Sau khi đăng ký làm đối tác, bạn có thể bật tính năng trò chuyện cho các thương hiệu mà bạn quản lý bằng cách tạo nhân viên hỗ trợ trên Business Messages cho các thương hiệu đó.
Nhân viên hỗ trợ là một thực thể trò chuyện mà người dùng tương tác. Bạn tạo một đại lý cho mỗi thương hiệu mà bạn quản lý. Bạn tạo và quản lý nhân viên hỗ trợ bằng API Thông tin liên lạc của doanh nghiệp, đồng thời kiểm soát việc nhắn tin cho nhân viên hỗ trợ bằng API Tin nhắn của doanh nghiệp.
Đại lý bao gồm các chức năng kinh doanh của một thương hiệu, chẳng hạn như hỗ trợ trực tuyến và vị trí thực tế (nếu có). Mỗi tin nhắn chứa ngữ cảnh mà người dùng đã bắt đầu cuộc trò chuyện. Cơ sở hạ tầng định tuyến thư của bạn có thể phát hiện xem người dùng đã xem một địa điểm kinh doanh cụ thể hay tìm kiếm thông tin hỗ trợ chung, đồng thời có thể định tuyến thư đến đúng đích.
Ví dụ: nếu quản lý thương hiệu Growing Tree Bank có một trang web và hai vị trí, bạn sẽ tạo một đại lý "Growing Tree Bank". Người dùng có thể gặp được trợ lý thông qua các lượt tìm kiếm chung hoặc dựa trên vị trí, đồng thời ngữ cảnh mà người dùng tìm thấy trợ lý sẽ được truyền cùng với từng thông báo đến webhook của bạn. Bạn sử dụng ngữ cảnh đó để định tuyến tin nhắn đến nhân viên tại một vị trí hoặc đến nhóm hỗ trợ trang web. Nhóm này sẽ tạo phản hồi và tiếp tục cuộc trò chuyện với người dùng.
Kỳ vọng
Trước khi tạo nhân viên hỗ trợ, hãy tìm hiểu những kỳ vọng đối với nhân viên hỗ trợ trên Business Messages.
- Nhân viên hỗ trợ phải tuân theo hướng dẫn thiết kế được nêu trong bài viết Thiết kế cuộc trò chuyện cho Business Messages.
Nhân viên hỗ trợ phải có người đại diện để trả lời các câu hỏi khi hệ thống tự động không thể thực hiện yêu cầu hoặc khi người dùng yêu cầu.
Nhân viên hỗ trợ phải duy trì điểm xếp hạng mức độ hài lòng của khách hàng (CSAT) ít nhất là 80% và tỷ lệ phản hồi của người bán (MRR) ít nhất là 95% như đã nêu trong phần Chỉ số.
Tạo một nhân viên hỗ trợ
Để tạo một nhân viên hỗ trợ, bạn cần thu thập và gửi thông tin về thương hiệu cũng như cách bạn muốn nhân viên hỗ trợ xuất hiện trước người dùng.
Nếu bạn quản lý nhiều thương hiệu, hãy lặp lại các bước để tạo một người đại diện cho từng thương hiệu.
Điều kiện tiên quyết
Trước khi tạo người đại diện cho các thương hiệu mà bạn quản lý, bạn cần thu thập một số thông tin:
Môi trường phát triển
Thông tin về môi trường phát triển của bạn.
Dự án GCP đã bật API Thông tin liên lạc kinh doanh
Để bật API, hãy xem phần Đăng ký với Business Messages.
Đường dẫn đến khoá tài khoản dịch vụ của dự án GCP trên máy phát triển
Thông tin chi tiết về thương hiệu
Thông tin về thương hiệu mà nhân viên hỗ trợ đại diện.
- Tên thương hiệu
- Trang web của thương hiệu
- Các lựa chọn liên hệ trên trang web (như được xác định trong
OPTION
) - Số điện thoại dành cho người tiêu dùng
- Số điện thoại được bật tính năng chuyển hướng cuộc gọi
Hình thức và chính sách của nhân viên hỗ trợ
Thông tin về cách nhân viên hỗ trợ xuất hiện trước người dùng và cách hoạt động của nhân viên hỗ trợ.
- Tên nhân viên hỗ trợ mà bạn muốn xuất hiện trong cuộc trò chuyện với người dùng
- Chính sách quyền riêng tư, dưới dạng một URL công khai bắt đầu bằng "https://"
(Nên dùng) Biểu trưng của nhân viên hỗ trợ (1024x1024 px), dưới dạng URL công khai
Trong cuộc trò chuyện, biểu trưng sẽ hiển thị dưới dạng hình tròn có đường kính 1024 px. Đảm bảo rằng biểu trưng của bạn hiển thị tốt ở dạng hình tròn.
(Không bắt buộc) Mã nhân viên hỗ trợ tuỳ chỉnh, giúp nhận dạng thương hiệu trong các thông báo mà webhook nhận được
Tương tác với nhân viên hỗ trợ
Thông tin về cách nhân viên hỗ trợ tương tác với người dùng.
Ngôn ngữ mà nhân viên hỗ trợ của bạn thường sử dụng, được quy định theo mã ngôn ngữ ISO 639-1 gồm hai ký tự
Tin nhắn chào mừng của nhân viên hỗ trợ
Nhân viên hỗ trợ sẽ nói gì để chào người dùng?
Câu mở đầu cuộc trò chuyện của nhân viên hỗ trợ
Danh sách các đề xuất, ở dạng khối trò chuyện (như được xác định trong SuggestedReply), để người dùng tương tác với nhân viên hỗ trợ
- Văn bản hiển thị cho người dùng trong khối
- Dữ liệu đăng lại, chuỗi được gửi lại cho webhook của bạn trong tải trọng thông báo nếu người dùng nhấn vào khối
Thời gian trò chuyện tự động và trò chuyện trực tiếp
Thời gian bắt đầu hằng ngày, dưới dạng đối tượng
TimeOfDay
Ví dụ: 8:15 sáng là
{ "hours": 8, "minutes": 15, }
Thời gian kết thúc hằng ngày, dưới dạng đối tượng
TimeOfDay
Ví dụ: 7:30 tối là
{ "hours": 19, "minutes": 30, }
Ngày bắt đầu, ngày đầu tiên trong tuần mà nhân viên hỗ trợ sẵn sàng trò chuyện (như được xác định trong
DayOfWeek
)Ngày kết thúc, ngày cuối cùng trong tuần mà nhân viên hỗ trợ sẵn sàng trò chuyện (như được xác định trong
DayOfWeek
)Múi giờ mà nhân viên hỗ trợ hoạt động (như được xác định trong Cơ sở dữ liệu múi giờ IANA, ví dụ: "Hoa Kỳ/Los_Angeles")
Điểm truy cập của nhân viên hỗ trợ
Thông tin về nơi người dùng có thể bắt đầu trò chuyện với nhân viên hỗ trợ.
Điểm truy cập được phép của nhân viên hỗ trợ, nơi người dùng có thể bắt đầu cuộc trò chuyện với nhân viên hỗ trợ (
NON_LOCAL
và/hoặcLOCATION
)
Thông tin về điểm truy cập NON_LOCAL
(không áp dụng cho điểm truy cập Google Ads).
Các khu vực được phép (dưới dạng mã vùng CLDR), để hạn chế quyền truy cập theo khu vực vào các điểm truy cập
NON_LOCAL
.Bất kể khu vực, một nhân viên hỗ trợ chỉ có thể có một số điện thoại liên kết với tài khoản. Nếu bạn cần một số điện thoại khác nhau theo khu vực, thì bạn phải tạo một nhân viên hỗ trợ khác nhau cho mỗi khu vực.
Để bật các điểm truy cập
NON_LOCAL
ở tất cả các khu vực hiện có, hãy sử dụng001
cho mã khu vực Thế giới.
Cài đặt và kiểm thử oauth2l
Tất cả các yêu cầu curl trong tài liệu của trang web này đều sử dụng oauth2l để xác thực. Nếu bạn muốn sử dụng dòng lệnh để kết nối với API Business Communications và Business Messages, hãy cài đặt oauth2l.
Cách cài đặt oauth2l bằng Python 3,
Tải oauth2l xuống.
Thay đổi thư mục thành "./oauth2l/python".
Cài đặt oauth2l bằng lệnh sau.
sudo python setup.sh build && sudo python setup.py install
Kiểm thử để đảm bảo oauth2l có thể tạo mã thông báo uỷ quyền.
oauth2l header --json resources/bm-agent-service-account-credentials.json businesscommunications
Xác minh rằng đầu ra tạo mã thông báo uỷ quyền ở dạng:
Authorization: Bearer AUTHORIZATION_BEARER_TOKEN
Có nhiều cách khác để cài đặt oauth2l cho các hệ điều hành khác nhau. Bất kể phương thức cài đặt của bạn là gì, hãy đảm bảo rằng bạn có thể tạo mã thông báo uỷ quyền dựa trên thông tin xác thực JSON của tài khoản dịch vụ trước khi tiếp tục.
Tạo tác nhân
Sau khi thu thập thông tin, bạn có thể tạo nhân viên hỗ trợ.
Tạo thương hiệu mà nhân viên hỗ trợ đại diện. Nếu thương hiệu đã tồn tại, hãy lấy
name
của thương hiệu và chuyển sang bước tiếp theo.Trong một thiết bị đầu cuối, hãy chạy lệnh sau:
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
Mã này dựa trên thư viện ứng dụng 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)
Lưu trữ giá trị
name
mà API trả về. Bạn sẽ cần mã này để cập nhật hoặc tạo tác nhân.Để cập nhật hoặc tra cứu thương hiệu, hãy xem
brands
.Tạo tác nhân. Thay thế BRAND_ID bằng phần giá trị
name
của thương hiệu theo sau là "brands/". Ví dụ: nếuname
là "brands/12345", thì mã thương hiệu là "12345".Trong một thiết bị đầu cuối, hãy chạy lệnh sau:
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
Mã này dựa trên thư viện ứng dụng 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)
Để biết các tuỳ chọn định dạng và giá trị, hãy xem
brands.agents
.Nếu thương hiệu có các địa điểm mà bạn muốn liên kết với đại lý, hãy xem phần Thêm địa điểm.
Ví dụ: Tạo một nhân viên hỗ trợ cho Công ty A
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', }, ], }, }, }, }, }"
Lưu trữ thông tin quan trọng
Khi bạn tạo một nhân viên hỗ trợ, API Business Communications sẽ trả về các giá trị của nhân viên hỗ trợ, bao gồm cả name
và testUrls
.
Đặt webhook ở cấp nhân viên hỗ trợ
Bạn sẽ nhận được tin nhắn được gửi đến nhân viên hỗ trợ tại webhook của bạn. Nếu muốn tin nhắn cho một nhân viên hỗ trợ cụ thể đến một webhook khác, bạn có thể đặt webhook ở cấp nhân viên hỗ trợ.
Để thiết lập webhook ở cấp nhân viên hỗ trợ, hãy sử dụng Bảng điều khiển dành cho nhà phát triển.
Kiểm thử một tác nhân
Mỗi nhân viên hỗ trợ đều có URL kiểm thử cho phép bạn xem cách người dùng nhìn thấy cuộc trò chuyện với nhân viên hỗ trợ đó và cho bạn cơ hội xác minh cơ sở hạ tầng nhắn tin.
TestUrl có các thuộc tính url
và surface
.
Để kiểm thử bằng thiết bị iOS, hãy sử dụng URL kiểm thử có giá trị nền là SURFACE_IOS_MAPS
. Khi mở URL trên một thiết bị iOS đã cài đặt ứng dụng Google Maps, bạn sẽ thấy một cuộc trò chuyện có đầy đủ chức năng với nhân viên hỗ trợ.
Thiết bị Android có hai URL thử nghiệm. URL có giá trị surface
là SURFACE_ANDROID_MAPS
sẽ mở cuộc trò chuyện trong Google Maps và đại diện cho các điểm truy cập vào cuộc trò chuyện xuất hiện trong Google Maps. URL có giá trị surface
là SURFACE_ANDROID_WEB
sẽ mở cuộc trò chuyện trong chế độ xem trò chuyện lớp phủ và đại diện cho tất cả các điểm truy cập khác.
Sau khi một nền tảng trò chuyện mở ra, nội dung trò chuyện sẽ bao gồm tất cả thông tin thương hiệu mà người dùng sẽ thấy và khi bạn gửi tin nhắn cho nhân viên hỗ trợ, webhook của bạn sẽ nhận được tin nhắn, bao gồm cả tải trọng JSON đầy đủ mà bạn có thể mong đợi khi giao tiếp với người dùng.
Để mở một URL thử nghiệm của nhân viên hỗ trợ, hãy nhấn vào một đường liên kết hoặc sử dụng Trình chạy nhân viên hỗ trợ thông qua Business Messages trên thiết bị di động.
Nhận thông tin về nhân viên hỗ trợ
Để nhận thông tin về một nhân viên hỗ trợ, chẳng hạn như agentTestUrl
, bạn có thể lấy thông tin từ API Business Communications, miễn là bạn có giá trị name
của nhân viên hỗ trợ.
Xem thông tin về một nhân viên hỗ trợ
Để lấy thông tin về tác nhân, hãy chạy lệnh sau. Thay thế BRAND_ID và AGENT_ID bằng các giá trị duy nhất từ name
của tác nhân.
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)
Liệt kê tất cả nhân viên hỗ trợ cho một thương hiệu
Nếu không biết name
của tác nhân, bạn có thể lấy thông tin cho tất cả tác nhân liên kết với một thương hiệu bằng cách bỏ qua giá trị AGENT_ID khỏi URL yêu cầu GET.
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)
Cập nhật thông tin của nhân viên hỗ trợ
Để cập nhật nhân viên hỗ trợ, bạn thực hiện yêu cầu PATCH bằng API Business Communications. Khi thực hiện lệnh gọi API, bạn sẽ thêm tên của các trường mà bạn đang chỉnh sửa làm giá trị cho tham số URL "updateMask".
Ví dụ: nếu bạn cập nhật các trường displayName
và customAgentId
, thì thông số URL "updateMask" sẽ là "updateMask=displayName,businessMessagesAgent.customAgentId".
Để biết các tuỳ chọn định dạng và giá trị, hãy xem brands.agents.patch
.
Nếu bạn không biết name
của một đại lý, hãy xem phần Liệt kê tất cả đại lý cho một thương hiệu.
Sau khi xác minh một đại lý, bạn chỉ có thể cập nhật các trường sau:
conversationalSetting
customAgentId
defaultLocale
primaryAgentInteraction
additionalAgentInteractions
phone
Nếu bạn cần cập nhật các trường khác sau khi xác minh nhân viên hỗ trợ, hãy liên hệ với chúng tôi. (Trước tiên, bạn phải đăng nhập bằng Tài khoản Google Business Messages. Để đăng ký tài khoản, hãy xem phần Đăng ký bằng Business Messages.)
Ví dụ: Cập nhật tên hiển thị
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)
Ví dụ: Chỉ định nhóm điểm truy cập NON_LOCAL
và 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)
Ví dụ: Cập nhật lời chào
Nếu cập nhật bất kỳ trường nào trong conversationalSettings
(chẳng hạn như welcomeMessage
), bạn phải cập nhật tất cả các trường trong đối tượng và chỉ định ngôn ngữ của chế độ cài đặt (dưới dạng mã ngôn ngữ ISO 639-1 gồm hai ký tự).
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)
Xoá nhân viên hỗ trợ
Khi bạn xoá một nhân viên hỗ trợ, Business Messages sẽ xoá tất cả dữ liệu của nhân viên hỗ trợ đó. Business Messages không xoá những tin nhắn mà nhân viên hỗ trợ của bạn gửi đang trong quá trình chuyển đến hoặc được lưu trữ trên thiết bị của người dùng. Tin nhắn gửi đến người dùng không phải là dữ liệu của nhân viên hỗ trợ.
Yêu cầu xoá sẽ không thành công nếu nhân viên hỗ trợ có vị trí được liên kết hoặc nếu bạn đã cố gắng xác minh nhân viên hỗ trợ một hoặc nhiều lần. Để cập nhật vị trí, hãy xem bài viết Thêm vị trí.
Bạn không thể xoá một nhân viên hỗ trợ đã được xác minh. Để xoá một nhân viên hỗ trợ mà bạn đã xác minh hoặc đã cố gắng xác minh, hãy liên hệ với chúng tôi. (Trước tiên, bạn phải đăng nhập bằng Tài khoản Google Business Messages. Để đăng ký tài khoản, hãy xem phần Đăng ký bằng Business Messages.)
Để xoá một tác nhân, hãy chạy lệnh sau. Thay thế BRAND_ID và AGENT_ID bằng các giá trị duy nhất từ name
của tác nhân.
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)
Để biết các tuỳ chọn định dạng và giá trị, hãy xem brands.agents.delete
.
Xoá thương hiệu
Khi xoá một thương hiệu, bạn sẽ thực hiện một yêu cầu XOÁ bằng API Thông tin liên lạc của doanh nghiệp. Yêu cầu xoá sẽ không thành công nếu bạn có một hoặc nhiều đại lý hoặc vị trí liên kết với thương hiệu, ngay cả khi các đại lý đó thuộc về một sản phẩm khác.
Để xoá một thương hiệu, hãy chạy lệnh sau. Thay thế BRAND_ID bằng giá trị duy nhất từ name
của thương hiệu.
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)
Để biết các tuỳ chọn định dạng và giá trị, hãy xem brands.delete
.
Các bước tiếp theo
Giờ đây, khi đã có một nhân viên hỗ trợ, bạn có thể làm theo các bước sau:
- Thêm vị trí vào nhân viên hỗ trợ
- Thiết kế trải nghiệm trò chuyện
- Phát triển luồng tin nhắn