Добавьте автоматизации с помощью Dialogflow

Dialogflow — это инструмент для понимания естественного языка (NLU), который обрабатывает вводимые пользователем данные, сопоставляет их с известными намерениями и отвечает соответствующими ответами. Существует две редакции Dialogflow. Интегрировав свой агент Business Messages с Dialogflow ES, вы можете легко создать простую автоматизацию, чтобы ускорить разработку своего агента. Благодаря интеграции с Dialogflow CX вы можете создать расширенную автоматизацию для более сложных разговоров.

Агенты Business Messages поддерживают прямую интеграцию с

Чтобы интегрировать агент Business Messages с другими функциями Dialogflow ES или Dialogflow CX , обратитесь к документации каждого продукта.

Когда пользователь отправляет сообщение агенту с интеграцией Dialogflow, Business Messages передает пользовательское сообщение в Dialogflow и отправляет ответ Dialogflow агенту в объекте сообщения dialogflowResponse . Вы можете настроить агенты для автоматической отправки ответа Dialogflow пользователю без каких-либо действий с вашей стороны. Подробнее см. в разделе Автоответы .

Интеграция диалогового потока

Прежде чем вы сможете использовать автоматизацию на основе Dialogflow через Business Messages, вам необходимо включить интеграцию Dialogflow.

Предпосылки

Для начала вам нужно

  • агент деловых сообщений
  • агент Dialogflow в регионе Global с корневым языком английский (en)

Если у вас нет агента Dialogflow, создайте его .

Диалогфлоу ЕС

Прежде чем вы сможете включить интеграцию Dialogflow ES, вам потребуется идентификатор проекта вашего агента Dialogflow. Чтобы найти идентификатор проекта,

  1. Перейдите в консоль Dialogflow .
  2. Выберите агент Dialogflow, который вы хотите подключить к Business Messages, затем щелкните значок шестеренки. рядом с именем агента.
  3. В разделе Google Project обратите внимание на значение идентификатора проекта .

Диалоговый поток CX

Прежде чем вы сможете включить интеграцию Dialogflow CX, вам потребуется идентификатор проекта вашего агента Dialogflow и идентификатор агента. Чтобы найти эти идентификаторы,

  1. Перейдите к консоли Dialogflow CX .
  2. Выберите свой проект Dialogflow.
  3. В средстве выбора агента щелкните дополнительное меню. рядом с вашим агентом Dialogflow.
  4. Щелкните Копировать имя . При этом будет скопировано полное имя вашего агента в следующем формате: projects/PROJECT_ID/locations/REGION_ID/agents/AGENT_ID .
  5. Обратите внимание на значения идентификатора проекта и идентификатора агента.

Создайте интеграцию

  1. Получите адрес электронной почты учетной записи службы Dialogflow партнера из dialogflowServiceAccountEmail . Замените PARTNER_ID своим идентификатором партнера.

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

    Питон

    
    """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. Скопируйте адрес электронной почты сервисного аккаунта. Эта учетная запись связывает ваши деловые сообщения и агенты Dialogflow.

  3. В Google Cloud Console выберите свой проект Dialogflow.

  4. Перейдите к разрешениям IAM .

  5. Нажмите « Добавить » и введите адрес электронной почты сервисного аккаунта для новых участников .

  6. Для выбора роли выберите Редактор агента консоли Dialogflow .

  7. Нажмите « Добавить другую роль » и выберите «Клиент Dialogflow API» .

  8. Нажмите Сохранить .

  9. Интегрируйте свой проект Dialogflow с агентом Business Messages.

    Замените AUTO_RESPONSE_STATUS на ENABLED или DISABLED, в зависимости от того, хотите ли вы, чтобы Business Messages автоматически отвечал пользователям с ответами Dialogflow.

    Диалогфлоу ЕС

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

    Питон

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

    Диалоговый поток 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();
    

    Питон

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

    Параметры форматирования и значений см. в разделе Integration .

Подключение Business Messages и Dialogflow занимает около двух минут. Чтобы проверить статус интеграции, получите OperationInfo интеграции.

Обновите интеграцию

Чтобы обновить настройку автоматического ответа вашего агента, выполните следующую команду. Замените AUTO_RESPONSE_STATUS на ENABLED или DISABLED в зависимости от того, хотите ли вы, чтобы Business Messages автоматически отвечал пользователям с ответами Dialogflow.

Диалогфлоу ЕС

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
}'

Диалоговый поток 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
}'

Параметры форматирования и значений см. в разделе Integration .

Переключение между версиями Dialogflow

Агент Business Messages может одновременно поддерживать только одну интеграцию Dialogflow. Чтобы переключиться с одной редакции Dialogflow на другую, вам необходимо удалить текущую интеграцию перед созданием новой.

Удалить интеграцию

Если вам нужно удалить Dialogflow из агента Business Messages, удалите интеграцию с помощью следующей команды.

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

питон


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

Параметры форматирования и значений см. в разделе Integration .

Получить информацию об интеграции

Чтобы получить информацию об интеграции, вы можете использовать Business Communications API, если у вас есть значение name интеграции.

Получить информацию для одной интеграции

Чтобы получить информацию об интеграции, выполните следующую команду.

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

питон


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

Параметры форматирования и значений см. в разделе Integration .

Список всех интеграций для агента

Если вы не знаете имя интеграции, вы можете получить информацию обо всех интеграциях, связанных с агентом, опустив значение INTEGRATION_ID в URL-адресе запроса 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();

питон


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

Параметры форматирования и значений см. в разделе Integration .

Соответствие намерений

После того как вы включите интеграцию Dialogflow для агента Business Messages, ваш агент сможет использовать настроенные намерения вашего проекта Dialogflow, чтобы понимать и отвечать на вопросы пользователей без необходимости написания кода. Чтобы узнать больше о намерениях, см. документацию по Dialogflow ES и Dialogflow CX .

Настройте свои намерения Dialogflow для каждого диалогового варианта, который вы собираетесь поддерживать с помощью автоматизации. Агенты Business Messages полагаются на Dialogflow для понимания пользовательских сообщений.

При вызове API Dialogflow Business Messages передает полезную нагрузку сообщения пользователя вашим намерениям и веб-перехватчику выполнения. Когда сообщение пользователя соответствует намерению, вы можете получить доступ к этим полезным данным в формате Struct в поле business_messages_payload в QueryParameters .

Полезная нагрузка содержит все поля пользовательского сообщения, кроме DialogflowResponse .

Для Dialogflow CX Business Messages также передает параметр сеанса, называемый channel со значением google_business_messages в соответствии с вашими намерениями, и вы можете ссылаться на него в своем агенте в следующем формате: $session.params.channel .

Этот параметр можно использовать для добавления условий к выполнению Dialogflow для поддержки нескольких каналов в одном и том же агенте Dialogflow.

Дополнительные сведения о параметрах запроса см. в справочниках Dialogflow ES и Dialogflow CX .

Предпосылки

При создании моделей NLU в Dialogflow вы можете настроить различные типы ответов для намерения. Business Messages поддерживает ответ по умолчанию, который может включать следующее:

  • Текст
  • Пользовательская полезная нагрузка
  • Передача живого агента (только Dialogflow CX)

Настраиваемая полезная нагрузка должна соответствовать допустимому объекту ответа на сообщение Business Messages JSON . При настройке настраиваемых ответов полезной нагрузки для намерения Business Messages игнорирует следующие поля:

  • name
  • messageId
  • representative

См. следующие примеры ответов.

Текст с предложениями

{
  "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"
      }
    }
  ]
}

Богатая карта

{
  "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
            }
          }
        }
      ]
    }
  }
}

Передача живого агента

{
  "metadata": {}
}

ЧаВо боты

После того, как вы включите интеграцию Dialogflow ES для агента бизнес-сообщений, вы можете создать бота для часто задаваемых вопросов. Когда вы предоставляете вопросы и ответы в виде поддерживаемого документа знаний, Business Messages и Dialogflow создают необходимую инфраструктуру для понимания и ответа на вопросы пользователей без необходимости написания кода.

Чтобы увидеть бота часто задаваемых вопросов в действии, пообщайтесь с ботом часто задаваемых вопросов для деловых сообщений .

Предпосылки

Прежде чем создавать бота для часто задаваемых вопросов, вам необходимо, чтобы ваши вопросы и ответы были доступны в виде документа знаний (не более 50 МБ): общедоступного файла HTML или файла CSV.

Как правило, документы знаний

  • Может включать ограниченный Markdown в ответы, как указано в форматированном тексте .
  • Иметь максимальный размер 50 МБ.
  • Не должно превышать 2000 пар вопросов/ответов.
  • Не поддерживайте повторяющиеся вопросы с разными ответами.

Для HTML-файлов

  • Файлы с общедоступных URL-адресов должны быть просканированы поисковым индексатором Google, чтобы они существовали в поисковом индексе. Вы можете проверить это с помощью Google Search Console . Обратите внимание, что индексатор не обновляет ваш контент. Вы должны явно обновлять документ при изменении исходного содержимого.
  • Dialogflow удаляет теги HTML из контента при создании ответов. По этой причине лучше избегать HTML-тегов и по возможности использовать обычный текст.
  • Файлы с одной парой вопрос/ответ не поддерживаются.

Для файлов CSV,

  • Файлы должны содержать вопросы в первом столбце и ответы во втором без заголовка.
  • Файлы должны использовать запятые в качестве разделителей.

Создайте бота для часто задаваемых вопросов

Чтобы создать бота для часто задаваемых вопросов, вы сначала создаете базу знаний для хранения всех данных бота, а затем добавляете в базу знаний один или несколько документов с парами вопросов и ответов.

Создайте базу знаний

Чтобы создать базу знаний, выполните следующую команду. Замените BRAND_ID , AGENT_ID и INTEGRATION_ID уникальными значениями из name документа . Замените KNOWLEDGE_BASE_DISPLAY_NAME идентифицирующей строкой по вашему выбору.

После создания базы знаний вы можете создавать в ней документы .

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__"
      }
    ]
  }
}'

Параметры форматирования и значений см. DialogflowKnowledgebase .

Создать документ знаний

Чтобы создать документ знаний, выполните следующую команду.

Добавьте документ в список существующих документов или создайте новый список, если его еще нет. Список существующих документов должен включать значение name документа в запросе.

Общедоступный HTML-файл

Замените следующие переменные:

  • BRAND_ID , AGENT_ID и INTEGRATION_ID с уникальными значениями из name интеграции
  • KNOWLEDGE_BASE_DISPLAY_NAME и DOCUMENT_DISPLAY_NAME с идентифицирующими строками по вашему выбору
  • PUBLIC_URL с общедоступным URL-адресом документа базы знаний

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__"
          }
        ]
      }
    ]
  }
}'

Локальный CSV-файл

Замените следующие переменные:

  • BRAND_ID , AGENT_ID и INTEGRATION_ID с уникальными значениями из name интеграции
  • KNOWLEDGE_BASE_DISPLAY_NAME и DOCUMENT_DISPLAY_NAME с идентифицирующими строками по вашему выбору
  • CSV_RAW_BYTES с CSV-файлом в виде строки в кодировке 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__"
          }
        ]
      }
    ]
  }
}'

Параметры форматирования и значений см. DialogflowKnowledgebase .

Добавление документа в базу знаний занимает около двух минут. Чтобы проверить статус документа, получите OperationInfo интеграции.

Удалить документ знаний

Если вам нужно удалить пары вопрос/ответ из вашего агента Business Messages, удалите документ знаний, который их содержит, с помощью следующей команды.

Выполните следующую команду, чтобы удалить один существующий документ. Замените BRAND_ID , AGENT_ID и INTEGRATION_ID уникальными значениями из name документа . Замените KNOWLEDGE_BASE_DISPLAY_NAME соответствующей строкой.

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__"
      }
    ]
  }
}'

Параметры форматирования и значений см. DialogflowKnowledgebase .

Автоответы

Если вы включите автоматический ответ во время интеграции Dialogflow, Business Messages автоматически отвечает пользователю через Dialogflow. Ваш агент Business Messages отвечает с наивысшим уровнем достоверности. При интеграции Dialogflow ES, если есть совпадения как с ответом на часто задаваемые вопросы, так и с пользовательским намерением, Business Messages отвечает совпадением с наивысшим уровнем достоверности.

Деловые сообщения помечают все автоматически отвеченные сообщения как исходящие от представителей BOT . Если ваш агент поддерживает агентов в реальном времени , Business Messages приостанавливает автоматические ответы после событий REPRESENTATIVE_JOINED и возобновляет автоматические ответы после событий REPRESENTATIVE_LEFT . См. Переключение с бота на живого агента .

Автоматический ответ с ответом на часто задаваемые вопросы

При интеграции Dialogflow ES, если ответ на часто задаваемые вопросы имеет самый высокий уровень достоверности, Business Messages сопоставляет ответ с текстовым сообщением. Если доступен связанный, но другой ответ, в сообщении отображается предложение «Просмотреть другой ответ». Если нет, сообщение включает вопрос и предлагаемые ответы, спрашивающие, удовлетворило ли сообщение запрос пользователя.

Автоматический ответ с намеренным ответом

Ответы о намерениях могут включать один или несколько следующих ответов.

Если ответ о намерении имеет совпадение с наивысшим уровнем достоверности, применяется следующее.

  • Если в ответе есть хотя бы одно текстовое значение, Business Messages сопоставляет это значение с текстовым сообщением.
  • Если в ответе есть хотя бы одна пользовательская полезная нагрузка с допустимой структурой объекта JSON Business Messages, Business Messages создает сообщение с использованием предоставленного объекта JSON.
  • Если в ответе есть хотя бы один ответ на передачу обслуживания активного агента, см. раздел Автоматический ответ с запросом активного агента .

Поскольку Dialogflow может включать в себя несколько ответов в рамках одного совпадения намерений, Business Messages отправляет каждый ответ Text, Custom payload или Live агента на передачу в виде отдельного сообщения. Если есть несколько сообщений с совпадением намерений, но некоторые из них имеют неверный формат, Business Messages отправляет только действительные сообщения в качестве автоответов.

Автоматический ответ на запрос живого агента

Dialogflow CX поддерживает ответ на передачу обслуживания активного агента . Он сигнализирует о том, что разговор должен быть передан представителю, и позволяет передавать пользовательские метаданные для процедуры передачи. Если ответ о намерении имеет совпадение с наивысшим уровнем достоверности и включает передачу обслуживания активного агента, Business Messages отправляет событие, запрошенное активным агентом, на ваш веб-перехватчик. Чтобы обработать это событие, см. Handoff от бота к живому агенту .

Автоматический ответ с резервным сообщением

Если Dialogflow не получает соответствия с высоким уровнем достоверности, Business Messages отправляет резервный ответ. Резервные копии обрабатываются по-разному в Dialogflow ES и Dialogflow CX.

Диалогфлоу ЕС

Для ботов часто задаваемых вопросов, если нет совпадения с ответом на часто задаваемые вопросы, Business Messages отправляет резервное сообщение о том, что не может найти ответ.

Для настроенных намерений, если нет совпадения с ответом о намерении, Business Messages отправляет резервный ответ о намерении . Вы можете использовать резервный текст, предоставленный Dialogflow, или настроить резервный вариант с дополнительным текстом и пользовательскими полезными данными.

Вот пример резервного ответа о намерении, который может получить ваш веб-перехватчик:

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

intent_name предварительно заполняет намерение_имя и intent_display_name .

Диалоговый поток CX

Dialogflow CX обрабатывает ответы на резервные намерения как встроенные события . Если нет совпадения с ответом о намерении, Business Messages отправляет резервное сообщение из события «Нет совпадения по умолчанию» в Dialogflow. Вы можете использовать резервный текст, предоставленный Dialogflow, или настроить резервный вариант с дополнительным текстом, пользовательскими полезными данными и параметрами передачи обслуживания в реальном времени.

Вот пример резервного ответа о намерении, который может получить ваш веб-перехватчик:

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

Деловые сообщения жестко кодируют intent_name и intent_display_name .

Поля диалогового потока

После включения интеграции Dialogflow пользовательские сообщения, которые получает агент, включают объект dialogflowResponse . Ваш веб-перехватчик получает полезные данные для всех пользовательских сообщений независимо от того, ответили ли Business Messages на сообщение от вашего имени автоматически. Чтобы проверить наличие автоответа, посмотрите значение поля autoResponded и решите, нужно ли вам отвечать пользователю.

Диалогфлоу ЕС

...
"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",
  }],
},
...
Поле Описание
queryText Исходный диалоговый текст запроса. Если для модели Dialogflow включена автоматическая коррекция орфографии, queryText содержит исправленный пользовательский ввод.
intentName Уникальный идентификатор совпавшего намерения.
intentDisplayName Имя совпавшего намерения.
intentDetectionConfidence Числовой рейтинг достоверности совпадения между queryText и intentName .
text Текстовый ответ.
jsonPayload Пользовательский ответ полезной нагрузки. Эта строка соответствует настраиваемой полезной нагрузке, определенной в Dialogflow. Если полезная нагрузка не имеет допустимой структуры объекта JSON для бизнес-сообщений, error описывает проблему.
error Описание ошибки с сообщением о выполнении намерения.
userQuestion Вопрос, который задал пользователь, проанализированный Dialogflow.
faqQuestion Вопрос от Dialogflow совпал с вопросом пользователя.
faqAnswer Ответ от Dialogflow совпал с вопросом пользователя.
matchConfidenceLevel Уровень достоверности совпадения между userQuestion и faqQuestion .
matchConfidence Числовой рейтинг достоверности совпадения между userQuestion и faqQuestion .
autoResponded Отвечали ли Business Messages пользователю автоматически ответом от Dialogflow.
message Полезная нагрузка автоответчика.
responseSource Источник автоответа. См. ResponseSource .

Диалоговый поток 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",
  }],
},
...
Поле Описание
queryText Исходный диалоговый текст запроса. Если для модели Dialogflow включена автоматическая коррекция орфографии, queryText содержит исправленный пользовательский ввод.
intentName Уникальный идентификатор совпавшего намерения.
intentDisplayName Имя совпавшего намерения.
intentDetectionConfidence Числовой рейтинг достоверности совпадения между queryText и intentName .
text Текстовый ответ.
jsonPayload Пользовательский ответ полезной нагрузки. Эта строка соответствует настраиваемой полезной нагрузке, определенной в Dialogflow. Если полезная нагрузка не имеет допустимой структуры объекта JSON для бизнес-сообщений, error описывает проблему.
error Описание ошибки с сообщением о выполнении намерения.
liveAgentHandoff Настраиваемые метаданные для процедуры передачи обслуживания живого агента.
autoResponded Отвечали ли Business Messages пользователю автоматически ответом от Dialogflow.
message Полезная нагрузка автоответа.
responseSource Источник автоответа. См. ResponseSource .