Agrega automatización con Dialogflow

Dialogflow es una herramienta de comprensión del lenguaje natural (CLN) que procesa las entradas del usuario, las mapea a intents conocidos y responde con las respuestas adecuadas. Hay dos ediciones de Dialogflow. Si integras tu agente de Business Messages con Dialogflow ES, puedes crear una automatización simple para iniciar el desarrollo de tu agente con facilidad. Mediante la integración con Dialogflow CX, puedes crear una automatización avanzada para conversaciones más complejas.

Los agentes de Business Messages admiten integraciones directas con

Para integrar un agente de Business Messages con otras funciones de Dialogflow ES o Dialogflow CX, consulta la documentación de cada producto.

Cuando un usuario envía un mensaje a un agente que tiene una integración de Dialogflow, Business Messages pasa el mensaje del usuario a Dialogflow y envía la respuesta de Dialogflow al agente en el objeto dialogflowResponse del mensaje. Puedes configurar agentes para que envíen automáticamente la respuesta de Dialogflow al usuario sin que tengas que realizar ninguna acción. Consulta Respuestas automáticas para obtener más detalles.

Integración en Dialogflow

Para poder aprovechar la automatización basada en Dialogflow a través de Business Messages, debes habilitar la integración de Dialogflow.

Requisitos previos

Para comenzar, necesita

  • un agente de Business Messages
  • un agente de Dialogflow en la región global, con un idioma raíz en inglés (en)

Si no tienes un agente de Dialogflow, crea uno.

Dialogflow ES

Para habilitar una integración de Dialogflow ES, necesitas el ID del proyecto del agente de Dialogflow. Para encontrar el ID del proyecto, haz lo siguiente:

  1. Navega a la consola de Dialogflow.
  2. Selecciona el agente de Dialogflow que deseas conectar a Business Messages y haz clic en el ícono de ajustes junto al nombre del agente.
  3. En Proyecto de Google, anota el valor ID del proyecto.

Dialogflow CX

Para habilitar una integración de Dialogflow CX, necesitas el ID del proyecto y del agente de Dialogflow. Para ubicar estos ID,

  1. Navega a la consola de Dialogflow CX.
  2. Selecciona tu proyecto de Dialogflow.
  3. En el selector de agentes, haz clic en el menú ampliado junto a tu agente de Dialogflow.
  4. Haz clic en Copiar nombre. Esto copia el nombre completo de tu agente en el siguiente formato: projects/PROJECT_ID/locations/REGION_ID/agents/AGENT_ID.
  5. Anota los valores del ID del proyecto y del agente.

Crea la integración

  1. Obtén el correo electrónico de la cuenta de servicio de Dialogflow del socio de dialogflowServiceAccountEmail. Reemplaza PARTNER_ID por tu ID de socio.

    cURL

    
    # This code gets the partner.
    # Read more: https://developers.google.com/business-communications/business-messages/reference/business-communications/rest/v1/partners/get
    
    # Replace the __PARTNER_ID__
    # Make sure a service account key file exists at ./service_account_key.json
    
    curl -X GET \
    "https://businesscommunications.googleapis.com/v1/partners/__PARTNER_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 a partner.
     * Read more: https://developers.google.com/business-communications/business-messages/reference/business-communications/rest/v1/partners/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 PARTNER_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 partnerName = 'partners/' + PARTNER_ID;
    
       if (authClient) {
         // Setup the parameters for the API call
         const apiParams = {
           auth: authClient,
           name: partnerName,
         };
    
         bcApi.partners.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();
    

    Python

    
    """This code gets a partner.
    
    Read more: https://developers.google.com/business-communications/business-messages/reference/business-communications/rest/v1/partners/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,
        BusinesscommunicationsPartnersGetRequest,
    )
    
    # Edit the values below:
    PARTNER_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)
    
    partners_service = BusinesscommunicationsV1.PartnersService(client)
    
    partner_name = 'partners/' + PARTNER_ID
    
    partner = partners_service.Get(BusinesscommunicationsPartnersGetRequest(
            name=partner_name
        ))
    
    print(partner)
    
  2. Copia el correo electrónico de la cuenta de servicio. Esta cuenta conecta tus agentes de Business Messages y Dialogflow.

  3. En Google Cloud Console, selecciona tu proyecto de Dialogflow.

  4. Navega a los permisos de IAM.

  5. Haz clic en Agregar y, luego, ingresa el correo electrónico de la cuenta de servicio de Nuevos miembros.

  6. En Selecciona una función, selecciona Editor de agentes de la consola de Dialogflow.

  7. Haz clic en Agregar otra función y selecciona Cliente de la API de Dialogflow.

  8. Haz clic en Guardar.

  9. Integra tu proyecto de Dialogflow a tu agente de Business Messages.

    Reemplaza AUTO_RESPONSE_STATUS por ENABLED o DISABLED, según desees o no que Business Messages responda automáticamente a los usuarios con respuestas de Dialogflow.

    Dialogflow ES

    cURL

    
    # This code creates a Dialogflow ES integration.
    # Read more: https://developers.google.com/business-communications/business-messages/guides/how-to/integrate/dialogflow?method=api#dialogflow_es
    
    # Replace the __BRAND_ID__, __AGENT_ID__, __DIALOGFLOW_ES_PROJECT_ID__ and __AUTO_RESPONSE_STATUS__
    # 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/__AGENT_ID__/integrations" \
    -H "$(oauth2l header --json ./service_account_key.json businesscommunications)" \
    -H "Content-Type: application/json"  \
    -H "User-Agent: curl/business-communications" \
    -d '{
       "dialogflowEsIntegration": {
         "dialogflowProjectId": "__DIALOGFLOW_ES_PROJECT_ID__",
         "autoResponseStatus": "__AUTO_RESPONSE_STATUS__"
       }
    }'
    

    Node.js

    
    /**
     * This code snippet creates a Dialogflow ES integration.
     * Read more: https://developers.google.com/business-communications/business-messages/guides/how-to/integrate/dialogflow?method=api#dialogflow_es
     *
     * 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 DIALOGFLOW_ES_PROJECT_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 agentName = 'brands/' + BRAND_ID + '/agents/' + AGENT_ID;
    
       if (authClient) {
         const integrationObject = {
           dialogflowEsIntegration: {
             dialogflowProjectId: DIALOGFLOW_ES_PROJECT_ID,
             autoResponseStatus: 'ENABLED'
           }
         };
    
         // Setup the parameters for the API call
         const apiParams = {
           auth: authClient,
           parent: agentName,
           resource: integrationObject
         };
    
         bcApi.brands.agents.integrations.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();
    

    Python

    
    """This code snippet creates a Dialogflow ES integration.
    
    Read more: https://developers.google.com/business-communications/business-messages/guides/how-to/integrate/dialogflow?method=api#dialogflow_es
    
    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 (
        BusinesscommunicationsBrandsAgentsIntegrationsCreateRequest,
        DialogflowEsIntegration
    )
    
    # Edit the values below:
    BRAND_ID = 'EDIT_HERE'
    AGENT_ID = 'EDIT_HERE'
    DIALOGFLOW_ES_PROJECT_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)
    
    integrations_service = BusinesscommunicationsV1.BrandsAgentsIntegrationsService(client)
    
    agent_name = 'brands/' + BRAND_ID + '/agents/' + AGENT_ID
    
    integration = integrations_service.Create(BusinesscommunicationsBrandsAgentsIntegrationsCreateRequest(
      integration=DialogflowEsIntegration(
        autoResponseStatus=DialogflowEsIntegration.AutoResponseStatusValueValuesEnum.ENABLED,
        dialogflowProjectId=DIALOGFLOW_ES_PROJECT_ID
      ),
      parent=agent_name
    ))
    
    print(integration)
    

    Dialogflow CX

    cURL

    
    # This code creates a Dialogflow CX integration.
    # Read more: https://developers.google.com/business-communications/business-messages/guides/how-to/integrate/dialogflow?method=api#dialogflow_cx
    
    # Replace the __BRAND_ID__, __AGENT_ID__, __DIALOGFLOW_CX_PROJECT_ID__, __DIALOGFLOW_CX_AGENT_ID__ and __AUTO_RESPONSE_STATUS__
    # 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/__AGENT_ID__/integrations" \
    -H "$(oauth2l header --json ./service_account_key.json businesscommunications)" \
    -H "Content-Type: application/json"  \
    -H "User-Agent: curl/business-communications" \
    -d '{
       "dialogflowCxIntegration": {
         "dialogflowProjectId": "__DIALOGFLOW_CX_PROJECT_ID__",
         "dialogflowAgentId": "__DIALOGFLOW_CX_AGENT_ID__",
         "autoResponseStatus": "__AUTO_RESPONSE_STATUS__"
       }
    }'
    

    Node.js

    
    /**
     * This code snippet creates a Dialogflow CX integration.
     * Read more: https://developers.google.com/business-communications/business-messages/guides/how-to/integrate/dialogflow?method=api#dialogflow_cx
     *
     * 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 DIALOGFLOW_CX_AGENT_ID = 'EDIT_HERE'
    const DIALOGFLOW_CX_PROJECT_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 agentName = 'brands/' + BRAND_ID + '/agents/' + AGENT_ID;
    
      if (authClient) {
        const integrationObject = {
          dialogflowCxIntegration: {
            dialogflowProjectId: DIALOGFLOW_CX_PROJECT_ID,
            dialogflowAgentId: DIALOGFLOW_CX_AGENT_ID,
            autoResponseStatus: 'ENABLED'
          }
        };
    
        // Setup the parameters for the API call
        const apiParams = {
          auth: authClient,
          parent: agentName,
          resource: integrationObject
        };
    
        bcApi.brands.agents.integrations.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();
    

    Python

    
    """This code snippet creates a Dialogflow CX integration.
    
    Read more: https://developers.google.com/business-communications/business-messages/guides/how-to/integrate/dialogflow?method=api#dialogflow_cx
    
    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 (
        BusinesscommunicationsBrandsAgentsIntegrationsCreateRequest,
        DialogflowCxIntegration
    )
    
    # Edit the values below:
    BRAND_ID = 'EDIT_HERE'
    AGENT_ID = 'EDIT_HERE'
    DIALOGFLOW_CX_AGENT_ID = 'EDIT_HERE'
    DIALOGFLOW_CX_PROJECT_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)
    
    integrations_service = BusinesscommunicationsV1.BrandsAgentsIntegrationsService(client)
    
    agent_name = 'brands/' + BRAND_ID + '/agents/' + AGENT_ID
    
    integration = integrations_service.Create(BusinesscommunicationsBrandsAgentsIntegrationsCreateRequest(
      integration=DialogflowCxIntegration(
        autoResponseStatus=DialogflowCxIntegration.AutoResponseStatusValueValuesEnum.ENABLED,
        dialogflowAgentId=DIALOGFLOW_CX_AGENT_ID,
        dialogflowProjectId=DIALOGFLOW_CX_PROJECT_ID
      ),
      parent=agent_name
    ))
    
    print(integration)
    

    Para ver las opciones de formato y de valor, consulta Integration.

La conexión de Business Messages y Dialogflow tarda aproximadamente dos minutos. Para verificar el estado de la integración, obtén el OperationInfo de la integración.

Actualiza la integración

Para actualizar la configuración de respuesta automática de tu agente, ejecuta el siguiente comando. Reemplaza AUTO_RESPONSE_STATUS por ENABLED o DISABLED en función de si deseas o no que Business Messages responda automáticamente a los usuarios con respuestas de Dialogflow.

Dialogflow ES

cURL


# This code updates the Dialogflow association.
# Read more: https://developers.google.com/business-communications/business-messages/reference/business-communications/rest/v1/brands.agents/updateDialogflowAssociation

# Replace the __BRAND_ID__ and __AGENT_ID__
# Make sure a service account key file exists at ./service_account_key.json

curl -X PATCH \
"https://businesscommunications.googleapis.com/v1/brands/__BRAND_ID__/agents/__AGENT_ID__/dialogflowAssociation?updateMask=enableAutoResponse" \
-H "Content-Type: application/json" \
-H "User-Agent: curl/business-communications" \
-H "$(oauth2l header --json ./service_account_key.json businesscommunications)" \
-d '{
  "enableAutoResponse": true
}'

Dialogflow CX

cURL


# This code updates the Dialogflow association.
# Read more: https://developers.google.com/business-communications/business-messages/reference/business-communications/rest/v1/brands.agents/updateDialogflowAssociation

# Replace the __BRAND_ID__ and __AGENT_ID__
# Make sure a service account key file exists at ./service_account_key.json

curl -X PATCH \
"https://businesscommunications.googleapis.com/v1/brands/__BRAND_ID__/agents/__AGENT_ID__/dialogflowAssociation?updateMask=enableAutoResponse" \
-H "Content-Type: application/json" \
-H "User-Agent: curl/business-communications" \
-H "$(oauth2l header --json ./service_account_key.json businesscommunications)" \
-d '{
  "enableAutoResponse": true
}'

Para ver las opciones de formato y de valor, consulta Integration.

Cambia entre las ediciones de Dialogflow

Un agente de Business Messages solo puede admitir una integración de Dialogflow a la vez. Para cambiar de una edición de Dialogflow a otra, debes quitar la integración actual antes de crear la nueva.

Borrar la integración

Si necesitas quitar Dialogflow de tu agente de Business Messages, borra la integración con el siguiente comando.

cURL


# This code deletes an integration.
# Read more: https://developers.google.com/business-communications/business-messages/guides/how-to/integrate/dialogflow?method=api#delete_the_integration

# Replace the __BRAND_ID__, __AGENT_ID__ and __INTEGRATION_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__/integrations/__INTEGRATION_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 integration.
 * Read more: https://developers.google.com/business-communications/business-messages/guides/how-to/integrate/dialogflow?method=api#delete_the_integration
 *
 * 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 INTEGRATION_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 integrationName = 'brands/' + BRAND_ID + '/agents/' + AGENT_ID + '/integrations/' + INTEGRATION_ID;

   if (authClient) {
     // Setup the parameters for the API call
     const apiParams = {
       auth: authClient,
       name: integrationName,
     };

     bcApi.brands.agents.integrations.delete(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();

Python


"""This code snippet deletes an integration.

Read more: https://developers.google.com/business-communications/business-messages/guides/how-to/integrate/dialogflow?method=api#delete_the_integration

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 (
    BusinesscommunicationsBrandsAgentsIntegrationsDeleteRequest
)

# Edit the values below:
BRAND_ID = 'EDIT_HERE'
AGENT_ID = 'EDIT_HERE'
INTEGRATION_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)

integrations_service = BusinesscommunicationsV1.BrandsAgentsIntegrationsService(client)

integration_name = 'brands/' + BRAND_ID + '/agents/' + AGENT_ID + '/integrations/' + INTEGRATION_ID

integration = integrations_service.Delete(BusinesscommunicationsBrandsAgentsIntegrationsDeleteRequest(
  name=integration_name
))

print(integration)

Para ver las opciones de formato y de valor, consulta Integration.

Obtener información de integración

Para obtener información sobre una integración, puedes usar la API de Business Communications, siempre y cuando tengas el valor name de la integración.

Obtén información sobre una sola integración

Para obtener información de integración, ejecuta el siguiente comando.

cURL


# This code gets information about an integration.
# Read more: https://developers.google.com/business-communications/business-messages/guides/how-to/integrate/dialogflow?method=api#get_info_for_a_single_integration

# Replace the __BRAND_ID__, __AGENT_ID__ and __INTEGRATION_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__/integrations/__INTEGRATION_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 information about an integration.
 * Read more: https://developers.google.com/business-communications/business-messages/guides/how-to/integrate/dialogflow?method=api#get_info_for_a_single_integration
 *
 * 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 INTEGRATION_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 integrationName = 'brands/' + BRAND_ID + '/agents/' + AGENT_ID + '/integrations/' + INTEGRATION_ID;

   if (authClient) {
     // Setup the parameters for the API call
     const apiParams = {
       auth: authClient,
       name: integrationName,
     };

     bcApi.brands.agents.integrations.get(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();

Python


"""This code snippet gets information about an integration.

Read more: https://developers.google.com/business-communications/business-messages/guides/how-to/integrate/dialogflow?method=api#get_info_for_a_single_integration

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 (
    BusinesscommunicationsBrandsAgentsIntegrationsDeleteRequest
)

# Edit the values below:
BRAND_ID = 'EDIT_HERE'
AGENT_ID = 'EDIT_HERE'
INTEGRATION_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)

integrations_service = BusinesscommunicationsV1.BrandsAgentsIntegrationsService(client)

integration_name = 'brands/' + BRAND_ID + '/agents/' + AGENT_ID + '/integrations/' + INTEGRATION_ID

integration = integrations_service.Get(BusinesscommunicationsBrandsAgentsIntegrationsDeleteRequest(
  name=integration_name
))

print(integration)

Para ver las opciones de formato y de valor, consulta Integration.

Enumerar todas las integraciones de un agente

Si no conoces el nombre de la integración, puedes obtener información para todas las integraciones asociadas con un agente si omites el valor INTEGRATION_ID de una URL de solicitud GET.

cURL


# This code lists all integrations for an agent.
# Read more: https://developers.google.com/business-communications/business-messages/guides/how-to/integrate/dialogflow?method=api#list_all_integrations_for_an_agent

# 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__/integrations" \
-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 all integrations for an agent.
 * Read more: https://developers.google.com/business-communications/business-messages/guides/how-to/integrate/dialogflow?method=api#list_all_integrations_for_an_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 AGENT_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();

   if (authClient) {
     // Setup the parameters for the API call
     const apiParams = {
       auth: authClient,
       parent: 'brands/' + BRAND_ID + '/agents/' + AGENT_ID,
     };

     bcApi.brands.agents.integrations.list(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();

Python


"""This code snippet lists all integrations for an agent.

Read more: https://developers.google.com/business-communications/business-messages/guides/how-to/integrate/dialogflow?method=api#list_all_integrations_for_an_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 (
    BusinesscommunicationsBrandsAgentsIntegrationsListRequest
)

# 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)

integrations_service = BusinesscommunicationsV1.BrandsAgentsIntegrationsService(client)

agent_name = 'brands/' + BRAND_ID + '/agents/' + AGENT_ID

integration = integrations_service.List(
  BusinesscommunicationsBrandsAgentsIntegrationsListRequest(parent=agent_name)
)

print(integration)

Para ver las opciones de formato y de valor, consulta Integration.

Coincidencia de intents

Después de habilitar la integración de Dialogflow para un agente de Business Messages, este puede usar los intents configurados de tu proyecto de Dialogflow a fin de comprender y responder las preguntas de los usuarios sin tener que escribir código. Para obtener más información sobre los intents, consulta la documentación de Dialogflow ES y Dialogflow CX.

Configura tus intents de Dialogflow para cada opción de conversación que quieras admitir mediante la automatización. Los agentes de Business Messages confían en Dialogflow para comprender los mensajes de los usuarios.

Cuando llamas a las API de Dialogflow, Business Messages pasa la carga útil de mensaje del usuario a tus intents y tu webhook de entrega. Cuando un mensaje de usuario coincide con un intent, puedes acceder a esta carga útil en formato Struct en el campo business_messages_payload dentro de QueryParameters.

La carga útil contiene todos los campos del mensaje del usuario, excepto DialogflowResponse.

Para Dialogflow CX, Business Messages también pasa un parámetro de sesión llamado channel con el valor google_business_messages a tus intents, y puedes hacer referencia a él en tu agente con el siguiente formato: $session.params.channel.

Este parámetro se puede usar para agregar condicionales a tus entregas de Dialogflow a fin de admitir varios canales en el mismo agente de Dialogflow.

Para obtener más información sobre los parámetros de consulta, consulta las referencias de Dialogflow ES y Dialogflow CX.

Requisitos previos

Cuando creas modelos de CLN dentro de Dialogflow, puedes configurar diferentes tipos de respuesta para un intent. Business Messages admite la respuesta predeterminada, que puede incluir lo siguiente:

  • Texto
  • Carga útil personalizada
  • Transferencia de agente en vivo (solo Dialogflow CX)

Una carga útil personalizada debe coincidir con un objeto de respuesta de mensaje JSON de Business Messages válido. Cuando configuras respuestas de carga útil personalizadas para un intent, Business Messages ignora los siguientes campos:

  • name
  • messageId
  • representative

Consulta las siguientes respuestas de ejemplo.

Texto con sugerencias

{
  "text": "Hello World!",
  "fallback": "Hello World!\n\nReply with \"Hello\" or \"Hi!\"",
  "suggestions": [
    {
      "reply": {
        "text": "Hello",
        "postbackData": "hello-formal"
      }
    },
    {
      "reply": {
        "text": "Hi!",
        "postbackData": "hello-informal"
      }
    }
  ]
}

Tarjeta enriquecida

{
  "fallback": "Hello, world!\nSent with Business Messages\n\nReply with \"Suggestion #1\" or \"Suggestion #2\"",
  "richCard": {
    "standaloneCard": {
      "cardContent": {
        "title": "Hello, world!",
        "description": "Sent with Business Messages.",
        "media": {
          "height": "TALL",
          "contentInfo":{
            "altText": "Google logo",
            "fileUrl": "https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png",
            "forceRefresh": "false"
          }
        },
        "suggestions": [
          {
            "reply": {
              "text": "Suggestion #1",
              "postbackData": "suggestion_1"
            }
          },
          {
            "reply": {
              "text": "Suggestion #2",
              "postbackData": "suggestion_2"
            }
          }
        ]
      }
    }
  }
}
{
  "fallback": "Card #1\nThe description for card #1\n\nCard #2\nThe description for card #2\n\nReply with \"Card #1\" or \"Card #2\"",
  "richCard": {
    "carouselCard": {
      "cardWidth": "MEDIUM",
      "cardContents": [
        {
          "title": "Card #1",
          "description": "The description for card #1",
          "suggestions": [
            {
              "reply": {
                "text": "Card #1",
                "postbackData": "card_1"
              }
            }
          ],
          "media": {
            "height": "MEDIUM",
            "contentInfo": {
              "fileUrl": "https://my.files/cute-dog.jpg",
              "forceRefresh": false
            }
          }
        },
        {
          "title": "Card #2",
          "description": "The description for card #2",
          "suggestions": [
            {
              "reply": {
                "text": "Card #2",
                "postbackData": "card_2"
              }
            }
          ],
          "media": {
            "height": "MEDIUM",
            "contentInfo": {
              "fileUrl": "https://my.files/elephant.jpg",
              "forceRefresh": false
            }
          }
        }
      ]
    }
  }
}

Transferencia del agente humano

{
  "metadata": {}
}

Preguntas frecuentes sobre bots

Después de habilitar una integración de Dialogflow ES para un agente de Business Messages, puedes crear un bot de Preguntas frecuentes. Cuando proporcionas preguntas y respuestas como un documento de conocimiento compatible, Business Messages y Dialogflow crean la infraestructura necesaria para comprender y responder las preguntas de los usuarios sin tener que escribir código.

Para ver un bot de Preguntas frecuentes en funcionamiento, chatea con el bot de Preguntas frecuentes de Business Messages.

Requisitos previos

Antes de crear un bot de preguntas frecuentes, necesitas tus preguntas y respuestas como un documento de conocimiento (50 MB como máximo): un archivo HTML disponible públicamente o un archivo CSV.

En general, los documentos de conocimiento

  • Puede incluir Markdown limitado en las respuestas, como se especifica en Texto enriquecido.
  • Tener un tamaño máximo de 50 MB
  • No debe exceder los 2,000 pares de preguntas y respuestas.
  • No contestes preguntas duplicadas con respuestas diferentes.

Para los archivos HTML,

  • Para que los archivos de las URL públicas existan en el índice de búsqueda, el indexador de Búsqueda de Google debe haberlos rastreado. Puedes verificar esto con Google Search Console. Ten en cuenta que el indexador no mantiene actualizado tu contenido. Debes actualizar tu documento de forma explícita cuando cambie el contenido fuente.
  • Dialogflow quita las etiquetas HTML del contenido cuando se crean respuestas. Debido a esto, es mejor evitar las etiquetas HTML y usar texto sin formato siempre que sea posible.
  • No se admiten archivos con un solo par de preguntas y respuestas.

Para archivos CSV,

  • Los archivos deben tener preguntas en la primera columna y respuestas en la segunda, sin encabezado.
  • Los archivos deben usar comas como delimitadores.

Cómo crear un bot de preguntas frecuentes

Para crear un bot de preguntas frecuentes, primero crea una base de conocimiento a fin de almacenar todos los datos del bot y, luego, agrega uno o más documentos con pares de preguntas y respuestas a tu base de conocimiento.

Crear una base de conocimiento

Para crear una base de conocimiento, ejecuta el siguiente comando. Reemplaza BRAND_ID, AGENT_ID y INTEGRATION_ID por los valores únicos del name del documento. Reemplaza KNOWLEDGE_BASE_DISPLAY_NAME por una string de identificación de tu elección.

Después de crear una base de conocimiento, puedes crear documentos dentro de ella.

cURL


# This code creates a knowledge base.
# Read more: https://developers.google.com/business-communications/business-messages/guides/how-to/integrate/dialogflow?method=api#create-knowledge-base

# Replace the __BRAND_ID__, __AGENT_ID__, __INTEGRATION_ID__ and __KNOWLEDGE_BASE_DISPLAY_NAME__
# Make sure a service account key file exists at ./service_account_key.json

curl -X PATCH \
"https://businesscommunications.googleapis.com/v1/brands/__BRAND_ID__/agents/__AGENT_ID__/integrations/__INTEGRATION_ID__?updateMask=dialogflowEsIntegration.dialogflowKnowledgeBases" \
-H "Content-Type: application/json" \
-H "User-Agent: curl/business-communications" \
-H "$(oauth2l header --json ./service_account_key.json businesscommunications)" \
-d '{
  "dialogflowEsIntegration": {
    "dialogflowKnowledgeBases": [
      {
        "displayName": "__KNOWLEDGE_BASE_DISPLAY_NAME__"
      }
    ]
  }
}'

Para ver las opciones de formato y de valor, consulta DialogflowKnowledgebase.

Crea un documento de conocimiento

Para crear un documento de conocimiento, ejecuta el siguiente comando.

Agrega el documento a la lista de documentos existentes o crea una lista nueva si aún no existe. Una lista de documentos existentes debe incluir el valor name del documento en la solicitud.

Archivo HTML público

Reemplaza las siguientes variables:

  • BRAND_ID, AGENT_ID y INTEGRATION_ID con los valores únicos de la name de la integración
  • KNOWLEDGE_BASE_DISPLAY_NAME y DOCUMENT_DISPLAY_NAME con strings de identificación que elijas
  • PUBLIC_URL por la URL pública del documento

cURL


# This code creates a knowledge base document from an HTML document and adds it to the knowledge base.
# Read more: https://developers.google.com/business-communications/business-messages/guides/how-to/integrate/dialogflow?method=api#create-document

# Replace the __BRAND_ID__, __AGENT_ID__, __INTEGRATION_ID__, __KNOWLEDGE_BASE_DISPLAY_NAME__, __DOCUMENT_DISPLAY_NAME__ and __PUBLIC_URL__
# Make sure a service account key file exists at ./service_account_key.json

curl -X PATCH \
"https://businesscommunications.googleapis.com/v1/brands/__BRAND_ID__/agents/__AGENT_ID__/integrations/__INTEGRATION_ID__?updateMask=dialogflowEsIntegration.dialogflowKnowledgeBases" \
-H "Content-Type: application/json" \
-H "User-Agent: curl/business-communications" \
-H "$(oauth2l header --json ./service_account_key.json businesscommunications)" \
-d '{
  "dialogflowEsIntegration": {
    "dialogflowKnowledgeBases": [
      {
        "displayName": "__KNOWLEDGE_BASE_DISPLAY_NAME__",
        "documents": [
          {
            "displayName": "__DOCUMENT_DISPLAY_NAME__",
            "faqUrl": "__PUBLIC_URL__"
          }
        ]
      }
    ]
  }
}'

Archivo CSV local

Reemplaza las siguientes variables:

  • BRAND_ID, AGENT_ID y INTEGRATION_ID con los valores únicos de la name de la integración
  • KNOWLEDGE_BASE_DISPLAY_NAME y DOCUMENT_DISPLAY_NAME con strings de identificación que elijas
  • CSV_RAW_BYTES por el archivo CSV como una string codificada en base64

cURL


# This code creates a knowledge base document from a CSV document and adds it to the knowledge base.
# Read more: https://developers.google.com/business-communications/business-messages/guides/how-to/integrate/dialogflow?method=api#create-document

# Replace the __BRAND_ID__, __AGENT_ID__, __INTEGRATION_ID__, __KNOWLEDGE_BASE_DISPLAY_NAME__, __DOCUMENT_DISPLAY_NAME__ and __CSV_RAW_BYTES__
# Make sure a service account key file exists at ./service_account_key.json

curl -X PATCH \
"https://businesscommunications.googleapis.com/v1/brands/__BRAND_ID__/agents/__AGENT_ID__/integrations/__INTEGRATION_ID__?updateMask=dialogflowEsIntegration.dialogflowKnowledgeBases" \
-H "Content-Type: application/json" \
-H "User-Agent: curl/business-communications" \
-H "$(oauth2l header --json ./service_account_key.json businesscommunications)" \
-d '{
  "dialogflowEsIntegration": {
    "dialogflowKnowledgeBases": [
      {
        "displayName": "__KNOWLEDGE_BASE_DISPLAY_NAME__",
        "documents": [
          {
            "displayName": "__DOCUMENT_DISPLAY_NAME__",
            "rawContent": "__CSV_RAW_BYTES__"
          }
        ]
      }
    ]
  }
}'

Para ver las opciones de formato y de valor, consulta DialogflowKnowledgebase.

Se necesitan aproximadamente dos minutos para agregar un documento a una base de conocimiento. Para verificar el estado del documento, obtén la integración OperationInfo.

Cómo borrar un documento de conocimiento

Si necesitas quitar pares de preguntas y respuestas de tu agente de Business Messages, borra el documento de conocimiento que los contiene con el siguiente comando.

Ejecuta el siguiente comando para borrar un solo documento existente. Reemplaza BRAND_ID, AGENT_ID y INTEGRATION_ID por los valores únicos del name del documento. Reemplaza KNOWLEDGE_BASE_DISPLAY_NAME por la string adecuada.

cURL


# This code deletes a knowledge base document.
# Read more: https://developers.google.com/business-communications/business-messages/guides/how-to/integrate/dialogflow?method=api#delete_a_knowledge_document

# Replace the __BRAND_ID__, __AGENT_ID__, __INTEGRATION_ID__ and __KNOWLEDGE_BASE_DISPLAY_NAME__
# To delete all knowledge bases, set dialogflowKnowledgeBases to an empty list. Otherwise, the list should contain all existing knowledgebases except the one you would like to remove.
# Make sure a service account key file exists at ./service_account_key.json

curl -X PATCH \
"https://businesscommunications.googleapis.com/v1/brands/__BRAND_ID__/agents/__AGENT_ID__/integrations/__INTEGRATION_ID__?updateMask=dialogflowEsIntegration.dialogflowKnowledgeBases" \
-H "Content-Type: application/json" \
-H "User-Agent: curl/business-communications" \
-H "$(oauth2l header --json ./service_account_key.json businesscommunications)" \
-d '{
  "dialogflowEsIntegration": {
    "dialogflowKnowledgeBases": [
      {
        "displayName": "__KNOWLEDGE_BASE_DISPLAY_NAME__"
      }
    ]
  }
}'

Para ver las opciones de formato y de valor, consulta DialogflowKnowledgebase.

Respuestas automáticas

Si habilitas la respuesta automática durante la integración de Dialogflow, Business Messages responde automáticamente al usuario a través de Dialogflow. Tu agente de Business Messages responde con la coincidencia de nivel de confianza más alto. Con una integración de Dialogflow ES, si hay coincidencias con una respuesta a las preguntas frecuentes y un intent personalizado, Business Messages responde con la coincidencia que tiene el nivel de confianza más alto.

Business Messages marca todos los mensajes de respuesta automática como provenientes de representantes de BOT. Si tu agente admite agentes humanos, Business Messages suspende las respuestas automáticas después de los eventos REPRESENTATIVE_JOINED y las reanuda después del evento REPRESENTATIVE_LEFT. Consulta Handoff de bot to live agent.

Responder automáticamente con una respuesta a preguntas frecuentes

Con una integración de Dialogflow ES, si una respuesta de Preguntas frecuentes tiene el nivel de confianza más alto, Business Messages asigna la respuesta a un mensaje de texto. Si hay una respuesta relacionada, pero diferente disponible, el mensaje muestra una sugerencia "Ver otra respuesta&quot. De lo contrario, el mensaje incluye una pregunta y respuestas sugeridas para preguntar si el mensaje cumplió con la solicitud del usuario.

Respuesta automática con una respuesta de intent

Las respuestas de los intents pueden incluir una o más de las siguientes respuestas.

Si una respuesta de intent tiene la coincidencia de nivel de confianza más alta, se aplica lo siguiente.

  • Si la respuesta tiene al menos un valor de texto, Business Messages asigna este valor a un mensaje de texto.
  • Si la respuesta tiene al menos una carga útil personalizada con una estructura de objetos JSON válida, Business Messages crea un mensaje con el objeto JSON proporcionado.
  • Si la respuesta tiene al menos una respuesta de transferencia de un agente humano, consulta Respuesta automática con una solicitud de agente humano.

Debido a que Dialogflow puede incluir varias respuestas dentro de una coincidencia de intent, Business Messages envía cada mensaje de texto, carga útil personalizada o respuesta de transferencia del agente en vivo como un mensaje independiente. Si hay varios mensajes en una coincidencia de intent, pero algunos tienen errores de formato, Business Messages solo envía mensajes válidos como respuestas automáticas.

Respuesta automática con una solicitud de agente en vivo

Dialogflow CX admite la respuesta de transferencia de agente en vivo. Indica que la conversación debe transferirse a un representante humano y te permite pasar metadatos personalizados para el procedimiento de transferencia. Si una respuesta de intent tiene la coincidencia más alta en el nivel de confianza y, además, incluye un traspaso de agente en vivo, Business Messages envía un evento solicitado por un agente humano a tu webhook. Para controlar este evento, consulta Handoff de bot a live agent.

Respuesta automática con un mensaje de resguardo

Si Dialogflow no obtiene una coincidencia de nivel de confianza alto, Business Messages envía una respuesta de resguardo. Los resguardos se manejan de manera diferente en Dialogflow ES y Dialogflow CX.

Dialogflow ES

En el caso de los bots de Preguntas frecuentes, si no hay una respuesta a las preguntas frecuentes, Business Messages envía un mensaje alternativo que no pudo encontrar.

Para los intents configurados, si no hay una coincidencia con una respuesta de intent, Business Messages envía una respuesta de intent de resguardo. Puedes usar el texto de resguardo que proporciona Dialogflow o configurar el resguardo con texto adicional y cargas útiles personalizadas.

A continuación, te mostramos un ejemplo de una respuesta de intent de resguardo que puede recibir tu webhook:

{
  "intentResponses": [
    {
      "intentName": "projects/df-integration/agent/intents/12345",
      "intentDisplayName": "Default Fallback Intent",
      "intentDetectionConfidence": "1.0",
      "fulfillmentMessages": [
        {
          "text": "One more time?"
        }
      ]
    }
  ]
}

Dialogflow propaga previamente intent_name y intent_display_name.

Dialogflow CX

Dialogflow CX maneja las respuestas de intents de resguardo como eventos integrados. Si no hay una coincidencia con una respuesta de intent, Business Messages envía un mensaje de resguardo desde el evento predeterminado sin coincidencias en Dialogflow. Puedes usar el texto de resguardo que proporciona Dialogflow o configurar el resguardo con texto adicional, cargas útiles personalizadas y opciones de transferencia de agentes en vivo.

Este es un ejemplo de una respuesta de intent de resguardo que tu webhook puede recibir:

{
  "intentResponses": [
    {
      "intentName": "sys.no-match-default",
      "intentDisplayName": "Default Fallback Intent",
      "intentDetectionConfidence": "0.3",
      "fulfillmentMessages": [
        {
          "text": "I missed that, say that again?"
        }
      ]
    }
  ]
}

Business Messages codifica los códigos intent_name y intent_display_name.

Campos específicos de Dialogflow

Después de habilitar la integración de Dialogflow, los mensajes de usuario que recibe el agente incluyen el objeto dialogflowResponse. Tu webhook recibe cargas útiles para todos los mensajes de los usuarios, sin importar si Business Messages respondió automáticamente o no en tu nombre. Para verificar una respuesta automática, consulta el valor del campo autoResponded y decide si necesitas responder al usuario.

Dialogflow ES

...
"dialogflowResponse": {
  "queryText": "TEXT",
  "intentResponse": {
    "intentName": "INTENT_ID",
    "intentDisplayName": "INTENT_NAME",
    "intentDetectionConfidence": "CONFIDENCE_NUMERIC",
    "fulfillmentMessages": [{
      "text": "FULFILLMENT_TEXT",
      "jsonPayload": "JSON",
      "error": "ERROR_STATUS",
    }],
  "faqResponse": {
    "userQuestion": "USER_QUESTION",
    "answers": [{
      "faqQuestion": "FAQ_QUESTION",
      "faqAnswer": "FAQ_ANSWER",
      "matchConfidenceLevel": "CONFIDENCE_LEVEL",
      "matchConfidence": "CONFIDENCE_NUMERIC",
    }],
  },
  "autoResponded": "BOOLEAN",
  "autoRespondedMessages": [{
    "message": "MESSAGE_JSON",
    "responseSource": "SOURCE",
  }],
},
...
Campo Descripción
queryText Es el texto de consulta de conversación original. Si la corrección ortográfica automática está habilitada para el modelo de Dialogflow, queryText contiene la entrada del usuario corregida.
intentName El identificador único del intent coincidente.
intentDisplayName El nombre del intent coincidente.
intentDetectionConfidence La calificación de confianza numérica en la coincidencia entre queryText y intentName.
text Una respuesta de texto
jsonPayload Una respuesta de carga útil personalizada Esta string coincide con la carga útil personalizada definida en Dialogflow. Si la carga útil no tiene una estructura de objeto JSON válida para Business Messages, error describe el problema.
error Una descripción de un error con un mensaje de entrega de intent.
userQuestion La pregunta que hizo el usuario, según el análisis de Dialogflow.
faqQuestion Una pregunta de Dialogflow que coincide con la pregunta del usuario.
faqAnswer Una respuesta de Dialogflow coincidió con la pregunta del usuario.
matchConfidenceLevel El nivel de confianza en la coincidencia entre userQuestion y faqQuestion.
matchConfidence La calificación de confianza numérica en la coincidencia entre userQuestion y faqQuestion.
autoResponded Indica si Business Messages respondió al usuario automáticamente o no con una respuesta de Dialogflow.
message La carga útil de la respuesta automática.
responseSource La fuente de la respuesta automática. Consulta ResponseSource.

Dialogflow CX

...
"dialogflowResponse": {
  "queryText": "TEXT",
  "intentResponse": {
    "intentName": "INTENT_ID",
    "intentDisplayName": "INTENT_NAME",
    "intentDetectionConfidence": "CONFIDENCE_NUMERIC",
    "fulfillmentMessages": [{
      "text": "FULFILLMENT_TEXT",
      "jsonPayload": "JSON",
      "error": "ERROR_STATUS",
      "liveAgentHandoff": {
        "metadata": {}
      }
    }],
  "autoResponded": "BOOLEAN",
  "autoRespondedMessages": [{
    "message": "MESSAGE_JSON",
    "responseSource": "SOURCE",
  }],
},
...
Campo Descripción
queryText Es el texto de consulta de conversación original. Si la corrección ortográfica automática está habilitada para el modelo de Dialogflow, queryText contiene la entrada del usuario corregida.
intentName El identificador único del intent coincidente.
intentDisplayName El nombre del intent coincidente.
intentDetectionConfidence La calificación de confianza numérica en la coincidencia entre queryText y intentName.
text Una respuesta de texto
jsonPayload Una respuesta de carga útil personalizada Esta string coincide con la carga útil personalizada definida en Dialogflow. Si la carga útil no tiene una estructura de objeto JSON válida para Business Messages, error describe el problema.
error Una descripción de un error con un mensaje de entrega de intent.
liveAgentHandoff Metadatos personalizados del procedimiento de transferencia del agente en vivo.
autoResponded Indica si Business Messages respondió al usuario automáticamente o no con una respuesta de Dialogflow.
message La carga útil de la respuesta automática.
responseSource La fuente de la respuesta automática. Consulta ResponseSource.