Después de registrarte como socio, puedes habilitar conversaciones para las marcas que administras creando agentes de Business Messages para ellas.
Un agente es una entidad de conversación con la que interactúan los usuarios. Creas un agente para cada marca que administras. Creas y administras agentes con la API de Business Communications y controlas los mensajes de tus agentes con la API de Business Messages.
Un agente abarca las funciones comerciales de una marca, como la asistencia en línea y las ubicaciones físicas (si las hay). Cada mensaje contiene el contexto desde el que el usuario inició la conversación. Tu infraestructura de enrutamiento de mensajes puede detectar si el usuario vio una ubicación específica de la empresa o buscó asistencia general, y puede enrutar los mensajes al destino correcto.
Por ejemplo, si administras la marca Growing Tree Bank, que tiene un sitio web y dos ubicaciones, creas un solo agente "Growing Tree Bank". Los usuarios pueden encontrar al agente a través de búsquedas generales o basadas en la ubicación, y el contexto en el que el usuario encontró al agente se pasa junto con cada mensaje a tu webhook. Usas ese contexto para enrutar el mensaje al personal de una ubicación o al equipo de asistencia al cliente del sitio web, que crea una respuesta y continúa la conversación con el usuario.
Expectativas
Antes de crear un agente, comprende las expectativas de los agentes en Business Messages.
- Los agentes deben seguir la guía de diseño que se describe en Diseño de conversaciones para Business Messages.
Los agentes deben tener representantes humanos disponibles para responder preguntas cuando la automatización no puede completar una solicitud o cuando los usuarios lo solicitan.
Los agentes deben mantener una calificación de satisfacción del cliente (CSAT) de al menos el 80% y una tasa de respuesta del comercio (MRR) de al menos el 95%, como se describe en Métricas.
Crear un agente
Para crear un agente, debes recopilar y enviar información sobre la marca y cómo deseas que el agente aparezca para los usuarios.
Si administras varias marcas, repite los pasos para crear un agente para cada una.
Requisitos previos
Antes de crear agentes para las marcas que administras, debes recopilar la siguiente información:
Entorno de desarrollo
Información sobre tu entorno de desarrollo
Proyecto de GCP con la API de Business Communications habilitada
Para habilitar la API, consulta Cómo registrarse en Business Messages.
Ruta de acceso a la clave de la cuenta de servicio de tu proyecto de GCP en tu máquina de desarrollo
Detalles de la marca
Información sobre la marca que representa el agente.
- Nombre de la marca
- Sitio web de la marca
- Opciones de contacto en el sitio web (como se define en
OPTION
) - Número de teléfono para el consumidor
- Números de teléfono habilitados para la desviación de llamadas
Políticas y apariencia de los agentes
Información sobre cómo aparece el agente a los usuarios y cómo funciona.
- Es el nombre del agente, tal como quieres que aparezca en las conversaciones con los usuarios.
- Política de privacidad, como una URL disponible públicamente que comience con "https://"
(Recomendado) Logotipo del agente (1,024 x 1,024 px), como una URL de acceso público
En una conversación, los logotipos se muestran como círculos de 1,024 px de diámetro. Asegúrate de que tu logotipo se muestre bien como un círculo.
ID de agente personalizado (opcional), que identifica la marca en los mensajes que recibe el webhook
Interacción con el agente
Información sobre cómo interactúa tu agente con los usuarios.
La configuración regional en la que suele operar tu agente, especificada mediante un código de idioma ISO 639-1 de dos caracteres
Mensaje de bienvenida del agente
¿Qué dice el agente para saludar a los usuarios?
Iniciadores de conversación del agente
Una lista de sugerencias, en forma de chips de conversación (como se define en SuggestedReply), para que el usuario interactúe con el agente
- Es el texto que se muestra al usuario en el chip.
- Datos de notificación de conversión, la cadena que se envía a tu webhook en la carga útil del mensaje si el usuario presiona el chip
Horarios del chat automatizado y en vivo
Hora de inicio diaria, como un objeto
TimeOfDay
Por ejemplo, 8:15 a.m. es
{ "hours": 8, "minutes": 15, }
Hora de finalización diaria, como un objeto
TimeOfDay
Por ejemplo, 7:30 p.m. es
{ "hours": 19, "minutes": 30, }
Día de inicio, el primer día de la semana en que el agente está disponible para chatear (como se define en
DayOfWeek
)Día de finalización, el último día de la semana en que el agente está disponible para chatear (como se define en
DayOfWeek
)Es la zona horaria en la que opera el agente (tal como se define en la base de datos de zonas horarias de IANA, por ejemplo, "America/Los_Angeles").
Puntos de entrada del agente
Información sobre dónde los usuarios pueden iniciar conversaciones con el agente.
Puntos de entrada permitidos del agente, en los que los usuarios pueden iniciar conversaciones con los agentes (
NON_LOCAL
oLOCATION
)
Información sobre los puntos de entrada de NON_LOCAL
(no se aplica al punto de entrada de Google Ads).
Son las regiones permitidas (como códigos regionales de CLDR) para restringir el acceso regional a los puntos de entrada de
NON_LOCAL
.Independientemente de la región, un agente solo puede tener un número de teléfono asociado. Si necesitas un número de teléfono diferente según la región, se debe crear un agente diferente para cada región.
Para habilitar los puntos de entrada
NON_LOCAL
en todas las regiones disponibles, usa001
para el código de región mundial.
Instala y prueba oauth2l
Todas las solicitudes de curl en la documentación de este sitio usan oauth2l para la autenticación. Si deseas usar la línea de comandos para conectarte con las APIs de Business Communications y Business Messages, instala oauth2l.
Para instalar oauth2l con Python 3, haz lo siguiente:
Descarga oauth2l.
Cambia el directorio a "./oauth2l/python".
Instala oauth2l con el siguiente comando.
sudo python setup.sh build && sudo python setup.py install
Prueba que oauth2l pueda generar un token de autorización.
oauth2l header --json resources/bm-agent-service-account-credentials.json businesscommunications
Verifica que el resultado cree un token de autorización del siguiente formato:
Authorization: Bearer AUTHORIZATION_BEARER_TOKEN
Existen otras formas de instalar oauth2l para diferentes sistemas operativos. Independientemente del método de instalación, asegúrate de poder generar un token de autorización basado en las credenciales JSON de la cuenta de servicio antes de continuar.
Crea el agente
Una vez que hayas recopilado la información, es hora de crear tu agente.
Crea la marca que representa el agente. Si la marca ya existe, obtén su
name
y continúa con el siguiente paso.En una terminal, ejecuta el siguiente comando:
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
Este código se basa en la biblioteca cliente de comunicaciones de negocios de 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.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)
Almacena el valor
name
que muestra la API. La necesitarás para realizar actualizaciones o crear agentes.Para actualizar o buscar marcas, consulta
brands
.Crea el agente. Reemplaza BRAND_ID por la parte del valor
name
de la marca que sigue a "brands/". Por ejemplo, siname
es "brands/12345", el ID de la marca es "12345".En una terminal, ejecuta el siguiente comando:
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
Este código se basa en la biblioteca cliente de comunicaciones de negocios de 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.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)
Para conocer las opciones de formato y valor, consulta
brands.agents
.Si la marca tiene ubicaciones que deseas asociar con tu agente, consulta Cómo agregar ubicaciones.
Ejemplo: Crea un agente para 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', }, ], }, }, }, }, }"
Almacena información importante
Cuando creas un agente, la API de Business Communications muestra los valores de tu agente, incluidos name
y testUrls
.
Configura un webhook a nivel del agente
Recibirás los mensajes que se envíen a tu agente en tu webhook. Si quieres que los mensajes de un agente específico lleguen a un webhook diferente, puedes configurar un webhook a nivel del agente.
Para configurar un webhook a nivel del agente, usa la consola de desarrollador.
Prueba un agente
Cada agente tiene URLs de prueba que te permiten ver cómo les aparece una conversación con ese agente a los usuarios y te brindan la oportunidad de verificar tu infraestructura de mensajería.
Un TestUrl tiene atributos url
y surface
.
Para realizar pruebas con un dispositivo iOS, usa la URL de prueba con un valor de superficie de SURFACE_IOS_MAPS
. Si abres la URL en un dispositivo iOS que tenga instalada la app de Google Maps,
se abrirá una conversación completamente funcional con el agente.
Los dispositivos Android tienen dos URLs de prueba. Las URLs con un valor de surface
de SURFACE_ANDROID_MAPS
abren conversaciones en Google Maps y representan los puntos de entrada de conversación que aparecen en Google Maps. Las URLs con un valor de surface
de SURFACE_ANDROID_WEB
abren conversaciones en una vista de conversación superpuesta y representan todos los demás puntos de entrada.
Una vez que se abre una plataforma de conversación, la conversación incluye toda la información de desarrollo de la marca que verían los usuarios y, cuando envías un mensaje al agente, tu webhook recibe el mensaje, incluida la carga útil de JSON completa que puedes esperar cuando te comunicas con los usuarios.
Para abrir la URL de prueba de un agente, presiona un vínculo o usa el Agent Launcher de Business Messages en un dispositivo móvil.
Cómo obtener información del agente
Para obtener información sobre un agente, como agentTestUrl
, puedes obtenerla de la API de Business Communications, siempre que tengas el valor name
del agente.
Cómo obtener información de un solo agente
Para obtener información del agente, ejecuta el siguiente comando. Reemplaza BRAND_ID y AGENT_ID por los valores únicos del name
del agente.
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)
Cómo mostrar una lista de todos los agentes de una marca
Si no conoces el name
del agente, puedes obtener información de todos los agentes asociados con una marca si omites el valor AGENT_ID de una URL de solicitud 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)
Actualiza la información del agente
Para actualizar un agente, realiza una solicitud PATCH con la API de Business Communications. Cuando realices la llamada a la API, incluye los nombres de los campos que estás editando como valores para el parámetro de URL "updateMask".
Por ejemplo, si actualizas los campos displayName
y customAgentId
, el parámetro de URL "updateMask" es "updateMask=displayName,businessMessagesAgent.customAgentId".
Para conocer las opciones de formato y valor, consulta brands.agents.patch
.
Si no conoces el name
de un agente, consulta Cómo ver una lista de todos los agentes de una marca.
Después de verificar un agente, solo puedes actualizar los siguientes campos:
conversationalSetting
customAgentId
defaultLocale
primaryAgentInteraction
additionalAgentInteractions
phone
Si necesitas actualizar otros campos después de verificar tu agente, comunícate con nosotros. (Primero debes acceder con una Cuenta de Google de Business Messages). Para registrarte, consulta Cómo registrarse con Mensajes para Negocio.
Ejemplo: Actualiza el nombre visible
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)
Ejemplo: Especifica grupos de puntos de entrada NON_LOCAL
y 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)
Ejemplo: Actualiza el mensaje de bienvenida
Si actualizas cualquier campo dentro de conversationalSettings
, como welcomeMessage
, debes actualizar todos los campos dentro del objeto y especificar la configuración regional (como un código de idioma ISO 639-1 de dos caracteres).
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)
Borra un agente
Cuando borras un agente, Business Messages borra todos sus datos. Business Messages no borra los mensajes que envía tu agente que están en tránsito hacia el dispositivo de un usuario o almacenados en él. Los mensajes a los usuarios no son datos del agente.
Las solicitudes de eliminación fallan si el agente tiene una ubicación asociada o si intentaste verificarlo una o más veces. Para actualizar las ubicaciones, consulta Cómo agregar ubicaciones.
No puedes borrar un agente verificado. Para borrar un agente que verificaste o intentaste verificar, comunícate con nosotros. (Primero debes acceder con una Cuenta de Google de Business Messages). Para registrarte, consulta Cómo registrarse con Mensajes para Negocio.
Para borrar un agente, ejecuta el siguiente comando. Reemplaza BRAND_ID y AGENT_ID por los valores únicos del name
del agente.
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)
Para conocer las opciones de formato y valor, consulta brands.agents.delete
.
Cómo borrar una marca
Cuando borras una marca, realizas una solicitud DELETE con la API de Business Communications. Las solicitudes de eliminación fallan si tienes uno o más agentes o ubicaciones asociados con la marca, incluso si esos agentes pertenecen a un producto diferente.
Para borrar una marca, ejecuta el siguiente comando. Reemplaza BRAND_ID por el valor único del name
de la marca.
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)
Para conocer las opciones de formato y valor, consulta brands.delete
.
Próximos pasos
Ahora que tienes un agente, puedes seguir estos pasos: