Создать агентов для управления брендами,Создать агентов для управления брендами,Создать агентов для управления брендами

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

Агент — это диалоговая сущность, с которой взаимодействуют пользователи. Вы создаете одного агента для каждого бренда, которым управляете. Вы создаете агентов и управляете ими с помощью API бизнес-коммуникаций, а также управляете обменом сообщениями для своих агентов с помощью API бизнес-сообщений.

Агент включает в себя бизнес-функции бренда, такие как онлайн-поддержка и физическое местоположение (если таковое имеется). Каждое сообщение содержит контекст, из которого пользователь инициировал разговор. Ваша инфраструктура маршрутизации сообщений может определить, просматривал ли пользователь определенное местоположение компании или искал общую поддержку, и может направлять сообщения в правильный пункт назначения.

Отношения агент/бренд

Например, если вы управляете брендом Growing Tree Bank, у которого есть веб-сайт и два офиса, вы создаете одного агента Growing Tree Bank. Пользователи могут столкнуться с агентом посредством общего поиска или поиска по местоположению, а контекст, в котором пользователь нашел агента, передается вместе с каждым сообщением в ваш веб-перехватчик. Вы используете этот контекст для маршрутизации сообщения либо сотрудникам в определенном месте, либо команде поддержки веб-сайта, которая создает ответ и продолжает разговор с пользователем.

Ожидания

Прежде чем создавать агента, уясните ожидания агентов в отношении Business Messages.

Создать агента

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

Если вы управляете несколькими брендами, повторите шаги, чтобы создать агента для каждого бренда.

Предварительные условия

Прежде чем создавать агентов для брендов, которыми вы управляете, вам необходимо собрать некоторую информацию:

Среда разработки

Информация о вашей среде разработки.

Подробности о бренде

Информация о бренде, который представляет агент.

  • Имя бренда
  • Сайт бренда
  • Варианты связи на веб-сайте (как определено в OPTION )
  • Телефонный номер, ориентированный на потребителя
  • Телефонные номера, на которых разрешено отклонение вызовов

Внешний вид и политика агента

Информация о том, как агент выглядит для пользователей и как он работает.

  • Имя агента, какое вы хотите, чтобы оно отображалось в разговорах с пользователями.
  • Политика конфиденциальности в виде общедоступного URL-адреса, начинающегося с «https://».
  • (Рекомендуется) Логотип агента (1024x1024 пикселей) в виде общедоступного URL-адреса.

    В разговоре логотипы отображаются в виде кругов диаметром 1024 пикселя. Убедитесь, что ваш логотип хорошо отображается в виде круга.

  • (Необязательно) Пользовательский идентификатор агента, который идентифицирует бренд в сообщениях, которые получает вебхук.

Взаимодействие с агентом

Информация о том, как ваш агент взаимодействует с пользователями.

  • Языковой стандарт, в котором обычно работает ваш агент, указанный двухзначным кодом языка ISO 639-1.

  • Приветственное сообщение агента

    Что говорит агент, приветствуя пользователей?

  • Начало разговора с агентом

    Список предложений в виде фрагментов разговора (как определено в OfferedReply ), которые пользователь может взаимодействовать с агентом.

    • Текст, отображаемый пользователю в чипе
    • Данные обратной передачи, строка, отправляемая обратно на ваш веб-перехватчик в полезных данных сообщения, если пользователь касается чипа.
  • Время автоматического и живого чата

    • Ежедневное время начала как объект TimeOfDay

      Например, 8:15 утра

      {
        "hours": 8,
        "minutes": 15,
      }
      
    • Время окончания дня как объект TimeOfDay

      Например, 19:30

      {
        "hours": 19,
        "minutes": 30,
      }
      
    • День начала, первый день недели, когда агент доступен для чата (как определено в DayOfWeek ).

    • Конечный день — последний день недели, когда агент доступен для чата (как определено в DayOfWeek ).

    • Часовой пояс, в котором работает агент (как определено в базе данных часовых поясов IANA , например «Америка/Лос-Анджелес»)

Точки входа агента

Информация о том, где пользователи могут начать общение с агентом.

  • Разрешенные точки входа агента, где пользователи могут начинать разговор с агентами ( NON_LOCAL и/или LOCATION ).

Информация о точках входа NON_LOCAL (не относится к точке входа Google Ads ).

  • Разрешенные регионы (как коды регионов CLDR ), чтобы ограничить региональный доступ к точкам входа NON_LOCAL .

    Независимо от региона, с агентом может быть связан только один номер телефона. Если вам нужен другой номер телефона в зависимости от региона, для каждого региона необходимо создать отдельного агента.

    Чтобы включить точки входа NON_LOCAL во всех доступных регионах, используйте 001 для кода региона «Мир».

Установите и протестируйте oauth2l

Все запросы на завитки в документации этого сайта используют oauth2l для аутентификации. Если вы хотите использовать командную строку для подключения к API бизнес-коммуникаций и бизнес-сообщений, установите файл oauth2l.

Чтобы установить oauth2l с Python 3,

  1. Загрузите oauth2l .

  2. Измените каталог на «./oauth2l/python».

  3. Установите oauth2l с помощью следующей команды.

    sudo python setup.sh build && sudo python setup.py install
    
  4. Проверьте, может ли oauth2l генерировать токен авторизации.

    oauth2l header --json resources/bm-agent-service-account-credentials.json businesscommunications
    
  5. Убедитесь, что выходные данные создают токен авторизации в форме:

    Authorization: Bearer AUTHORIZATION_BEARER_TOKEN
    

Есть и другие способы установки oauth2l для разных операционных систем. Независимо от метода установки, прежде чем продолжить, убедитесь, что вы можете создать токен авторизации на основе учетных данных JSON учетной записи службы.

Создать агент

После того, как вы собрали всю информацию, пришло время создать своего агента.

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

    В терминале выполните следующую команду:

    КУЛЬ

    
    # This code creates a brand.
    # Read more: https://developers.google.com/business-communications/business-messages/reference/business-communications/rest/v1/brands/create
    
    # Make sure a service account key file exists at ./service_account_key.json
    
    curl -X POST "https://businesscommunications.googleapis.com/v1/brands" \
    -H "Content-Type: application/json" \
    -H "User-Agent: curl/business-communications" \
    -H "$(oauth2l header --json ./service_account_key.json businesscommunications)" \
    -d '{
      "displayName": "My first brand curl"
    }'
    

    Node.js

    
    /**
     * This code snippet creates a brand.
     * Read more: https://developers.google.com/business-communications/business-messages/reference/business-communications/rest/v1/brands/create
     *
     * This code is based on the https://github.com/google-business-communications/nodejs-businesscommunications Node.js
     * Business Communications client library.
     */
    
    /**
     * Edit the values below:
     */
    const PATH_TO_SERVICE_ACCOUNT_KEY = './service_account_key.json';
    
    const businesscommunications = require('businesscommunications');
    const {google} = require('googleapis');
    
    // Initialize the Business Communications API
    const bcApi = new businesscommunications.businesscommunications_v1.Businesscommunications({});
    
    // Set the scope that we need for the Business Communications API
    const scopes = [
      'https://www.googleapis.com/auth/businesscommunications',
    ];
    
    // Set the private key to the service account file
    const privatekey = require(PATH_TO_SERVICE_ACCOUNT_KEY);
    
    async function main() {
      const authClient = await initCredentials();
    
      if (authClient) {
        // Setup the parameters for the API call
        const apiParams = {
          auth: authClient,
          resource: {
            displayName: 'My first brand',
          },
        };
    
        bcApi.brands.create(apiParams, {}, (err, response) => {
          if (err !== undefined && err !== null) {
            console.dir(err);
          } else {
            // Brand created
            console.log(response.data);
          }
        });
      }
      else {
        console.log('Authentication failure.');
      }
    }
    
    /**
     * Initializes the Google credentials for calling the
     * Business Communcations API.
     */
     async function initCredentials() {
      // configure a JWT auth client
      const authClient = new google.auth.JWT(
        privatekey.client_email,
        null,
        privatekey.private_key,
        scopes,
      );
    
      return new Promise(function(resolve, reject) {
        // authenticate request
        authClient.authorize(function(err, tokens) {
          if (err) {
            reject('Failed to connect');
          } else {
            resolve(authClient);
          }
        });
      })
    }
    
    main();
    

    Джава

    import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
    import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
    import com.google.api.client.http.HttpTransport;
    import com.google.api.client.json.jackson2.JacksonFactory;
    import com.google.api.services.businesscommunications.v1.BusinessCommunications;
    import com.google.api.services.businesscommunications.v1.model.Brand;
    import java.io.FileInputStream;
    import java.util.Arrays;
    import java.util.UUID;
    
    class Main {
      /**
       * Initializes credentials used by the Business Communications API.
       */
      private static BusinessCommunications.Builder getBusinessCommunicationsBuilder() {
        BusinessCommunications.Builder builder = null;
        try {
          GoogleCredential credential = GoogleCredential
                .fromStream(new FileInputStream("PATH_TO_SERVICE_ACCOUNT_KEY"));
    
          credential = credential.createScoped(Arrays.asList(
              "https://www.googleapis.com/auth/businesscommunications"));
    
          credential.refreshToken();
    
          HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
          JacksonFactory jsonFactory = JacksonFactory.getDefaultInstance();
    
          // Create instance of the Business Communications API
          builder = new BusinessCommunications
              .Builder(httpTransport, jsonFactory, null)
              .setApplicationName(credential.getServiceAccountProjectId());
    
          // Set the API credentials and endpoint
          builder.setHttpRequestInitializer(credential);
        } catch (Exception e) {
          e.printStackTrace();
        }
    
        return builder;
      }
    
      public static void main(String args[]) {
        try {
          // Create client library reference
          BusinessCommunications.Builder builder = getBusinessCommunicationsBuilder();
    
          // Create a request to create a new brand
          BusinessCommunications.Brands.Create request = builder
              .build().brands().create(new Brand().setDisplayName("BRAND_NAME"));
    
          Brand brand = request.execute();
    
          // Print newly created brand object
          System.out.println(brand.toPrettyString());
        } catch (Exception e) {
          e.printStackTrace();
        }
      }
    }
    
    Этот код основан на клиентской библиотеке Java Business Communications .

    Питон

    
    """This code creates a brand.
    
    Read more: https://developers.google.com/business-communications/business-messages/reference/business-communications/rest/v1/brands/create
    
    This code is based on the https://github.com/google-business-communications/python-businessmessages
    Python Business Messages client library.
    """
    
    from oauth2client.service_account import ServiceAccountCredentials
    from businesscommunications.businesscommunications_v1_client import BusinesscommunicationsV1
    from businesscommunications.businesscommunications_v1_messages import (
        Brand)
    
    # Edit the values below:
    SCOPES = ['https://www.googleapis.com/auth/businesscommunications']
    SERVICE_ACCOUNT_FILE = './service_account_key.json'
    
    credentials = ServiceAccountCredentials.from_json_keyfile_name(
        SERVICE_ACCOUNT_FILE, scopes=SCOPES)
    
    client = BusinesscommunicationsV1(credentials=credentials)
    
    brands_service = BusinesscommunicationsV1.BrandsService(client)
    
    brand = brands_service.Create(Brand(displayName='My first brand'))
    
    print(brand)
    

    Сохраните значение name , которое возвращает API. Он понадобится вам для обновления или создания агентов.

    Чтобы обновить или найти бренды, см. brands .

  2. Создайте агента. Замените BRAND_ID частью значения name бренда, которая следует за «brands/». Например, если name — «brands/12345», идентификатор бренда — «12345».

    В терминале выполните следующую команду:

    КУЛЬ

    
    # This code creates a Business Messages agent.
    # Read more: https://developers.google.com/business-communications/business-messages/guides/how-to/agents?method=api#create_the_agent
    
    # Replace the __BRAND_ID__ with a brand id that you can create agents for
    # Make sure a service account key file exists at ./service_account_key.json
    
    curl -X POST "https://businesscommunications.googleapis.com/v1/brands/__BRAND_ID__/agents" \
    -H "Content-Type: application/json" \
    -H "User-Agent: curl/business-communications" \
    -H "$(oauth2l header --json ./service_account_key.json businesscommunications)" \
    -d '{
      "displayName": "My first agent",
      "businessMessagesAgent": {
        "logoUrl": "https://developers.google.com/identity/images/g-logo.png",
        "entryPointConfigs": [
          {
            "allowedEntryPoint": "NON_LOCAL"
          }
        ],
        "customAgentId": "'$(uuidgen)'",
        "nonLocalConfig": {
          "regionCodes": [
            "US",
            "CA"
          ],
          "contactOption": {
            "url": "https://www.your-company-website.com",
            "options": [
              "EMAIL",
              "PHONE"
            ]
          },
          "enabledDomains": [
            "your-company-website.com"
          ],
          "phoneNumber": {
            "number": "+10000000000"
          },
          "callDeflectionPhoneNumbers": [
            {
              "number": "+10000000000"
            },
            {
              "number": "+10000000000"
            }
          ]
        },
        "conversationalSettings": {
          "en": {
            "welcomeMessage": {
              "text": "This is a sample welcome message"
            },
            "privacyPolicy": {
              "url": "https://www.your-company-website.com/privacy"
            },
            "conversationStarters": [
              {
                "suggestion": {
                  "reply": {
                    "text": "Option 1",
                    "postbackData": "postback_option_1"
                  }
                }
              }
            ]
          }
        },
        "defaultLocale": "en",
        "primaryAgentInteraction": {
          "interactionType": "HUMAN",
          "humanRepresentative": {
            "humanMessagingAvailability": {
              "hours": [
                {
                  "startTime": {
                    "hours": 8,
                    "minutes": 30
                  },
                  "endTime": {
                    "hours": 20,
                    "minutes": 0
                  },
                  "timeZone": "America/Los_Angeles",
                  "startDay": "MONDAY",
                  "endDay": "SATURDAY"
                }
              ]
            }
          }
        }
      }
    }'
    

    Node.js

    
    /**
     * This code snippet creates a Business Messages agent.
     * Read more: https://developers.google.com/business-communications/business-messages/guides/how-to/agents?method=api#create_the_agent
     *
     * This code is based on the https://github.com/google-business-communications/nodejs-businesscommunications Node.js
     * Business Communications client library.
     */
    
    /**
     * Edit the values below:
     */
    const BRAND_ID = 'EDIT_HERE';
    const PATH_TO_SERVICE_ACCOUNT_KEY = './service_account_key.json';
    
    const businesscommunications = require('businesscommunications');
    const {google} = require('googleapis');
    const uuidv4 = require('uuid').v4;
    
    // Initialize the Business Communications API
    const bcApi = new businesscommunications.businesscommunications_v1.Businesscommunications({});
    
    // Set the scope that we need for the Business Communications API
    const scopes = [
      'https://www.googleapis.com/auth/businesscommunications',
    ];
    
    // Set the private key to the service account file
    const privatekey = require(PATH_TO_SERVICE_ACCOUNT_KEY);
    
    async function main() {
      const authClient = await initCredentials();
      const brandName = 'brands/' + BRAND_ID;
    
      if (authClient) {
        const agentObject = {
          displayName: 'My first agent',
          businessMessagesAgent: {
            customAgentId: uuidv4(), // Optional
            logoUrl: 'https://developers.google.com/identity/images/g-logo.png',
            entryPointConfigs: [
              {
                allowedEntryPoint: 'NON_LOCAL',
              }
            ],
            nonLocalConfig: { // Configuration options for launching on non-local entry points
              // List of phone numbers for call deflection, values must be globally unique
              callDeflectionPhoneNumbers: [
                { number: '+10000000000' },
                { number: '+10000000001' },
              ],
              // Contact information for the agent that displays with the messaging button
              contactOption: {
                options: [
                  'EMAIL',
                  'PHONE'
                ],
                url: 'https://www.your-company-website.com',
              },
              // Domains enabled for messaging within Search, values must be globally unique
              enabledDomains: [ 'your-company-website.com' ],
              // Agent's phone number. Overrides the `phone` field
              // for conversations started from non-local entry points
              phoneNumber: { number: '+10000000000' },
              // List of CLDR region codes for countries where the agent is allowed to launch `NON_LOCAL` entry points
              regionCodes: [ 'US', 'CA' ]
            },
            // Must match a conversational setting locale
            defaultLocale: 'en',
            conversationalSettings: {
              en: {
                privacyPolicy: { url: 'https://www.your-company-website.com/privacy' },
                welcomeMessage: { text: 'This is a sample welcome message' },
                conversationStarters: [
                  {
                    suggestion: {
                      reply: {
                        text: 'Option 1',
                        postbackData: 'postback_option_1',
                      },
                    },
                  },
                ],
              },
            },
            primaryAgentInteraction: {
              interactionType: 'HUMAN',
              humanRepresentative: {
                humanMessagingAvailability: {
                  hours: [
                    {
                      startTime: {
                        hours: 8,
                        minutes: 30
                      },
                      startDay: 'MONDAY',
                      endDay: 'SATURDAY',
                      endTime: {
                        hours: 20,
                        minutes: 0
                      },
                      timeZone: 'America/Los_Angeles',
                    },
                  ],
                },
              },
            },
          },
        };
    
        // Setup the parameters for the API call
        const apiParams = {
          auth: authClient,
          parent: brandName,
          resource: agentObject
        };
    
        bcApi.brands.agents.create(apiParams, {}, (err, response) => {
          if (err !== undefined && err !== null) {
            console.dir(err);
          } else {
            // Agent created
            console.log(response.data);
          }
        });
      }
      else {
        console.log('Authentication failure.');
      }
    }
    
    /**
     * Initializes the Google credentials for calling the
     * Business Messages API.
     */
     async function initCredentials() {
      // Configure a JWT auth client
      const authClient = new google.auth.JWT(
        privatekey.client_email,
        null,
        privatekey.private_key,
        scopes,
      );
    
      return new Promise(function(resolve, reject) {
        // Authenticate request
        authClient.authorize(function(err, tokens) {
          if (err) {
            reject(false);
          } else {
            resolve(authClient);
          }
        });
      });
    }
    
    main();
    

    Джава

    import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
    import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
    import com.google.api.client.http.HttpTransport;
    import com.google.api.client.json.jackson2.JacksonFactory;
    import com.google.api.services.businesscommunications.v1.BusinessCommunications;
    import com.google.api.services.businesscommunications.v1.model.Brand;
    import com.google.common.collect.ImmutableMap;
    import java.io.FileInputStream;
    import java.util.Arrays;
    import java.util.UUID;
    
    class Main {
      /**
       * Initializes credentials used by the Business Communications API.
       */
      private static BusinessCommunications.Builder getBusinessCommunicationsBuilder() {
        BusinessCommunications.Builder builder = null;
        try {
          GoogleCredential credential = GoogleCredential
                .fromStream(new FileInputStream("PATH_TO_SERVICE_ACCOUNT_KEY"));
    
          credential = credential.createScoped(Arrays.asList(
              "https://www.googleapis.com/auth/businesscommunications"));
    
          credential.refreshToken();
    
          HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
          JacksonFactory jsonFactory = JacksonFactory.getDefaultInstance();
    
          // Create instance of the Business Communications API
          builder = new BusinessCommunications
              .Builder(httpTransport, jsonFactory, null)
              .setApplicationName(credential.getServiceAccountProjectId());
    
          // Set the API credentials and endpoint
          builder.setHttpRequestInitializer(credential);
        } catch (Exception e) {
          e.printStackTrace();
        }
    
        return builder;
      }
    
      public static void main(String args[]) {
        try {
          // Create client library reference
          BusinessCommunications.Builder builder = getBusinessCommunicationsBuilder();
    
          String brandName = "BRAND_ID";
    
          BusinessCommunications.Brands.Agents.Create request = builder
              .build().brands().agents().create(brandName,
                  new Agent()
                      .setDisplayName("AGENT_NAME")
                      .setBusinessMessagesAgent(new BusinessMessagesAgent()
                          .setCustomAgentId("CUSTOM_ID") // Optional
                          .setLogoUrl("LOGO_URL")
                          .setEntryPointConfigs(Arrays.asList(
                            new BusinessMessagesEntryPointConfig()
                                .setAllowedEntryPoint(
                                    "ENTRY_POINT_1"),
                            new BusinessMessagesEntryPointConfig()
                                .setAllowedEntryPoint(
                                    "ENTRY_POINT_2")
                          ))
                          // Configuration options for launching on non-local entry points
                          .setNonLocalConfig(new NonLocalConfig()
                            // List of phone numbers for call deflection, values must be globally unique
                            .setCallDeflectionPhoneNumbers(Arrays.asList(new Phone().setNumber("DEFLECTION_PHONE_NUMBER_1"),
                                new Phone().setNumber("DEFLECTION_PHONE_NUMBER_2")))
                            // Contact information for the agent that displays with the messaging button
                            .setContactOption(new ContactOption().setOptions(Arrays.asList(
                                "CONTACT_OPTION_1",
                                "CONTACT_OPTION_2")
                            ).setUrl("WEBSITE_URL"))
                            // Domains enabled for messaging within Search, values must be globally unique
                            .setEnabledDomains(Arrays.asList("ENABLED_DOMAIN_1", "ENABLED_DOMAIN_2"))
                            // Agent's phone number. Overrides the `phone` field for
                            // conversations started from non-local entry points
                            .setPhoneNumber(new Phone().setNumber("CONTACT_PHONE_NUMBER"))
                            // List of regions where this agent will be available
                            .setRegionCodes(Arrays.asList("REGION_CODE")))
                          .setDefaultLocale("LOCALE")
                          // Create a map between the language code and the initial conversation settings
                          .setConversationalSettings(ImmutableMap.of("LOCALE",
                            new ConversationalSetting()
                                .setPrivacyPolicy(new PrivacyPolicy().setUrl("PRIVACY_POLICY_URL"))
                                .setWelcomeMessage(new WelcomeMessage().setText("WELCOME_MESSAGE"))
                                .setConversationStarters(Arrays.asList(
                                    new ConversationStarters().setSuggestion(new Suggestion()
                                        .setReply(new SuggestedReply().setText("SUGGESTION_TEXT").setPostbackData("SUGGESTION_POSTBACK_DATA")))
                                ))))
                          .setPrimaryAgentInteraction(new SupportedAgentInteraction()
                              .setInteractionType(InteractionType.HUMAN.toString())
                              .setHumanRepresentative(new HumanRepresentative()
                                  .setHumanMessagingAvailability(new MessagingAvailability()
                                      // Create a list of available hours
                                      .setHours(Arrays.asList(new Hours()
                                        .setStartTime(new TimeOfDay().setHours(START_TIME_HOURS).setMinutes(START_TIME_MINUTES))
                                        .setStartDay("BEGINNING_DAY_OF_WEEK")
                                        .setEndDay("END_DAY_OF_WEEK")
                                        .setEndTime(new TimeOfDay().setHours(END_TIME_HOURS).setMinutes(END_TIME_MINUTES))
                                        .setTimeZone("TIME_ZONE"))))))
    
                      ));
    
          Agent agent = request.execute();
    
          System.out.println(agent.toPrettyString());
        } catch (Exception e) {
          e.printStackTrace();
        }
      }
    }
    
    Этот код основан на клиентской библиотеке Java Business Communications .

    Питон

    
    """This code creates a Business Messages agent.
    
    Read more: https://developers.google.com/business-communications/business-messages/guides/how-to/agents?method=api#create_the_agent
    
    This code is based on the https://github.com/google-business-communications/python-businessmessages
    Python Business Messages client library.
    """
    
    from oauth2client.service_account import ServiceAccountCredentials
    from businesscommunications.businesscommunications_v1_client import BusinesscommunicationsV1
    from businesscommunications.businesscommunications_v1_messages import (
        Agent, BusinesscommunicationsBrandsAgentsCreateRequest,
        BusinessMessagesAgent, BusinessMessagesEntryPointConfig,
        ContactOption, ConversationalSetting, ConversationStarters,
        Hours, HumanRepresentative, MessagingAvailability,
        NonLocalConfig, Phone, PrivacyPolicy, Suggestion,
        SuggestedReply, SupportedAgentInteraction,
        TimeOfDay, WelcomeMessage
    )
    
    # Edit the values below:
    BRAND_ID = 'EDIT_HERE'
    SCOPES = ['https://www.googleapis.com/auth/businesscommunications']
    SERVICE_ACCOUNT_FILE = './service_account_key.json'
    
    credentials = ServiceAccountCredentials.from_json_keyfile_name(
        SERVICE_ACCOUNT_FILE, scopes=SCOPES)
    
    client = BusinesscommunicationsV1(credentials=credentials)
    
    agents_service = BusinesscommunicationsV1.BrandsAgentsService(client)
    
    brand_name = 'brands/ '+ BRAND_ID
    
    agent = Agent(
        displayName='My first agent',
        businessMessagesAgent=BusinessMessagesAgent(
            customAgentId='CUSTOM_ID', # Optional
            logoUrl='https://developers.google.com/identity/images/g-logo.png',
            entryPointConfigs=[BusinessMessagesEntryPointConfig(
                allowedEntryPoint=BusinessMessagesEntryPointConfig.AllowedEntryPointValueValuesEnum.LOCATION
            ), BusinessMessagesEntryPointConfig(
                allowedEntryPoint=BusinessMessagesEntryPointConfig.AllowedEntryPointValueValuesEnum.NON_LOCAL
            )],
            nonLocalConfig=NonLocalConfig(
                # List of phone numbers for call deflection, values must be globally unique
                # Generating a random phone number for demonstration purposes
                # This should be replaced with a real brand phone number
                callDeflectionPhoneNumbers=[Phone(number='+10000000000'),
                  Phone(number='+10000000001')],
                # Contact information for the agent that displays with the messaging button
                contactOption=ContactOption(
                        options=[ContactOption.OptionsValueListEntryValuesEnum.EMAIL,
                            ContactOption.OptionsValueListEntryValuesEnum.PHONE],
                        url='https://www.your-company-website.com'
                    ),
                # Domains enabled for messaging within Search, values must be globally unique
                # Generating a random URL for demonstration purposes
                # This should be replaced with a real brand URL
                enabledDomains=['your-company-website.com'],
                # Agent's phone number. Overrides the `phone` field for conversations started from non-local entry points
                phoneNumber=Phone(number='+10000000000'),
                # List of CLDR region codes for countries where the agent is allowed to launch `NON_LOCAL` entry points.
                # Example is for launching in Canada and the USA
                regionCodes=['US', 'CA']
            ),
            defaultLocale='en',
            conversationalSettings=BusinessMessagesAgent.ConversationalSettingsValue(
                additionalProperties=[BusinessMessagesAgent.ConversationalSettingsValue.AdditionalProperty(
                    key='en',
                    value=ConversationalSetting(
                        privacyPolicy=PrivacyPolicy(url='https://www.your-company-website.com/privacy'),
                        welcomeMessage=WelcomeMessage(text='This is a sample welcome message'),
                        conversationStarters=[
                            ConversationStarters(
                                suggestion=Suggestion(
                                    reply=SuggestedReply(text='Option 1',
                                                         postbackData='postback_option_1')
                                )
                            )
                        ]
                    )
                )]
            ),
            primaryAgentInteraction=SupportedAgentInteraction(
                interactionType=SupportedAgentInteraction.InteractionTypeValueValuesEnum.HUMAN,
                humanRepresentative=HumanRepresentative(
                    humanMessagingAvailability=MessagingAvailability(hours=[
                            Hours(
                                startTime=TimeOfDay(hours=8, minutes=30),
                                startDay=Hours.StartDayValueValuesEnum.MONDAY,
                                endDay=Hours.EndDayValueValuesEnum.SATURDAY,
                                endTime=TimeOfDay(hours=20, minutes=0),
                                timeZone='America/Los_Angeles'
                            )
                        ])
                )
            ),
        )
    )
    
    new_agent = agents_service.Create(
        BusinesscommunicationsBrandsAgentsCreateRequest(
            agent=agent,
            parent=brand_name
        )
    )
    
    print(new_agent)
    

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

  3. Если у бренда есть местоположения, которые вы хотите связать со своим агентом, см. раздел Добавление местоположений .

Пример. Создайте агента для банка Growing Tree Bank.

curl -X POST "https://businesscommunications.googleapis.com/v1/brands" \
-H "Content-Type: application/json" \
-H "User-Agent: curl/business-communications" \
-H "$(oauth2l header --json /path/to/service/account/key.json businesscommunications)" \
-d "{
    'displayName': 'Growing Tree Bank'
}"

# Fetch returned brand name value of "brands/12345"

curl -X POST "https://businesscommunications.googleapis.com/v1/brands/12345/agents" \
-H "Content-Type: application/json" \
-H "User-Agent: curl/business-communications" \
-H "$(oauth2l header --json /path/to/service/account/key.json businesscommunications)" \
-d "{
    'displayName': 'Growing Tree Bank',
    'businessMessagesAgent': {
        'logoUrl': 'https://www.growingtreebank.com/images/logo.png',
        'entryPointConfigs': [
          {
            'allowedEntryPoint': 'NON_LOCAL',
          },
          {
            'allowedEntryPoint': 'LOCATION',
          },
        ],
        'customAgentId': 'growing-tree-bank',
        'nonLocalConfig': {
            'regionCodes': ['001'],
            'contactOption': {
                'url': 'https://www.growingtreebank.com',
                'options': [
                    'EMAIL',
                    'PHONE',
                ],
            },
            'enabledDomains': [
                'https://www.growingtreebank.com',
            ],
            'phoneNumber': {
                'number': '+12223334444',
            },
            'callDeflectionPhoneNumbers': [
                {
                    'number': '+12223334444',
                },
                {
                    'number': '+56667778888',
                },
            ],
        },
        'conversationalSettings': {
            'en': {
                'welcomeMessage': {
                    'text': 'Thanks for contacting Growing Tree Bank. What can I help with today?',
                },
                'privacyPolicy': {
                    'url': 'https://www.growingtreebank.com/privacy',
                },
                'conversationStarters': [
                    {
                        'suggestion': {
                            'reply': {
                                'text': 'Set up an account',
                                'postbackData': 'new-account',
                            },
                        },
                    },
                ],
            },
        },
        'defaultLocale': 'en',
        'primaryAgentInteraction': {
            'interactionType': 'BOT',
            'botRepresentative': {
                'botMessagingAvailability': {
                    'hours': [
                        {
                            'startTime': {
                                'hours': '8',
                                'minutes': '00',
                            },
                            'endTime': {
                                'hours': '17',
                                'minutes': '30',
                            },
                            'timeZone': 'America/Los_Angeles',
                            'startDay': 'MONDAY',
                            'endDay': 'FRIDAY',
                        },
                    ],
                },
            },
        },
    },
}"

Храните важную информацию

Когда вы создаете агента, API бизнес-коммуникаций возвращает значения вашего агента, включая name и testUrls .

Установите вебхук на уровне агента

Вы получаете сообщения, отправленные вашему агенту, через вебхук. Если вы хотите, чтобы сообщения для определенного агента поступали на другой веб-перехватчик, вы можете установить веб-перехватчик на уровне агента.

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

Тестирование агента

У каждого агента есть тестовые URL-адреса, которые позволяют вам увидеть, как разговор с этим агентом отображается для пользователей, и дают вам возможность проверить вашу инфраструктуру обмена сообщениями.

TestUrl имеет атрибуты url и surface . Для тестирования на устройстве iOS используйте тестовый URL-адрес с поверхностным значением SURFACE_IOS_MAPS . Открытие URL-адреса на устройстве iOS, на котором установлено приложение Google Maps, открывает полнофункциональный диалог с агентом.

У устройств Android есть два тестовых URL-адреса. URL-адреса с surface значением SURFACE_ANDROID_MAPS открывают разговоры в Картах Google и представляют собой точки входа в диалог, которые появляются в Картах Google. URL-адреса с surface значением SURFACE_ANDROID_WEB открывают беседы в наложенном диалоговом представлении и представляют все остальные точки входа.

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

Чтобы открыть тестовый URL-адрес агента, коснитесь ссылки или воспользуйтесь средством запуска агента Business Messages на мобильном устройстве.

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

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

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

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

КУЛЬ


# This code gets the agent.
# Read more: https://developers.google.com/business-communications/business-messages/reference/business-communications/rest/v1/brands.agents/get

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

curl -X GET \
"https://businesscommunications.googleapis.com/v1/brands/__BRAND_ID__/agents/__AGENT_ID__" \
-H "Content-Type: application/json" \
-H "User-Agent: curl/business-communications" \
-H "$(oauth2l header --json ./service_account_key.json businesscommunications)"

Node.js


/**
 * This code snippet gets an agent.
 * Read more: https://developers.google.com/business-communications/business-messages/reference/business-communications/rest/v1/brands.agents/get
 *
 * This code is based on the https://github.com/google-business-communications/nodejs-businesscommunications Node.js
 * Business Communications client library.
 */

/**
 * Edit the values below:
 */
const BRAND_ID = 'EDIT_HERE';
const AGENT_ID = 'EDIT_HERE';
const PATH_TO_SERVICE_ACCOUNT_KEY = './service_account_key.json';

const businesscommunications = require('businesscommunications');
const {google} = require('googleapis');

// Initialize the Business Communications API
const bcApi = new businesscommunications.businesscommunications_v1.Businesscommunications({});

// Set the scope that we need for the Business Communications API
const scopes = [
  'https://www.googleapis.com/auth/businesscommunications',
];

// Set the private key to the service account file
const privatekey = require(PATH_TO_SERVICE_ACCOUNT_KEY);

async function main() {
  const authClient = await initCredentials();

  const agentName = 'brands/' + BRAND_ID + '/agents/' + AGENT_ID;

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

    bcApi.brands.agents.get(apiParams, {}, (err, response) => {
      if (err !== undefined && err !== null) {
        console.dir(err);
      } else {
        // Agent found
        console.log(response.data);
      }
    });
  }
  else {
    console.log('Authentication failure.');
  }
}

/**
 * Initializes the Google credentials for calling the
 * Business Messages API.
 */
 async function initCredentials() {
  // Configure a JWT auth client
  const authClient = new google.auth.JWT(
    privatekey.client_email,
    null,
    privatekey.private_key,
    scopes,
  );

  return new Promise(function(resolve, reject) {
    // Authenticate request
    authClient.authorize(function(err, tokens) {
      if (err) {
        reject(false);
      } else {
        resolve(authClient);
      }
    });
  });
}

main();

Джава

import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.services.businesscommunications.v1.BusinessCommunications;
import com.google.api.services.businesscommunications.v1.model.Agent;
import java.io.FileInputStream;
import java.util.Arrays;

class Main {
  /**
   * Initializes credentials used by the Business Communications API.
   */
  private static BusinessCommunications.Builder getBusinessCommunicationsBuilder() {
    BusinessCommunications.Builder builder = null;
    try {
      GoogleCredential credential = GoogleCredential
            .fromStream(new FileInputStream("PATH_TO_SERVICE_ACCOUNT_KEY"));

      credential = credential.createScoped(Arrays.asList(
          "https://www.googleapis.com/auth/businesscommunications"));

      credential.refreshToken();

      HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
      JacksonFactory jsonFactory = JacksonFactory.getDefaultInstance();

      // Create instance of the Business Communications API
      builder = new BusinessCommunications
          .Builder(httpTransport, jsonFactory, null)
          .setApplicationName(credential.getServiceAccountProjectId());

      // Set the API credentials and endpoint
      builder.setHttpRequestInitializer(credential);
    } catch (Exception e) {
      e.printStackTrace();
    }

    return builder;
  }

  public static void main(String args[]) {
    try {
      // Create client library reference
      BusinessCommunications.Builder builder = getBusinessCommunicationsBuilder();

      String agentName = "brands/BRAND_ID/agents/AGENT_ID";

      BusinessCommunications.Brands.Agents.Get request = builder
        .build().brands().agents().get(agentName);

      Agent agent = request.execute();

      System.out.println(agent.toPrettyString());
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
}
Этот код основан на клиентской библиотеке Java Business Communications .

Питон


"""This code gets the agent.

Read more: https://developers.google.com/business-communications/business-messages/reference/business-communications/rest/v1/brands.agents/get

This code is based on the https://github.com/google-business-communications/python-businessmessages
Python Business Messages client library.
"""

from oauth2client.service_account import ServiceAccountCredentials
from businesscommunications.businesscommunications_v1_client import BusinesscommunicationsV1
from businesscommunications.businesscommunications_v1_messages import (
    Agent,
    BusinesscommunicationsBrandsAgentsGetRequest,
)

# Edit the values below:
BRAND_ID = 'EDIT_HERE'
AGENT_ID = 'EDIT_HERE'
SCOPES = ['https://www.googleapis.com/auth/businesscommunications']
SERVICE_ACCOUNT_FILE = './service_account_key.json'

credentials = ServiceAccountCredentials.from_json_keyfile_name(
    SERVICE_ACCOUNT_FILE, scopes=SCOPES)

client = BusinesscommunicationsV1(credentials=credentials)

agents_service = BusinesscommunicationsV1.BrandsAgentsService(client)

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

agent = agents_service.Get(BusinesscommunicationsBrandsAgentsGetRequest(
        name=agent_name
    ))

print(agent)

Список всех агентов бренда

Если вы не знаете name агента, вы можете получить информацию обо всех агентах, связанных с брендом, опустив значение AGENT_ID в URL-адресе запроса GET.

КУЛЬ


# This code lists all agents from a brand.
# Read more: https://developers.google.com/business-communications/business-messages/reference/business-communications/rest/v1/brands.agents/list

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

curl -X GET \
"https://businesscommunications.googleapis.com/v1/brands/__BRAND_ID__/agents/" \
-H "Content-Type: application/json" \
-H "User-Agent: curl/business-communications" \
-H "$(oauth2l header --json ./service_account_key.json businesscommunications)"

Node.js


/**
 * This code snippet lists the agents of a brand.
 * Read more: https://developers.google.com/business-communications/business-messages/reference/business-communications/rest/v1/brands.agents/list
 *
 * This code is based on the https://github.com/google-business-communications/nodejs-businesscommunications Node.js
 * Business Communications client library.
 */

/**
 * Edit the values below:
 */
const BRAND_ID = 'EDIT_HERE';
const PATH_TO_SERVICE_ACCOUNT_KEY = './service_account_key.json';

const businesscommunications = require('businesscommunications');
const {google} = require('googleapis');

// Initialize the Business Communications API
const bcApi = new businesscommunications.businesscommunications_v1.Businesscommunications({});

// Set the scope that we need for the Business Communications API
const scopes = [
  'https://www.googleapis.com/auth/businesscommunications',
];

// Set the private key to the service account file
const privatekey = require(PATH_TO_SERVICE_ACCOUNT_KEY);

async function main() {
  const authClient = await initCredentials();

  const brandName = 'brands/' + BRAND_ID;

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

    bcApi.brands.agents.list(apiParams, {}, (err, response) => {
      if (err !== undefined && err !== null) {
        console.dir(err);
      } else {
        // Agent found
        console.log(response.data);
      }
    });
  }
  else {
    console.log('Authentication failure.');
  }
}

/**
 * Initializes the Google credentials for calling the
 * Business Messages API.
 */
 async function initCredentials() {
  // Configure a JWT auth client
  const authClient = new google.auth.JWT(
    privatekey.client_email,
    null,
    privatekey.private_key,
    scopes,
  );

  return new Promise(function(resolve, reject) {
    // Authenticate request
    authClient.authorize(function(err, tokens) {
      if (err) {
        reject(false);
      } else {
        resolve(authClient);
      }
    });
  });
}

main();

Джава

import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.services.businesscommunications.v1.BusinessCommunications;
import com.google.api.services.businesscommunications.v1.model.Agent;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

class Main {
  /**
   * Initializes credentials used by the Business Communications API.
   */
  private static BusinessCommunications.Builder getBusinessCommunicationsBuilder() {
    BusinessCommunications.Builder builder = null;
    try {
      GoogleCredential credential = GoogleCredential
            .fromStream(new FileInputStream("PATH_TO_SERVICE_ACCOUNT_KEY"));

      credential = credential.createScoped(Arrays.asList(
          "https://www.googleapis.com/auth/businesscommunications"));

      credential.refreshToken();

      HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
      JacksonFactory jsonFactory = JacksonFactory.getDefaultInstance();

      // Create instance of the Business Communications API
      builder = new BusinessCommunications
          .Builder(httpTransport, jsonFactory, null)
          .setApplicationName(credential.getServiceAccountProjectId());

      // Set the API credentials and endpoint
      builder.setHttpRequestInitializer(credential);
    } catch (Exception e) {
      e.printStackTrace();
    }

    return builder;
  }

  public static void main(String args[]) {
    try {
      // Create client library reference
      BusinessCommunications.Builder builder = getBusinessCommunicationsBuilder();

      String brandName = "brands/BRAND_ID";

      BusinessCommunications.Brands.Agents.List request = builder
          .build().brands().agents().list(brandName);

      List agents = request.execute().getAgents();
      agents.stream().forEach(agent -> {
        try {
          System.out.println(agent.toPrettyString());
        } catch (IOException e) {
          e.printStackTrace();
        }
      });
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
}
Этот код основан на клиентской библиотеке Java Business Communications .

Питон


"""This code lists all agents from a brand.

Read more: https://developers.google.com/business-communications/business-messages/reference/business-communications/rest/v1/brands.agents/list

This code is based on the https://github.com/google-business-communications/python-businessmessages
Python Business Messages client library.
"""

from oauth2client.service_account import ServiceAccountCredentials
from businesscommunications.businesscommunications_v1_client import BusinesscommunicationsV1
from businesscommunications.businesscommunications_v1_messages import (
    Agent,
    BusinesscommunicationsBrandsAgentsGetRequest,
)

# Edit the values below:
BRAND_ID = 'EDIT_HERE'
SCOPES = ['https://www.googleapis.com/auth/businesscommunications']
SERVICE_ACCOUNT_FILE = './service_account_key.json'

credentials = ServiceAccountCredentials.from_json_keyfile_name(
    SERVICE_ACCOUNT_FILE, scopes=SCOPES)

client = BusinesscommunicationsV1(credentials=credentials)

agents_service = BusinesscommunicationsV1.BrandsAgentsService(client)

brand_name = 'brands/' + BRAND_ID

agents = agents_service.List(BusinesscommunicationsBrandsAgentsListRequest(
        parent=brand_name
    ))

print(agents)

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

Чтобы обновить агента, вы выполняете запрос PATCH с помощью API бизнес-коммуникаций. Когда вы выполняете вызов API, вы включаете имена полей, которые вы редактируете, в качестве значений для параметра URL-адреса updateMask.

Например, если вы обновите поля displayName и customAgentId , параметр URL-адреса updateMask будет иметь значение «updateMask=displayName,businessMessagesAgent.customAgentId».

Параметры форматирования и значения см. в brands.agents.patch .

Если вы не знаете name агента, см. раздел Список всех агентов бренда .

После проверки агента вы можете обновить только следующие поля:

  • conversationalSetting

  • customAgentId

  • defaultLocale

  • primaryAgentInteraction

  • additionalAgentInteractions

  • phone

Если вам нужно обновить другие поля после подтверждения агента,свяжитесь с нами. (Сначала необходимо войти в систему с помощью учетной записи Google Business Messages. Чтобы зарегистрировать учетную запись, см. раздел Регистрация в Business Messages .)

Пример: обновить отображаемое имя

КУЛЬ

curl -X PATCH \
"https://businesscommunications.googleapis.com/v1/brands/BRAND_ID/agents/AGENT_ID?updateMask=displayName" \
-H "Content-Type: application/json" \
-H "User-Agent: curl/business-communications" \
-H "$(oauth2l header --json PATH_TO_SERVICE_ACCOUNT_KEY businesscommunications)" \
-d "{
    'displayName': 'Growing Tree Bank',
}"

Node.js

const businesscommunications = require('businesscommunications');
const {google} = require('googleapis');

// Initialize the Business Communications API
let bcApi = new businesscommunications.businesscommunications_v1.Businesscommunications({});

// Set the scope that we need for the Business Communications API
const scopes = [
  'https://www.googleapis.com/auth/businesscommunications',
];

// Set the private key to the service account file
const privatekey = require('PATH_TO_SERVICE_ACCOUNT_KEY');

/**
 * Initializes the Google credentials for calling the
 * Business Messages API.
 */
async function initCredentials() {
  // Configure a JWT auth client
  let authClient = new google.auth.JWT(
    privatekey.client_email,
    null,
    privatekey.private_key,
    scopes,
  );

  return new Promise(function(resolve, reject) {
    // Authenticate request
    authClient.authorize(function(err, tokens) {
      if (err) {
        reject(false);
      } else {
        resolve(authClient);
      }
    });
  });
}

async function main() {
  let authClient = await initCredentials();

  let agentName = 'brands/BRAND_ID/agents/AGENT_ID';

  if (authClient) {
    // Setup the parameters for the API call
    const apiParams = {
      auth: authClient,
      name: agentName,
      updateMask: 'displayName',
      resource: {
        displayName: 'Growing Tree Bank',
      }
    };

    bcApi.brands.agents.patch(apiParams, {}, (err, response) => {
      if (err !== undefined && err !== null) {
        console.dir(err);
      } else {
        // Agent found
        console.log(response.data);
      }
    });
  }
  else {
    console.log('Authentication failure.');
  }
}

main();
Этот код основан на клиентской библиотеке Node.js Business Communications .

Джава

import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.services.businesscommunications.v1.BusinessCommunications;
import com.google.api.services.businesscommunications.v1.model.Agent;
import java.io.FileInputStream;
import java.util.Arrays;

class Main {
  /**
   * Initializes credentials used by the Business Communications API.
   */
  private static BusinessCommunications.Builder getBusinessCommunicationsBuilder() {
    BusinessCommunications.Builder builder = null;
    try {
      GoogleCredential credential = GoogleCredential
            .fromStream(new FileInputStream("PATH_TO_SERVICE_ACCOUNT_KEY"));

      credential = credential.createScoped(Arrays.asList(
          "https://www.googleapis.com/auth/businesscommunications"));

      credential.refreshToken();

      HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
      JacksonFactory jsonFactory = JacksonFactory.getDefaultInstance();

      // Create instance of the Business Communications API
      builder = new BusinessCommunications
          .Builder(httpTransport, jsonFactory, null)
          .setApplicationName(credential.getServiceAccountProjectId());

      // Set the API credentials and endpoint
      builder.setHttpRequestInitializer(credential);
    } catch (Exception e) {
      e.printStackTrace();
    }

    return builder;
  }

  public static void main(String args[]) {
    try {
      // Create client library reference
      BusinessCommunications.Builder builder = getBusinessCommunicationsBuilder();

      String agentName = "brands/BRAND_ID/agents/AGENT_ID";

      Agent agent = new Agent().setDisplayName("Growing Tree Bank");

      BusinessCommunications.Brands.Agents.Patch request = builder
          .build().brands().agents().patch(agentName, agent);

      request.setUpdateMask("displayName");

      Agent updatedAgent = request.execute();
      System.out.println(updatedAgent.toPrettyString());
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
}
Этот код основан на клиентской библиотеке Java Business Communications .

Питон

from oauth2client.service_account import ServiceAccountCredentials
from businesscommunications.businesscommunications_v1_client import (
    BusinesscommunicationsV1
)
from businesscommunications.businesscommunications_v1_messages import (
    Agent,
    BusinesscommunicationsBrandsAgentsPatchRequest,
)

SCOPES = ['https://www.googleapis.com/auth/businesscommunications']
SERVICE_ACCOUNT_FILE = 'PATH_TO_SERVICE_ACCOUNT_KEY'

credentials = ServiceAccountCredentials.from_json_keyfile_name(
    SERVICE_ACCOUNT_FILE, scopes=SCOPES)

client = BusinesscommunicationsV1(credentials=credentials)

agents_service = BusinesscommunicationsV1.BrandsAgentsService(client)

agent_name = 'brands/BRAND_ID/agents/AGENT_ID'

agent=Agent(
          displayName='Growing Tree Bank'
      )

updated_agent = agents_service.Patch(
        BusinesscommunicationsBrandsAgentsPatchRequest(
            agent=agent,
            name=agent_name,
            updateMask='displayName'
        )
    )

print(updated_agent)
Этот код основан на клиентской библиотеке Python Business Communications .

Пример: укажите группы точек входа NON_LOCAL и LOCATION

КУЛЬ

curl -X PATCH \
"https://businesscommunications.googleapis.com/v1/brands/BRAND_ID/agents/AGENT_ID?updateMask=businessMessagesAgent.entryPointConfigs" \
-H "Content-Type: application/json" \
-H "User-Agent: curl/business-communications" \
-H "$(oauth2l header --json PATH_TO_SERVICE_ACCOUNT_KEY businesscommunications)" \
-d "{
  'businessMessagesAgent': {
    'entryPointConfigs': [
      {
        'allowedEntryPoint': 'NON_LOCAL',
      },
      {
        'allowedEntryPoint': 'LOCATION',
      },
    ],
  },
}"

Node.js

const businesscommunications = require('businesscommunications');
const {google} = require('googleapis');

// Initialize the Business Communications API
let bcApi = new businesscommunications.businesscommunications_v1.Businesscommunications({});

// Set the scope that we need for the Business Communications API
const scopes = [
  'https://www.googleapis.com/auth/businesscommunications',
];

// Set the private key to the service account file
const privatekey = require('PATH_TO_SERVICE_ACCOUNT_KEY');

/**
 * Initializes the Google credentials for calling the
 * Business Messages API.
 */
async function initCredentials() {
  // Configure a JWT auth client
  let authClient = new google.auth.JWT(
    privatekey.client_email,
    null,
    privatekey.private_key,
    scopes,
  );

  return new Promise(function(resolve, reject) {
    // Authenticate request
    authClient.authorize(function(err, tokens) {
      if (err) {
        reject(false);
      } else {
        resolve(authClient);
      }
    });
  });
}

async function main() {
  let authClient = await initCredentials();

  let agentName = 'brands/BRAND_ID/agents/AGENT_ID';

  if (authClient) {
    // Setup the parameters for the API call
    const apiParams = {
      auth: authClient,
      name: agentName,
      updateMask: 'businessMessagesAgent.entryPointConfigs',
      resource: {
        businessMessagesAgent: {
          entryPointConfigs: [
            {
              allowedEntryPoint: 'LOCATION',
            },
            {
              allowedEntryPoint: 'NON_LOCAL',
            },
          ],
        }
      }
    };

    bcApi.brands.agents.patch(apiParams, {}, (err, response) => {
      if (err !== undefined && err !== null) {
        console.dir(err);
      } else {
        // Agent found
        console.log(response.data);
      }
    });
  }
  else {
    console.log('Authentication failure.');
  }
}

main();
Этот код основан на клиентской библиотеке Node.js Business Communications .

Джава

import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.services.businesscommunications.v1.BusinessCommunications;
import com.google.api.services.businesscommunications.v1.model.*;
import java.io.FileInputStream;
import java.util.Arrays;

class Main {
  /**
   * Initializes credentials used by the Business Communications API.
   */
  private static BusinessCommunications.Builder getBusinessCommunicationsBuilder() {
    BusinessCommunications.Builder builder = null;
    try {
      GoogleCredential credential = GoogleCredential
            .fromStream(new FileInputStream("PATH_TO_SERVICE_ACCOUNT_KEY"));

      credential = credential.createScoped(Arrays.asList(
          "https://www.googleapis.com/auth/businesscommunications"));

      credential.refreshToken();

      HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
      JacksonFactory jsonFactory = JacksonFactory.getDefaultInstance();

      // Create instance of the Business Communications API
      builder = new BusinessCommunications
          .Builder(httpTransport, jsonFactory, null)
          .setApplicationName(credential.getServiceAccountProjectId());

      // Set the API credentials and endpoint
      builder.setHttpRequestInitializer(credential);
    } catch (Exception e) {
      e.printStackTrace();
    }

    return builder;
  }

  public static void main(String args[]) {
    try {
      // Create client library reference
      BusinessCommunications.Builder builder = getBusinessCommunicationsBuilder();

      String agentName = "brands/BRAND_ID/agents/AGENT_ID";

      Agent agent = new Agent().setBusinessMessagesAgent(
          new BusinessMessagesAgent().setEntryPointConfigs(Arrays.asList(
              new BusinessMessagesEntryPointConfig()
                  .setAllowedEntryPoint(
                      "NON_LOCAL"),
              new BusinessMessagesEntryPointConfig()
                  .setAllowedEntryPoint(
                      "LOCATION"))));

      BusinessCommunications.Brands.Agents.Patch request = builder
          .build().brands().agents().patch(agentName, agent);

      request.setUpdateMask("businessMessagesAgent.entryPointConfigs");

      Agent updatedAgent = request.execute();
      System.out.println(updatedAgent.toPrettyString());
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
}
Этот код основан на клиентской библиотеке Java Business Communications .

Питон

from oauth2client.service_account import ServiceAccountCredentials
from businesscommunications.businesscommunications_v1_client import (
    BusinesscommunicationsV1
)
from businesscommunications.businesscommunications_v1_messages import (
    Agent,
    BusinessMessagesAgent,
    BusinessMessagesEntryPointConfig,
    BusinesscommunicationsBrandsAgentsPatchRequest,
)

SCOPES = ['https://www.googleapis.com/auth/businesscommunications']
SERVICE_ACCOUNT_FILE = 'PATH_TO_SERVICE_ACCOUNT_KEY'

credentials = ServiceAccountCredentials.from_json_keyfile_name(
    SERVICE_ACCOUNT_FILE, scopes=SCOPES)

client = BusinesscommunicationsV1(credentials=credentials)

agents_service = BusinesscommunicationsV1.BrandsAgentsService(client)

agent_name = 'brands/BRAND_ID/agents/AGENT_ID'

agent=Agent(
    businessMessagesAgent=BusinessMessagesAgent(
        entryPointConfigs=[BusinessMessagesEntryPointConfig(
            allowedEntryPoint=BusinessMessagesEntryPointConfig.AllowedEntryPointValueValuesEnum.NON_LOCAL
        ), BusinessMessagesEntryPointConfig(
            allowedEntryPoint=BusinessMessagesEntryPointConfig.AllowedEntryPointValueValuesEnum.LOCATION
        )]
    )
)

updated_agent = agents_service.Patch(
        BusinesscommunicationsBrandsAgentsPatchRequest(
            agent=agent,
            name=agent_name,
            updateMask='businessMessagesAgent.entryPointConfigs'
        )
    )

print(updated_agent)
Этот код основан на клиентской библиотеке Python Business Communications .

Пример: Обновление приветственного сообщения

Если вы обновляете какое-либо поле в conversationalSettings , например, welcomeMessage , вам необходимо обновить все поля внутри объекта и указать локаль параметров (в виде двухсимвольного кода языка ISO 639-1 ).

КУЛЬ

curl -X PATCH \
"https://businesscommunications.googleapis.com/v1/brands/BRAND_ID/agents/AGENT_ID?updateMask=businessMessagesAgent.conversationalSettings.en" \
-H "Content-Type: application/json" \
-H "User-Agent: curl/business-communications" \
-H "$(oauth2l header --json PATH_TO_SERVICE_ACCOUNT_KEY businesscommunications)" \
-d "{
    'businessMessagesAgent': {
        'conversationalSettings': {
            'en': {
                'welcomeMessage': {
                    'text': 'Thanks for contacting Growing Tree Bank. What can I help with today?',
                },
                'offlineMessage': {
                    'text': 'We\'re closed for the night. Please reach out to us again tomorrow.',
                },
                'privacyPolicy': {
                    'url': 'https://www.growingtreebank.com/privacy',
                },
                'conversationStarters': [
                    {
                        'suggestion': {
                            'reply': {
                                'text': 'Set up an account',
                                'postbackData': 'new-account',
                            },
                        },
                    },
                    {
                        'suggestion': {
                            'reply': {
                                'text': 'Look up account information',
                                'postbackData': 'account-lookup',
                            },
                        },
                    },
                ],
            },
        },
    },
}"

Node.js

const businesscommunications = require('businesscommunications');
const {google} = require('googleapis');

// Initialize the Business Communications API
let bcApi = new businesscommunications.businesscommunications_v1.Businesscommunications({});

// Set the scope that we need for the Business Communications API
const scopes = [
  'https://www.googleapis.com/auth/businesscommunications',
];

// Set the private key to the service account file
const privatekey = require('PATH_TO_SERVICE_ACCOUNT_KEY');

/**
 * Initializes the Google credentials for calling the
 * Business Messages API.
 */
async function initCredentials() {
  // Configure a JWT auth client
  let authClient = new google.auth.JWT(
    privatekey.client_email,
    null,
    privatekey.private_key,
    scopes,
  );

  return new Promise(function(resolve, reject) {
    // Authenticate request
    authClient.authorize(function(err, tokens) {
      if (err) {
        reject(false);
      } else {
        resolve(authClient);
      }
    });
  });
}

async function main() {
  let authClient = await initCredentials();

  let agentName = 'brands/BRAND_ID/agents/AGENT_ID';

  if (authClient) {
    // Setup the parameters for the API call
    const apiParams = {
      auth: authClient,
      name: agentName,
      updateMask: 'businessMessagesAgent.conversationalSettings.en',
      resource: {
        businessMessagesAgent: {
          conversationalSettings: {
            en: {
              privacyPolicy: { url: 'https://www.growingtreebank.com/privacy' },
              welcomeMessage: { text: 'Thanks for contacting Growing Tree Bank. What can I help with today?' },
              offlineMessage: { text: 'We\'re closed for the night. Please reach out to us again tomorrow.' },
              conversationStarters: [
                {
                  suggestion: {
                    reply: {
                      text: 'Set up an account',
                      postbackData: 'new-account',
                    },
                  },
                },
                {
                  suggestion: {
                    reply: {
                      text: 'Look up account information',
                      postbackData: 'account-lookup',
                    },
                  },
                },
              ],
            },
          }
        }
      }
    };

    bcApi.brands.agents.patch(apiParams, {}, (err, response) => {
      if (err !== undefined && err !== null) {
        console.dir(err);
      } else {
        // Agent found
        console.log(response.data);
      }
    });
  }
  else {
    console.log('Authentication failure.');
  }
}

main();
Этот код основан на клиентской библиотеке Node.js Business Communications .

Джава

import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.services.businesscommunications.v1.BusinessCommunications;
import com.google.api.services.businesscommunications.v1.model.*;
import com.google.common.collect.ImmutableMap;
import java.io.FileInputStream;
import java.util.Arrays;

class Main {
  /**
   * Initializes credentials used by the Business Communications API.
   */
  private static BusinessCommunications.Builder getBusinessCommunicationsBuilder() {
    BusinessCommunications.Builder builder = null;
    try {
      GoogleCredential credential = GoogleCredential
            .fromStream(new FileInputStream("PATH_TO_SERVICE_ACCOUNT_KEY"));

      credential = credential.createScoped(Arrays.asList(
          "https://www.googleapis.com/auth/businesscommunications"));

      credential.refreshToken();

      HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
      JacksonFactory jsonFactory = JacksonFactory.getDefaultInstance();

      // Create instance of the Business Communications API
      builder = new BusinessCommunications
          .Builder(httpTransport, jsonFactory, null)
          .setApplicationName(credential.getServiceAccountProjectId());

      // Set the API credentials and endpoint
      builder.setHttpRequestInitializer(credential);
    } catch (Exception e) {
      e.printStackTrace();
    }

    return builder;
  }

  public static void main(String args[]) {
    try {
      // Create client library reference
      BusinessCommunications.Builder builder = getBusinessCommunicationsBuilder();

      String agentName = "brands/BRAND_ID/agents/AGENT_ID";

      Agent agent = new Agent().setBusinessMessagesAgent(
          new BusinessMessagesAgent().setConversationalSettings(ImmutableMap.of("en",
              new ConversationalSetting()
                  .setPrivacyPolicy(new PrivacyPolicy().setUrl("https://www.growingtreebank.com/privacy"))
                  .setWelcomeMessage(new WelcomeMessage().setText("Thanks for contacting Growing Tree Bank. What can I help with today?"))
                  .setOfflineMessage(new OfflineMessage().setText("We're closed for the night. Please reach out to us again tomorrow."))
                  .setConversationStarters(Arrays.asList(
                      new ConversationStarters().setSuggestion(new Suggestion()
                          .setReply(new SuggestedReply()
                              .setText("Set up an account")
                              .setPostbackData("new-account"))),
                      new ConversationStarters().setSuggestion(new Suggestion()
                          .setReply(new SuggestedReply()
                              .setText("Look up account information")
                              .setPostbackData("account-lookup")))
                      )))));

      BusinessCommunications.Brands.Agents.Patch request = builder
          .build().brands().agents().patch(agentName, agent);

      request.setUpdateMask("businessMessagesAgent.conversationalSettings.en");

      Agent updatedAgent = request.execute();
      System.out.println(updatedAgent.toPrettyString());
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
}
Этот код основан на клиентской библиотеке Java Business Communications .

Питон

from oauth2client.service_account import ServiceAccountCredentials
from businesscommunications.businesscommunications_v1_client import (
    BusinesscommunicationsV1
)
from businesscommunications.businesscommunications_v1_messages import (
    Agent,
    BusinessMessagesAgent,
    ConversationStarters,
    ConversationalSetting,
    OfflineMessage,
    PrivacyPolicy,
    WelcomeMessage,
    BusinesscommunicationsBrandsAgentsPatchRequest,
)

SCOPES = ['https://www.googleapis.com/auth/businesscommunications']
SERVICE_ACCOUNT_FILE = 'PATH_TO_SERVICE_ACCOUNT_KEY'

credentials = ServiceAccountCredentials.from_json_keyfile_name(
    SERVICE_ACCOUNT_FILE, scopes=SCOPES)

client = BusinesscommunicationsV1(credentials=credentials)

agents_service = BusinesscommunicationsV1.BrandsAgentsService(client)

agent_name = 'brands/BRAND_ID/agents/AGENT_ID'

agent=Agent(
		businessMessagesAgent=BusinessMessagesAgent(
		  	conversationalSettings=BusinessMessagesAgent.ConversationalSettingsValue(
		        additionalProperties=[BusinessMessagesAgent.ConversationalSettingsValue.AdditionalProperty(
		            key='en',
		            value=ConversationalSetting(
		                privacyPolicy=PrivacyPolicy(url='https://www.growingtreebank.com/privacy'),
		                welcomeMessage=WelcomeMessage(text='Thanks for contacting Growing Tree Bank. What can I help with today?'),
		                offlineMessage=OfflineMessage(text='We\'re closed for the night. Please reach out to us again tomorrow.'),
		                conversationStarters=[
		                    ConversationStarters(
		                        suggestion=Suggestion(
		                            reply=SuggestedReply(text='Set up an account',
		                                postbackData='new-account')
		                        )
		                    ),
		                    ConversationStarters(
		                        suggestion=Suggestion(
		                            reply=SuggestedReply(text='Look up account information',
		                                postbackData='account-lookup')
		                        )
		                    )]
		                )
		            )
		        ]
		    )
		)
)

updated_agent = agents_service.Patch(
        BusinesscommunicationsBrandsAgentsPatchRequest(
            agent=agent,
            name=agent_name,
            updateMask='businessMessagesAgent.conversationalSettings.en'
        )
    )

print(updated_agent)
Этот код основан на клиентской библиотеке Python Business Communications .

Удаление агента

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

Запросы на удаление завершаются неудачей, если у агента есть связанное местоположение или если вы пытались проверить агента один или несколько раз. Чтобы обновить местоположения, см. раздел Добавление местоположений .

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

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

КУЛЬ


# This code deletes an agent.
# Read more: https://developers.google.com/business-communications/business-messages/reference/business-communications/rest/v1/brands.agents/delete

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

curl -X DELETE "https://businesscommunications.googleapis.com/v1/brands/__BRAND_ID__/agents/__AGENT_ID__" \
-H "Content-Type: application/json" \
-H "User-Agent: curl/business-communications" \
-H "$(oauth2l header --json ./service_account_key.json businesscommunications)"

Node.js


/**
 * This code snippet deletes an agent.
 * Read more: https://developers.google.com/business-communications/business-messages/reference/business-communications/rest/v1/brands.agents/delete
 *
 * This code is based on the https://github.com/google-business-communications/nodejs-businesscommunications Node.js
 * Business Communications client library.
 */

/**
 * Edit the values below:
 */
const BRAND_ID = 'EDIT_HERE';
const AGENT_ID = 'EDIT_HERE';
const PATH_TO_SERVICE_ACCOUNT_KEY = './service_account_key.json';

const businesscommunications = require('businesscommunications');
const {google} = require('googleapis');

// Initialize the Business Communications API
const bcApi = new businesscommunications.businesscommunications_v1.Businesscommunications({});

// Set the scope that we need for the Business Communications API
const scopes = [
  'https://www.googleapis.com/auth/businesscommunications',
];

// Set the private key to the service account file
const privatekey = require(PATH_TO_SERVICE_ACCOUNT_KEY);

async function main() {
  const authClient = await initCredentials();

  const agentName = 'brands/' + BRAND_ID + '/agents/' + AGENT_ID;

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

    bcApi.brands.agents.delete(apiParams, {}, (err, response) => {
      if (err !== undefined && err !== null) {
        console.dir(err);
      } else {
        // Agent removed
        console.log(response.data);
      }
    });
  }
  else {
    console.log('Authentication failure.');
  }
}

/**
 * Initializes the Google credentials for calling the
 * Business Messages API.
 */
 async function initCredentials() {
  // Configure a JWT auth client
  const authClient = new google.auth.JWT(
    privatekey.client_email,
    null,
    privatekey.private_key,
    scopes,
  );

  return new Promise(function(resolve, reject) {
    // Authenticate request
    authClient.authorize(function(err, tokens) {
      if (err) {
        reject(false);
      } else {
        resolve(authClient);
      }
    });
  });
}

main();

Джава

import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.services.businesscommunications.v1.BusinessCommunications;
import com.google.api.services.businesscommunications.v1.model.*;
import java.io.FileInputStream;
import java.util.Arrays;

class Main {
  /**
   * Initializes credentials used by the Business Communications API.
   */
  private static BusinessCommunications.Builder getBusinessCommunicationsBuilder() {
    BusinessCommunications.Builder builder = null;
    try {
      GoogleCredential credential = GoogleCredential
            .fromStream(new FileInputStream("PATH_TO_SERVICE_ACCOUNT_KEY"));

      credential = credential.createScoped(Arrays.asList(
          "https://www.googleapis.com/auth/businesscommunications"));

      credential.refreshToken();

      HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
      JacksonFactory jsonFactory = JacksonFactory.getDefaultInstance();

      // Create instance of the Business Communications API
      builder = new BusinessCommunications
          .Builder(httpTransport, jsonFactory, null)
          .setApplicationName(credential.getServiceAccountProjectId());

      // Set the API credentials and endpoint
      builder.setHttpRequestInitializer(credential);
    } catch (Exception e) {
      e.printStackTrace();
    }

    return builder;
  }

  public static void main(String args[]) {
    try {
      // Create client library reference
      BusinessCommunications.Builder builder = getBusinessCommunicationsBuilder();

      String agentName = "brands/BRAND_ID/agents/AGENT_ID";

      BusinessCommunications.Brands.Agents.Delete request
         = builder.build().brands().agents().delete(agentName);

      System.out.println(request.execute());
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
}
Этот код основан на клиентской библиотеке Java Business Communications .

Питон


"""This code deletes an agent.

Read more: https://developers.google.com/business-communications/business-messages/reference/business-communications/rest/v1/brands.agents/delete

This code is based on the https://github.com/google-business-communications/python-businessmessages
Python Business Messages client library.
"""

from oauth2client.service_account import ServiceAccountCredentials
from businesscommunications.businesscommunications_v1_client import BusinesscommunicationsV1
from businesscommunications.businesscommunications_v1_messages import (
    Agent,
    BusinesscommunicationsBrandsAgentsDeleteRequest,
)

# Edit the values below:
BRAND_ID = 'EDIT_HERE'
AGENT_ID = 'EDIT_HERE'
SCOPES = ['https://www.googleapis.com/auth/businesscommunications']
SERVICE_ACCOUNT_FILE = './service_account_key.json'

credentials = ServiceAccountCredentials.from_json_keyfile_name(
    SERVICE_ACCOUNT_FILE, scopes=SCOPES)

client = BusinesscommunicationsV1(credentials=credentials)

agents_service = BusinesscommunicationsV1.BrandsAgentsService(client)

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

agent = agents_service.Delete(BusinesscommunicationsBrandsAgentsDeleteRequest(
        name=agent_name
    ))

print(agent)

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

Удалить бренд

Когда вы удаляете бренд, вы выполняете запрос DELETE с помощью API бизнес-коммуникаций. Запросы на удаление не выполняются, если у вас есть один или несколько агентов или местоположений, связанных с брендом, даже если эти агенты относятся к другому продукту.

Чтобы удалить бренд, выполните следующую команду. Замените BRAND_ID уникальным значением name бренда.

КУЛЬ


# This code deletes a brand.
# Read more: https://developers.google.com/business-communications/business-messages/reference/business-communications/rest/v1/brands/delete

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

curl -X DELETE "https://businesscommunications.googleapis.com/v1/brands/__BRAND_ID__" \
-H "Content-Type: application/json" \
-H "User-Agent: curl/business-communications" \
-H "$(oauth2l header --json ./service_account_key.json businesscommunications)"

Node.js


/**
 * This code snippet deletes a brand.
 * Read more: https://developers.google.com/business-communications/business-messages/reference/business-communications/rest/v1/brands/delete
 *
 * This code is based on the https://github.com/google-business-communications/nodejs-businesscommunications Node.js
 * Business Communications client library.
 */

/**
 * Edit the values below:
 */
const BRAND_ID = 'EDIT_HERE';
const PATH_TO_SERVICE_ACCOUNT_KEY = './service_account_key.json';

const businesscommunications = require('businesscommunications');
const {google} = require('googleapis');

// Initialize the Business Communications API
const bcApi = new businesscommunications.businesscommunications_v1.Businesscommunications({});

// Set the scope that we need for the Business Communications API
const scopes = [
  'https://www.googleapis.com/auth/businesscommunications',
];

// Set the private key to the service account file
const privatekey = require(PATH_TO_SERVICE_ACCOUNT_KEY);

async function main() {
  const authClient = await initCredentials();

  const brandName = 'brands/' + BRAND_ID;

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

    bcApi.brands.delete(apiParams, {}, (err, response) => {
      if (err !== undefined && err !== null) {
        console.dir(err);
      } else {
        // Brand removed
        console.log(response.data);
      }
    });
  }
  else {
    console.log('Authentication failure.');
  }
}

/**
 * Initializes the Google credentials for calling the
 * Business Messages API.
 */
 async function initCredentials() {
  // Configure a JWT auth client
  const authClient = new google.auth.JWT(
    privatekey.client_email,
    null,
    privatekey.private_key,
    scopes,
  );

  return new Promise(function(resolve, reject) {
    // Authenticate request
    authClient.authorize(function(err, tokens) {
      if (err) {
        reject(false);
      } else {
        resolve(authClient);
      }
    });
  });
}

main();

Джава

import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.services.businesscommunications.v1.BusinessCommunications;
import com.google.api.services.businesscommunications.v1.model.*;
import java.io.FileInputStream;
import java.util.Arrays;

class Main {
  /**
   * Initializes credentials used by the Business Communications API.
   */
  private static BusinessCommunications.Builder getBusinessCommunicationsBuilder() {
    BusinessCommunications.Builder builder = null;
    try {
      GoogleCredential credential = GoogleCredential
            .fromStream(new FileInputStream("PATH_TO_SERVICE_ACCOUNT_KEY"));

      credential = credential.createScoped(Arrays.asList(
          "https://www.googleapis.com/auth/businesscommunications"));

      credential.refreshToken();

      HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
      JacksonFactory jsonFactory = JacksonFactory.getDefaultInstance();

      // Create instance of the Business Communications API
      builder = new BusinessCommunications
          .Builder(httpTransport, jsonFactory, null)
          .setApplicationName(credential.getServiceAccountProjectId());

      // Set the API credentials and endpoint
      builder.setHttpRequestInitializer(credential);
    } catch (Exception e) {
      e.printStackTrace();
    }

    return builder;
  }

  public static void main(String args[]) {
    try {
      // Create client library reference
      BusinessCommunications.Builder builder = getBusinessCommunicationsBuilder();

      String brandName = "brands/BRAND_ID";

      BusinessCommunications.Brands.Delete request = builder.build().brands().delete(brandName);

      System.out.println(request.execute());
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
}
Этот код основан на клиентской библиотеке Java Business Communications .

Питон


"""This code deletes a brand.

Read more: https://developers.google.com/business-communications/business-messages/reference/business-communications/rest/v1/brands/delete

This code is based on the https://github.com/google-business-communications/python-businessmessages
Python Business Messages client library.
"""

from oauth2client.service_account import ServiceAccountCredentials
from businesscommunications.businesscommunications_v1_client import BusinesscommunicationsV1
from businesscommunications.businesscommunications_v1_messages import (
    BusinesscommunicationsBrandsAgentsDeleteRequest
)

# Edit the values below:
BRAND_ID = 'EDIT_HERE'
SCOPES = ['https://www.googleapis.com/auth/businesscommunications']
SERVICE_ACCOUNT_FILE = './service_account_key.json'

credentials = ServiceAccountCredentials.from_json_keyfile_name(
    SERVICE_ACCOUNT_FILE, scopes=SCOPES)

client = BusinesscommunicationsV1(credentials=credentials)

agents_service = BusinesscommunicationsV1.BrandsAgentsService(client)

brand_name = 'brands/' + BRAND_ID

agent = agents_service.Delete(BusinesscommunicationsBrandsAgentsDeleteRequest(
        name=brand_name
    ))

print(agent)

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

Следующие шаги

Теперь, когда у вас есть агент, вы можете предпринять следующие шаги:

,

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

Агент — это диалоговая сущность, с которой взаимодействуют пользователи. Вы создаете одного агента для каждого бренда, которым управляете. Вы создаете агентов и управляете ими с помощью API бизнес-коммуникаций, а также управляете обменом сообщениями для своих агентов с помощью API бизнес-сообщений.

Агент включает в себя бизнес-функции бренда, такие как онлайн-поддержка и физическое местоположение (если таковое имеется). Каждое сообщение содержит контекст, из которого пользователь инициировал разговор. Ваша инфраструктура маршрутизации сообщений может определить, просматривал ли пользователь определенное местоположение компании или искал общую поддержку, и может направлять сообщения в правильный пункт назначения.

Отношения агент/бренд

Например, если вы управляете брендом Growing Tree Bank, у которого есть веб-сайт и два офиса, вы создаете одного агента Growing Tree Bank. Пользователи могут столкнуться с агентом посредством общего поиска или поиска по местоположению, а контекст, в котором пользователь нашел агента, передается вместе с каждым сообщением в ваш веб-перехватчик. Вы используете этот контекст для маршрутизации сообщения либо сотрудникам в определенном месте, либо команде поддержки веб-сайта, которая создает ответ и продолжает разговор с пользователем.

Ожидания

Прежде чем создавать агента, уясните ожидания агентов в отношении Business Messages.

Создать агента

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

Если вы управляете несколькими брендами, повторите шаги, чтобы создать агента для каждого бренда.

Предварительные условия

Прежде чем создавать агентов для брендов, которыми вы управляете, вам необходимо собрать некоторую информацию:

Среда разработки

Информация о вашей среде разработки.

Подробности о бренде

Информация о бренде, который представляет агент.

  • Имя бренда
  • Сайт бренда
  • Варианты связи на веб-сайте (как определено в OPTION )
  • Телефонный номер, ориентированный на потребителя
  • Телефонные номера, на которых разрешено отклонение вызовов

Внешний вид и политика агента

Информация о том, как агент выглядит для пользователей и как он работает.

  • Имя агента, какое вы хотите, чтобы оно отображалось в разговорах с пользователями.
  • Политика конфиденциальности в виде общедоступного URL-адреса, начинающегося с «https://».
  • (Рекомендуется) Логотип агента (1024x1024 пикселей) в виде общедоступного URL-адреса.

    В разговоре логотипы отображаются в виде кругов диаметром 1024 пикселя. Убедитесь, что ваш логотип хорошо отображается в виде круга.

  • (Необязательно) Пользовательский идентификатор агента, который идентифицирует бренд в сообщениях, которые получает вебхук.

Взаимодействие с агентом

Информация о том, как ваш агент взаимодействует с пользователями.

  • Языковой стандарт, в котором обычно работает ваш агент, указанный двухзначным кодом языка ISO 639-1.

  • Приветственное сообщение агента

    Что говорит агент, приветствуя пользователей?

  • Начало разговора с агентом

    Список предложений в виде фрагментов разговора (как определено в OfferedReply ), которые пользователь может взаимодействовать с агентом.

    • Текст, отображаемый пользователю в чипе
    • Данные обратной передачи, строка, отправляемая обратно на ваш веб-перехватчик в полезных данных сообщения, если пользователь касается чипа.
  • Время автоматического и живого чата

    • Ежедневное время начала как объект TimeOfDay

      Например, 8:15 утра

      {
        "hours": 8,
        "minutes": 15,
      }
      
    • Время окончания дня как объект TimeOfDay

      Например, 19:30

      {
        "hours": 19,
        "minutes": 30,
      }
      
    • День начала, первый день недели, когда агент доступен для чата (как определено в DayOfWeek ).

    • Конечный день — последний день недели, когда агент доступен для чата (как определено в DayOfWeek ).

    • Часовой пояс, в котором работает агент (как определено в базе данных часовых поясов IANA , например «Америка/Лос-Анджелес»)

Точки входа агента

Информация о том, где пользователи могут начать общение с агентом.

  • Разрешенные точки входа агента, где пользователи могут начинать разговор с агентами ( NON_LOCAL и/или LOCATION ).

Информация о точках входа NON_LOCAL (не относится к точке входа Google Ads ).

  • Разрешенные регионы (как коды регионов CLDR ), чтобы ограничить региональный доступ к точкам входа NON_LOCAL .

    Независимо от региона, с агентом может быть связан только один номер телефона. Если вам нужен другой номер телефона в зависимости от региона, для каждого региона необходимо создать отдельного агента.

    Чтобы включить точки входа NON_LOCAL во всех доступных регионах, используйте 001 для кода региона «Мир».

Установите и протестируйте oauth2l

Все запросы на завитки в документации этого сайта используют oauth2l для аутентификации. Если вы хотите использовать командную строку для подключения к API бизнес-коммуникаций и бизнес-сообщений, установите файл oauth2l.

Чтобы установить oauth2l с Python 3,

  1. Загрузите oauth2l .

  2. Измените каталог на «./oauth2l/python».

  3. Установите oauth2l с помощью следующей команды.

    sudo python setup.sh build && sudo python setup.py install
    
  4. Проверьте, может ли oauth2l генерировать токен авторизации.

    oauth2l header --json resources/bm-agent-service-account-credentials.json businesscommunications
    
  5. Убедитесь, что выходные данные создают токен авторизации в форме:

    Authorization: Bearer AUTHORIZATION_BEARER_TOKEN
    

Есть и другие способы установки oauth2l для разных операционных систем. Независимо от метода установки, прежде чем продолжить, убедитесь, что вы можете создать токен авторизации на основе учетных данных JSON учетной записи службы.

Создать агент

После того, как вы собрали всю информацию, пришло время создать своего агента.

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

    В терминале выполните следующую команду:

    КУЛЬ

    
    # This code creates a brand.
    # Read more: https://developers.google.com/business-communications/business-messages/reference/business-communications/rest/v1/brands/create
    
    # Make sure a service account key file exists at ./service_account_key.json
    
    curl -X POST "https://businesscommunications.googleapis.com/v1/brands" \
    -H "Content-Type: application/json" \
    -H "User-Agent: curl/business-communications" \
    -H "$(oauth2l header --json ./service_account_key.json businesscommunications)" \
    -d '{
      "displayName": "My first brand curl"
    }'
    

    Node.js

    
    /**
     * This code snippet creates a brand.
     * Read more: https://developers.google.com/business-communications/business-messages/reference/business-communications/rest/v1/brands/create
     *
     * This code is based on the https://github.com/google-business-communications/nodejs-businesscommunications Node.js
     * Business Communications client library.
     */
    
    /**
     * Edit the values below:
     */
    const PATH_TO_SERVICE_ACCOUNT_KEY = './service_account_key.json';
    
    const businesscommunications = require('businesscommunications');
    const {google} = require('googleapis');
    
    // Initialize the Business Communications API
    const bcApi = new businesscommunications.businesscommunications_v1.Businesscommunications({});
    
    // Set the scope that we need for the Business Communications API
    const scopes = [
      'https://www.googleapis.com/auth/businesscommunications',
    ];
    
    // Set the private key to the service account file
    const privatekey = require(PATH_TO_SERVICE_ACCOUNT_KEY);
    
    async function main() {
      const authClient = await initCredentials();
    
      if (authClient) {
        // Setup the parameters for the API call
        const apiParams = {
          auth: authClient,
          resource: {
            displayName: 'My first brand',
          },
        };
    
        bcApi.brands.create(apiParams, {}, (err, response) => {
          if (err !== undefined && err !== null) {
            console.dir(err);
          } else {
            // Brand created
            console.log(response.data);
          }
        });
      }
      else {
        console.log('Authentication failure.');
      }
    }
    
    /**
     * Initializes the Google credentials for calling the
     * Business Communcations API.
     */
     async function initCredentials() {
      // configure a JWT auth client
      const authClient = new google.auth.JWT(
        privatekey.client_email,
        null,
        privatekey.private_key,
        scopes,
      );
    
      return new Promise(function(resolve, reject) {
        // authenticate request
        authClient.authorize(function(err, tokens) {
          if (err) {
            reject('Failed to connect');
          } else {
            resolve(authClient);
          }
        });
      })
    }
    
    main();
    

    Джава

    import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
    import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
    import com.google.api.client.http.HttpTransport;
    import com.google.api.client.json.jackson2.JacksonFactory;
    import com.google.api.services.businesscommunications.v1.BusinessCommunications;
    import com.google.api.services.businesscommunications.v1.model.Brand;
    import java.io.FileInputStream;
    import java.util.Arrays;
    import java.util.UUID;
    
    class Main {
      /**
       * Initializes credentials used by the Business Communications API.
       */
      private static BusinessCommunications.Builder getBusinessCommunicationsBuilder() {
        BusinessCommunications.Builder builder = null;
        try {
          GoogleCredential credential = GoogleCredential
                .fromStream(new FileInputStream("PATH_TO_SERVICE_ACCOUNT_KEY"));
    
          credential = credential.createScoped(Arrays.asList(
              "https://www.googleapis.com/auth/businesscommunications"));
    
          credential.refreshToken();
    
          HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
          JacksonFactory jsonFactory = JacksonFactory.getDefaultInstance();
    
          // Create instance of the Business Communications API
          builder = new BusinessCommunications
              .Builder(httpTransport, jsonFactory, null)
              .setApplicationName(credential.getServiceAccountProjectId());
    
          // Set the API credentials and endpoint
          builder.setHttpRequestInitializer(credential);
        } catch (Exception e) {
          e.printStackTrace();
        }
    
        return builder;
      }
    
      public static void main(String args[]) {
        try {
          // Create client library reference
          BusinessCommunications.Builder builder = getBusinessCommunicationsBuilder();
    
          // Create a request to create a new brand
          BusinessCommunications.Brands.Create request = builder
              .build().brands().create(new Brand().setDisplayName("BRAND_NAME"));
    
          Brand brand = request.execute();
    
          // Print newly created brand object
          System.out.println(brand.toPrettyString());
        } catch (Exception e) {
          e.printStackTrace();
        }
      }
    }
    
    Этот код основан на клиентской библиотеке Java Business Communications .

    Питон

    
    """This code creates a brand.
    
    Read more: https://developers.google.com/business-communications/business-messages/reference/business-communications/rest/v1/brands/create
    
    This code is based on the https://github.com/google-business-communications/python-businessmessages
    Python Business Messages client library.
    """
    
    from oauth2client.service_account import ServiceAccountCredentials
    from businesscommunications.businesscommunications_v1_client import BusinesscommunicationsV1
    from businesscommunications.businesscommunications_v1_messages import (
        Brand)
    
    # Edit the values below:
    SCOPES = ['https://www.googleapis.com/auth/businesscommunications']
    SERVICE_ACCOUNT_FILE = './service_account_key.json'
    
    credentials = ServiceAccountCredentials.from_json_keyfile_name(
        SERVICE_ACCOUNT_FILE, scopes=SCOPES)
    
    client = BusinesscommunicationsV1(credentials=credentials)
    
    brands_service = BusinesscommunicationsV1.BrandsService(client)
    
    brand = brands_service.Create(Brand(displayName='My first brand'))
    
    print(brand)
    

    Сохраните значение name , которое возвращает API. Он понадобится вам для обновления или создания агентов.

    Чтобы обновить или найти бренды, см. brands .

  2. Создайте агента. Замените BRAND_ID частью значения name бренда, которая следует за «brands/». Например, если name — «brands/12345», идентификатор бренда — «12345».

    В терминале выполните следующую команду:

    КУЛЬ

    
    # This code creates a Business Messages agent.
    # Read more: https://developers.google.com/business-communications/business-messages/guides/how-to/agents?method=api#create_the_agent
    
    # Replace the __BRAND_ID__ with a brand id that you can create agents for
    # Make sure a service account key file exists at ./service_account_key.json
    
    curl -X POST "https://businesscommunications.googleapis.com/v1/brands/__BRAND_ID__/agents" \
    -H "Content-Type: application/json" \
    -H "User-Agent: curl/business-communications" \
    -H "$(oauth2l header --json ./service_account_key.json businesscommunications)" \
    -d '{
      "displayName": "My first agent",
      "businessMessagesAgent": {
        "logoUrl": "https://developers.google.com/identity/images/g-logo.png",
        "entryPointConfigs": [
          {
            "allowedEntryPoint": "NON_LOCAL"
          }
        ],
        "customAgentId": "'$(uuidgen)'",
        "nonLocalConfig": {
          "regionCodes": [
            "US",
            "CA"
          ],
          "contactOption": {
            "url": "https://www.your-company-website.com",
            "options": [
              "EMAIL",
              "PHONE"
            ]
          },
          "enabledDomains": [
            "your-company-website.com"
          ],
          "phoneNumber": {
            "number": "+10000000000"
          },
          "callDeflectionPhoneNumbers": [
            {
              "number": "+10000000000"
            },
            {
              "number": "+10000000000"
            }
          ]
        },
        "conversationalSettings": {
          "en": {
            "welcomeMessage": {
              "text": "This is a sample welcome message"
            },
            "privacyPolicy": {
              "url": "https://www.your-company-website.com/privacy"
            },
            "conversationStarters": [
              {
                "suggestion": {
                  "reply": {
                    "text": "Option 1",
                    "postbackData": "postback_option_1"
                  }
                }
              }
            ]
          }
        },
        "defaultLocale": "en",
        "primaryAgentInteraction": {
          "interactionType": "HUMAN",
          "humanRepresentative": {
            "humanMessagingAvailability": {
              "hours": [
                {
                  "startTime": {
                    "hours": 8,
                    "minutes": 30
                  },
                  "endTime": {
                    "hours": 20,
                    "minutes": 0
                  },
                  "timeZone": "America/Los_Angeles",
                  "startDay": "MONDAY",
                  "endDay": "SATURDAY"
                }
              ]
            }
          }
        }
      }
    }'
    

    Node.js

    
    /**
     * This code snippet creates a Business Messages agent.
     * Read more: https://developers.google.com/business-communications/business-messages/guides/how-to/agents?method=api#create_the_agent
     *
     * This code is based on the https://github.com/google-business-communications/nodejs-businesscommunications Node.js
     * Business Communications client library.
     */
    
    /**
     * Edit the values below:
     */
    const BRAND_ID = 'EDIT_HERE';
    const PATH_TO_SERVICE_ACCOUNT_KEY = './service_account_key.json';
    
    const businesscommunications = require('businesscommunications');
    const {google} = require('googleapis');
    const uuidv4 = require('uuid').v4;
    
    // Initialize the Business Communications API
    const bcApi = new businesscommunications.businesscommunications_v1.Businesscommunications({});
    
    // Set the scope that we need for the Business Communications API
    const scopes = [
      'https://www.googleapis.com/auth/businesscommunications',
    ];
    
    // Set the private key to the service account file
    const privatekey = require(PATH_TO_SERVICE_ACCOUNT_KEY);
    
    async function main() {
      const authClient = await initCredentials();
      const brandName = 'brands/' + BRAND_ID;
    
      if (authClient) {
        const agentObject = {
          displayName: 'My first agent',
          businessMessagesAgent: {
            customAgentId: uuidv4(), // Optional
            logoUrl: 'https://developers.google.com/identity/images/g-logo.png',
            entryPointConfigs: [
              {
                allowedEntryPoint: 'NON_LOCAL',
              }
            ],
            nonLocalConfig: { // Configuration options for launching on non-local entry points
              // List of phone numbers for call deflection, values must be globally unique
              callDeflectionPhoneNumbers: [
                { number: '+10000000000' },
                { number: '+10000000001' },
              ],
              // Contact information for the agent that displays with the messaging button
              contactOption: {
                options: [
                  'EMAIL',
                  'PHONE'
                ],
                url: 'https://www.your-company-website.com',
              },
              // Domains enabled for messaging within Search, values must be globally unique
              enabledDomains: [ 'your-company-website.com' ],
              // Agent's phone number. Overrides the `phone` field
              // for conversations started from non-local entry points
              phoneNumber: { number: '+10000000000' },
              // List of CLDR region codes for countries where the agent is allowed to launch `NON_LOCAL` entry points
              regionCodes: [ 'US', 'CA' ]
            },
            // Must match a conversational setting locale
            defaultLocale: 'en',
            conversationalSettings: {
              en: {
                privacyPolicy: { url: 'https://www.your-company-website.com/privacy' },
                welcomeMessage: { text: 'This is a sample welcome message' },
                conversationStarters: [
                  {
                    suggestion: {
                      reply: {
                        text: 'Option 1',
                        postbackData: 'postback_option_1',
                      },
                    },
                  },
                ],
              },
            },
            primaryAgentInteraction: {
              interactionType: 'HUMAN',
              humanRepresentative: {
                humanMessagingAvailability: {
                  hours: [
                    {
                      startTime: {
                        hours: 8,
                        minutes: 30
                      },
                      startDay: 'MONDAY',
                      endDay: 'SATURDAY',
                      endTime: {
                        hours: 20,
                        minutes: 0
                      },
                      timeZone: 'America/Los_Angeles',
                    },
                  ],
                },
              },
            },
          },
        };
    
        // Setup the parameters for the API call
        const apiParams = {
          auth: authClient,
          parent: brandName,
          resource: agentObject
        };
    
        bcApi.brands.agents.create(apiParams, {}, (err, response) => {
          if (err !== undefined && err !== null) {
            console.dir(err);
          } else {
            // Agent created
            console.log(response.data);
          }
        });
      }
      else {
        console.log('Authentication failure.');
      }
    }
    
    /**
     * Initializes the Google credentials for calling the
     * Business Messages API.
     */
     async function initCredentials() {
      // Configure a JWT auth client
      const authClient = new google.auth.JWT(
        privatekey.client_email,
        null,
        privatekey.private_key,
        scopes,
      );
    
      return new Promise(function(resolve, reject) {
        // Authenticate request
        authClient.authorize(function(err, tokens) {
          if (err) {
            reject(false);
          } else {
            resolve(authClient);
          }
        });
      });
    }
    
    main();
    

    Джава

    import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
    import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
    import com.google.api.client.http.HttpTransport;
    import com.google.api.client.json.jackson2.JacksonFactory;
    import com.google.api.services.businesscommunications.v1.BusinessCommunications;
    import com.google.api.services.businesscommunications.v1.model.Brand;
    import com.google.common.collect.ImmutableMap;
    import java.io.FileInputStream;
    import java.util.Arrays;
    import java.util.UUID;
    
    class Main {
      /**
       * Initializes credentials used by the Business Communications API.
       */
      private static BusinessCommunications.Builder getBusinessCommunicationsBuilder() {
        BusinessCommunications.Builder builder = null;
        try {
          GoogleCredential credential = GoogleCredential
                .fromStream(new FileInputStream("PATH_TO_SERVICE_ACCOUNT_KEY"));
    
          credential = credential.createScoped(Arrays.asList(
              "https://www.googleapis.com/auth/businesscommunications"));
    
          credential.refreshToken();
    
          HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
          JacksonFactory jsonFactory = JacksonFactory.getDefaultInstance();
    
          // Create instance of the Business Communications API
          builder = new BusinessCommunications
              .Builder(httpTransport, jsonFactory, null)
              .setApplicationName(credential.getServiceAccountProjectId());
    
          // Set the API credentials and endpoint
          builder.setHttpRequestInitializer(credential);
        } catch (Exception e) {
          e.printStackTrace();
        }
    
        return builder;
      }
    
      public static void main(String args[]) {
        try {
          // Create client library reference
          BusinessCommunications.Builder builder = getBusinessCommunicationsBuilder();
    
          String brandName = "BRAND_ID";
    
          BusinessCommunications.Brands.Agents.Create request = builder
              .build().brands().agents().create(brandName,
                  new Agent()
                      .setDisplayName("AGENT_NAME")
                      .setBusinessMessagesAgent(new BusinessMessagesAgent()
                          .setCustomAgentId("CUSTOM_ID") // Optional
                          .setLogoUrl("LOGO_URL")
                          .setEntryPointConfigs(Arrays.asList(
                            new BusinessMessagesEntryPointConfig()
                                .setAllowedEntryPoint(
                                    "ENTRY_POINT_1"),
                            new BusinessMessagesEntryPointConfig()
                                .setAllowedEntryPoint(
                                    "ENTRY_POINT_2")
                          ))
                          // Configuration options for launching on non-local entry points
                          .setNonLocalConfig(new NonLocalConfig()
                            // List of phone numbers for call deflection, values must be globally unique
                            .setCallDeflectionPhoneNumbers(Arrays.asList(new Phone().setNumber("DEFLECTION_PHONE_NUMBER_1"),
                                new Phone().setNumber("DEFLECTION_PHONE_NUMBER_2")))
                            // Contact information for the agent that displays with the messaging button
                            .setContactOption(new ContactOption().setOptions(Arrays.asList(
                                "CONTACT_OPTION_1",
                                "CONTACT_OPTION_2")
                            ).setUrl("WEBSITE_URL"))
                            // Domains enabled for messaging within Search, values must be globally unique
                            .setEnabledDomains(Arrays.asList("ENABLED_DOMAIN_1", "ENABLED_DOMAIN_2"))
                            // Agent's phone number. Overrides the `phone` field for
                            // conversations started from non-local entry points
                            .setPhoneNumber(new Phone().setNumber("CONTACT_PHONE_NUMBER"))
                            // List of regions where this agent will be available
                            .setRegionCodes(Arrays.asList("REGION_CODE")))
                          .setDefaultLocale("LOCALE")
                          // Create a map between the language code and the initial conversation settings
                          .setConversationalSettings(ImmutableMap.of("LOCALE",
                            new ConversationalSetting()
                                .setPrivacyPolicy(new PrivacyPolicy().setUrl("PRIVACY_POLICY_URL"))
                                .setWelcomeMessage(new WelcomeMessage().setText("WELCOME_MESSAGE"))
                                .setConversationStarters(Arrays.asList(
                                    new ConversationStarters().setSuggestion(new Suggestion()
                                        .setReply(new SuggestedReply().setText("SUGGESTION_TEXT").setPostbackData("SUGGESTION_POSTBACK_DATA")))
                                ))))
                          .setPrimaryAgentInteraction(new SupportedAgentInteraction()
                              .setInteractionType(InteractionType.HUMAN.toString())
                              .setHumanRepresentative(new HumanRepresentative()
                                  .setHumanMessagingAvailability(new MessagingAvailability()
                                      // Create a list of available hours
                                      .setHours(Arrays.asList(new Hours()
                                        .setStartTime(new TimeOfDay().setHours(START_TIME_HOURS).setMinutes(START_TIME_MINUTES))
                                        .setStartDay("BEGINNING_DAY_OF_WEEK")
                                        .setEndDay("END_DAY_OF_WEEK")
                                        .setEndTime(new TimeOfDay().setHours(END_TIME_HOURS).setMinutes(END_TIME_MINUTES))
                                        .setTimeZone("TIME_ZONE"))))))
    
                      ));
    
          Agent agent = request.execute();
    
          System.out.println(agent.toPrettyString());
        } catch (Exception e) {
          e.printStackTrace();
        }
      }
    }
    
    Этот код основан на клиентской библиотеке Java Business Communications .

    Питон

    
    """This code creates a Business Messages agent.
    
    Read more: https://developers.google.com/business-communications/business-messages/guides/how-to/agents?method=api#create_the_agent
    
    This code is based on the https://github.com/google-business-communications/python-businessmessages
    Python Business Messages client library.
    """
    
    from oauth2client.service_account import ServiceAccountCredentials
    from businesscommunications.businesscommunications_v1_client import BusinesscommunicationsV1
    from businesscommunications.businesscommunications_v1_messages import (
        Agent, BusinesscommunicationsBrandsAgentsCreateRequest,
        BusinessMessagesAgent, BusinessMessagesEntryPointConfig,
        ContactOption, ConversationalSetting, ConversationStarters,
        Hours, HumanRepresentative, MessagingAvailability,
        NonLocalConfig, Phone, PrivacyPolicy, Suggestion,
        SuggestedReply, SupportedAgentInteraction,
        TimeOfDay, WelcomeMessage
    )
    
    # Edit the values below:
    BRAND_ID = 'EDIT_HERE'
    SCOPES = ['https://www.googleapis.com/auth/businesscommunications']
    SERVICE_ACCOUNT_FILE = './service_account_key.json'
    
    credentials = ServiceAccountCredentials.from_json_keyfile_name(
        SERVICE_ACCOUNT_FILE, scopes=SCOPES)
    
    client = BusinesscommunicationsV1(credentials=credentials)
    
    agents_service = BusinesscommunicationsV1.BrandsAgentsService(client)
    
    brand_name = 'brands/ '+ BRAND_ID
    
    agent = Agent(
        displayName='My first agent',
        businessMessagesAgent=BusinessMessagesAgent(
            customAgentId='CUSTOM_ID', # Optional
            logoUrl='https://developers.google.com/identity/images/g-logo.png',
            entryPointConfigs=[BusinessMessagesEntryPointConfig(
                allowedEntryPoint=BusinessMessagesEntryPointConfig.AllowedEntryPointValueValuesEnum.LOCATION
            ), BusinessMessagesEntryPointConfig(
                allowedEntryPoint=BusinessMessagesEntryPointConfig.AllowedEntryPointValueValuesEnum.NON_LOCAL
            )],
            nonLocalConfig=NonLocalConfig(
                # List of phone numbers for call deflection, values must be globally unique
                # Generating a random phone number for demonstration purposes
                # This should be replaced with a real brand phone number
                callDeflectionPhoneNumbers=[Phone(number='+10000000000'),
                  Phone(number='+10000000001')],
                # Contact information for the agent that displays with the messaging button
                contactOption=ContactOption(
                        options=[ContactOption.OptionsValueListEntryValuesEnum.EMAIL,
                            ContactOption.OptionsValueListEntryValuesEnum.PHONE],
                        url='https://www.your-company-website.com'
                    ),
                # Domains enabled for messaging within Search, values must be globally unique
                # Generating a random URL for demonstration purposes
                # This should be replaced with a real brand URL
                enabledDomains=['your-company-website.com'],
                # Agent's phone number. Overrides the `phone` field for conversations started from non-local entry points
                phoneNumber=Phone(number='+10000000000'),
                # List of CLDR region codes for countries where the agent is allowed to launch `NON_LOCAL` entry points.
                # Example is for launching in Canada and the USA
                regionCodes=['US', 'CA']
            ),
            defaultLocale='en',
            conversationalSettings=BusinessMessagesAgent.ConversationalSettingsValue(
                additionalProperties=[BusinessMessagesAgent.ConversationalSettingsValue.AdditionalProperty(
                    key='en',
                    value=ConversationalSetting(
                        privacyPolicy=PrivacyPolicy(url='https://www.your-company-website.com/privacy'),
                        welcomeMessage=WelcomeMessage(text='This is a sample welcome message'),
                        conversationStarters=[
                            ConversationStarters(
                                suggestion=Suggestion(
                                    reply=SuggestedReply(text='Option 1',
                                                         postbackData='postback_option_1')
                                )
                            )
                        ]
                    )
                )]
            ),
            primaryAgentInteraction=SupportedAgentInteraction(
                interactionType=SupportedAgentInteraction.InteractionTypeValueValuesEnum.HUMAN,
                humanRepresentative=HumanRepresentative(
                    humanMessagingAvailability=MessagingAvailability(hours=[
                            Hours(
                                startTime=TimeOfDay(hours=8, minutes=30),
                                startDay=Hours.StartDayValueValuesEnum.MONDAY,
                                endDay=Hours.EndDayValueValuesEnum.SATURDAY,
                                endTime=TimeOfDay(hours=20, minutes=0),
                                timeZone='America/Los_Angeles'
                            )
                        ])
                )
            ),
        )
    )
    
    new_agent = agents_service.Create(
        BusinesscommunicationsBrandsAgentsCreateRequest(
            agent=agent,
            parent=brand_name
        )
    )
    
    print(new_agent)
    

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

  3. Если у бренда есть местоположения, которые вы хотите связать со своим агентом, см. раздел Добавление местоположений .

Пример. Создайте агента для банка Growing Tree Bank.

curl -X POST "https://businesscommunications.googleapis.com/v1/brands" \
-H "Content-Type: application/json" \
-H "User-Agent: curl/business-communications" \
-H "$(oauth2l header --json /path/to/service/account/key.json businesscommunications)" \
-d "{
    'displayName': 'Growing Tree Bank'
}"

# Fetch returned brand name value of "brands/12345"

curl -X POST "https://businesscommunications.googleapis.com/v1/brands/12345/agents" \
-H "Content-Type: application/json" \
-H "User-Agent: curl/business-communications" \
-H "$(oauth2l header --json /path/to/service/account/key.json businesscommunications)" \
-d "{
    'displayName': 'Growing Tree Bank',
    'businessMessagesAgent': {
        'logoUrl': 'https://www.growingtreebank.com/images/logo.png',
        'entryPointConfigs': [
          {
            'allowedEntryPoint': 'NON_LOCAL',
          },
          {
            'allowedEntryPoint': 'LOCATION',
          },
        ],
        'customAgentId': 'growing-tree-bank',
        'nonLocalConfig': {
            'regionCodes': ['001'],
            'contactOption': {
                'url': 'https://www.growingtreebank.com',
                'options': [
                    'EMAIL',
                    'PHONE',
                ],
            },
            'enabledDomains': [
                'https://www.growingtreebank.com',
            ],
            'phoneNumber': {
                'number': '+12223334444',
            },
            'callDeflectionPhoneNumbers': [
                {
                    'number': '+12223334444',
                },
                {
                    'number': '+56667778888',
                },
            ],
        },
        'conversationalSettings': {
            'en': {
                'welcomeMessage': {
                    'text': 'Thanks for contacting Growing Tree Bank. What can I help with today?',
                },
                'privacyPolicy': {
                    'url': 'https://www.growingtreebank.com/privacy',
                },
                'conversationStarters': [
                    {
                        'suggestion': {
                            'reply': {
                                'text': 'Set up an account',
                                'postbackData': 'new-account',
                            },
                        },
                    },
                ],
            },
        },
        'defaultLocale': 'en',
        'primaryAgentInteraction': {
            'interactionType': 'BOT',
            'botRepresentative': {
                'botMessagingAvailability': {
                    'hours': [
                        {
                            'startTime': {
                                'hours': '8',
                                'minutes': '00',
                            },
                            'endTime': {
                                'hours': '17',
                                'minutes': '30',
                            },
                            'timeZone': 'America/Los_Angeles',
                            'startDay': 'MONDAY',
                            'endDay': 'FRIDAY',
                        },
                    ],
                },
            },
        },
    },
}"

Храните важную информацию

Когда вы создаете агента, API бизнес-коммуникаций возвращает значения вашего агента, включая name и testUrls .

Установите вебхук на уровне агента

Вы получаете сообщения, отправленные вашему агенту, через вебхук. Если вы хотите, чтобы сообщения для определенного агента поступали на другой веб-перехватчик, вы можете установить веб-перехватчик на уровне агента.

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

Тестирование агента

У каждого агента есть тестовые URL-адреса, которые позволяют вам увидеть, как разговор с этим агентом отображается для пользователей, и дают вам возможность проверить вашу инфраструктуру обмена сообщениями.

TestUrl имеет атрибуты url и surface . Для тестирования на устройстве iOS используйте тестовый URL-адрес с поверхностным значением SURFACE_IOS_MAPS . Открытие URL-адреса на устройстве iOS, на котором установлено приложение Google Maps, открывает полнофункциональный диалог с агентом.

У устройств Android есть два тестовых URL-адреса. URL-адреса с surface значением SURFACE_ANDROID_MAPS открывают разговоры в Картах Google и представляют собой точки входа в диалог, которые появляются в Картах Google. URL-адреса с surface значением SURFACE_ANDROID_WEB открывают беседы в наложенном диалоговом представлении и представляют все остальные точки входа.

Как только открывается разговорная поверхность, разговор включает в себя всю информацию о брендингах, которую увидят пользователи, и когда вы отправляете сообщение агенту, ваш WebHook получает сообщение , включая полную полезную нагрузку JSON, которую вы можете ожидать при общении с пользователями.

Чтобы открыть тестовый URL -адрес агента, нажмите на ссылку или используйте запуск агента Business Messages на мобильном устройстве.

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

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

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

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

загрязнение


# This code gets the agent.
# Read more: https://developers.google.com/business-communications/business-messages/reference/business-communications/rest/v1/brands.agents/get

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

curl -X GET \
"https://businesscommunications.googleapis.com/v1/brands/__BRAND_ID__/agents/__AGENT_ID__" \
-H "Content-Type: application/json" \
-H "User-Agent: curl/business-communications" \
-H "$(oauth2l header --json ./service_account_key.json businesscommunications)"

Node.js


/**
 * This code snippet gets an agent.
 * Read more: https://developers.google.com/business-communications/business-messages/reference/business-communications/rest/v1/brands.agents/get
 *
 * This code is based on the https://github.com/google-business-communications/nodejs-businesscommunications Node.js
 * Business Communications client library.
 */

/**
 * Edit the values below:
 */
const BRAND_ID = 'EDIT_HERE';
const AGENT_ID = 'EDIT_HERE';
const PATH_TO_SERVICE_ACCOUNT_KEY = './service_account_key.json';

const businesscommunications = require('businesscommunications');
const {google} = require('googleapis');

// Initialize the Business Communications API
const bcApi = new businesscommunications.businesscommunications_v1.Businesscommunications({});

// Set the scope that we need for the Business Communications API
const scopes = [
  'https://www.googleapis.com/auth/businesscommunications',
];

// Set the private key to the service account file
const privatekey = require(PATH_TO_SERVICE_ACCOUNT_KEY);

async function main() {
  const authClient = await initCredentials();

  const agentName = 'brands/' + BRAND_ID + '/agents/' + AGENT_ID;

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

    bcApi.brands.agents.get(apiParams, {}, (err, response) => {
      if (err !== undefined && err !== null) {
        console.dir(err);
      } else {
        // Agent found
        console.log(response.data);
      }
    });
  }
  else {
    console.log('Authentication failure.');
  }
}

/**
 * Initializes the Google credentials for calling the
 * Business Messages API.
 */
 async function initCredentials() {
  // Configure a JWT auth client
  const authClient = new google.auth.JWT(
    privatekey.client_email,
    null,
    privatekey.private_key,
    scopes,
  );

  return new Promise(function(resolve, reject) {
    // Authenticate request
    authClient.authorize(function(err, tokens) {
      if (err) {
        reject(false);
      } else {
        resolve(authClient);
      }
    });
  });
}

main();

Джава

import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.services.businesscommunications.v1.BusinessCommunications;
import com.google.api.services.businesscommunications.v1.model.Agent;
import java.io.FileInputStream;
import java.util.Arrays;

class Main {
  /**
   * Initializes credentials used by the Business Communications API.
   */
  private static BusinessCommunications.Builder getBusinessCommunicationsBuilder() {
    BusinessCommunications.Builder builder = null;
    try {
      GoogleCredential credential = GoogleCredential
            .fromStream(new FileInputStream("PATH_TO_SERVICE_ACCOUNT_KEY"));

      credential = credential.createScoped(Arrays.asList(
          "https://www.googleapis.com/auth/businesscommunications"));

      credential.refreshToken();

      HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
      JacksonFactory jsonFactory = JacksonFactory.getDefaultInstance();

      // Create instance of the Business Communications API
      builder = new BusinessCommunications
          .Builder(httpTransport, jsonFactory, null)
          .setApplicationName(credential.getServiceAccountProjectId());

      // Set the API credentials and endpoint
      builder.setHttpRequestInitializer(credential);
    } catch (Exception e) {
      e.printStackTrace();
    }

    return builder;
  }

  public static void main(String args[]) {
    try {
      // Create client library reference
      BusinessCommunications.Builder builder = getBusinessCommunicationsBuilder();

      String agentName = "brands/BRAND_ID/agents/AGENT_ID";

      BusinessCommunications.Brands.Agents.Get request = builder
        .build().brands().agents().get(agentName);

      Agent agent = request.execute();

      System.out.println(agent.toPrettyString());
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
}
Этот код основан на клиентской библиотеке Java Business Communications .

Питон


"""This code gets the agent.

Read more: https://developers.google.com/business-communications/business-messages/reference/business-communications/rest/v1/brands.agents/get

This code is based on the https://github.com/google-business-communications/python-businessmessages
Python Business Messages client library.
"""

from oauth2client.service_account import ServiceAccountCredentials
from businesscommunications.businesscommunications_v1_client import BusinesscommunicationsV1
from businesscommunications.businesscommunications_v1_messages import (
    Agent,
    BusinesscommunicationsBrandsAgentsGetRequest,
)

# Edit the values below:
BRAND_ID = 'EDIT_HERE'
AGENT_ID = 'EDIT_HERE'
SCOPES = ['https://www.googleapis.com/auth/businesscommunications']
SERVICE_ACCOUNT_FILE = './service_account_key.json'

credentials = ServiceAccountCredentials.from_json_keyfile_name(
    SERVICE_ACCOUNT_FILE, scopes=SCOPES)

client = BusinesscommunicationsV1(credentials=credentials)

agents_service = BusinesscommunicationsV1.BrandsAgentsService(client)

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

agent = agents_service.Get(BusinesscommunicationsBrandsAgentsGetRequest(
        name=agent_name
    ))

print(agent)

Перечислите все агенты для бренда

Если вы не знаете name агента, вы можете получить информацию для всех агентов, связанных с брендом, опустив значение AGENT_ID из URL -адреса запроса GET.

загрязнение


# This code lists all agents from a brand.
# Read more: https://developers.google.com/business-communications/business-messages/reference/business-communications/rest/v1/brands.agents/list

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

curl -X GET \
"https://businesscommunications.googleapis.com/v1/brands/__BRAND_ID__/agents/" \
-H "Content-Type: application/json" \
-H "User-Agent: curl/business-communications" \
-H "$(oauth2l header --json ./service_account_key.json businesscommunications)"

Node.js


/**
 * This code snippet lists the agents of a brand.
 * Read more: https://developers.google.com/business-communications/business-messages/reference/business-communications/rest/v1/brands.agents/list
 *
 * This code is based on the https://github.com/google-business-communications/nodejs-businesscommunications Node.js
 * Business Communications client library.
 */

/**
 * Edit the values below:
 */
const BRAND_ID = 'EDIT_HERE';
const PATH_TO_SERVICE_ACCOUNT_KEY = './service_account_key.json';

const businesscommunications = require('businesscommunications');
const {google} = require('googleapis');

// Initialize the Business Communications API
const bcApi = new businesscommunications.businesscommunications_v1.Businesscommunications({});

// Set the scope that we need for the Business Communications API
const scopes = [
  'https://www.googleapis.com/auth/businesscommunications',
];

// Set the private key to the service account file
const privatekey = require(PATH_TO_SERVICE_ACCOUNT_KEY);

async function main() {
  const authClient = await initCredentials();

  const brandName = 'brands/' + BRAND_ID;

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

    bcApi.brands.agents.list(apiParams, {}, (err, response) => {
      if (err !== undefined && err !== null) {
        console.dir(err);
      } else {
        // Agent found
        console.log(response.data);
      }
    });
  }
  else {
    console.log('Authentication failure.');
  }
}

/**
 * Initializes the Google credentials for calling the
 * Business Messages API.
 */
 async function initCredentials() {
  // Configure a JWT auth client
  const authClient = new google.auth.JWT(
    privatekey.client_email,
    null,
    privatekey.private_key,
    scopes,
  );

  return new Promise(function(resolve, reject) {
    // Authenticate request
    authClient.authorize(function(err, tokens) {
      if (err) {
        reject(false);
      } else {
        resolve(authClient);
      }
    });
  });
}

main();

Джава

import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.services.businesscommunications.v1.BusinessCommunications;
import com.google.api.services.businesscommunications.v1.model.Agent;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

class Main {
  /**
   * Initializes credentials used by the Business Communications API.
   */
  private static BusinessCommunications.Builder getBusinessCommunicationsBuilder() {
    BusinessCommunications.Builder builder = null;
    try {
      GoogleCredential credential = GoogleCredential
            .fromStream(new FileInputStream("PATH_TO_SERVICE_ACCOUNT_KEY"));

      credential = credential.createScoped(Arrays.asList(
          "https://www.googleapis.com/auth/businesscommunications"));

      credential.refreshToken();

      HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
      JacksonFactory jsonFactory = JacksonFactory.getDefaultInstance();

      // Create instance of the Business Communications API
      builder = new BusinessCommunications
          .Builder(httpTransport, jsonFactory, null)
          .setApplicationName(credential.getServiceAccountProjectId());

      // Set the API credentials and endpoint
      builder.setHttpRequestInitializer(credential);
    } catch (Exception e) {
      e.printStackTrace();
    }

    return builder;
  }

  public static void main(String args[]) {
    try {
      // Create client library reference
      BusinessCommunications.Builder builder = getBusinessCommunicationsBuilder();

      String brandName = "brands/BRAND_ID";

      BusinessCommunications.Brands.Agents.List request = builder
          .build().brands().agents().list(brandName);

      List agents = request.execute().getAgents();
      agents.stream().forEach(agent -> {
        try {
          System.out.println(agent.toPrettyString());
        } catch (IOException e) {
          e.printStackTrace();
        }
      });
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
}
Этот код основан на клиентской библиотеке Java Business Communications .

Питон


"""This code lists all agents from a brand.

Read more: https://developers.google.com/business-communications/business-messages/reference/business-communications/rest/v1/brands.agents/list

This code is based on the https://github.com/google-business-communications/python-businessmessages
Python Business Messages client library.
"""

from oauth2client.service_account import ServiceAccountCredentials
from businesscommunications.businesscommunications_v1_client import BusinesscommunicationsV1
from businesscommunications.businesscommunications_v1_messages import (
    Agent,
    BusinesscommunicationsBrandsAgentsGetRequest,
)

# Edit the values below:
BRAND_ID = 'EDIT_HERE'
SCOPES = ['https://www.googleapis.com/auth/businesscommunications']
SERVICE_ACCOUNT_FILE = './service_account_key.json'

credentials = ServiceAccountCredentials.from_json_keyfile_name(
    SERVICE_ACCOUNT_FILE, scopes=SCOPES)

client = BusinesscommunicationsV1(credentials=credentials)

agents_service = BusinesscommunicationsV1.BrandsAgentsService(client)

brand_name = 'brands/' + BRAND_ID

agents = agents_service.List(BusinesscommunicationsBrandsAgentsListRequest(
        parent=brand_name
    ))

print(agents)

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

Чтобы обновить агента, вы выполняете запрос на патч с API Business Communications. Когда вы делаете вызов API, вы включаете имена полей, которые вы редактируете в качестве значений для параметра URL «UpdateMask».

Например, если вы обновляете поля displayName и customAgentId , параметр URL «UpdateMask» - «UpdateMask = DisplayName, BusinessMessageAgent.customagentid».

Для форматирования и вариантов стоимости см. brands.agents.patch .

Если вы не знаете name агента, см. Список всех агентов для бренда .

После проверки агента вы можете обновить только следующие поля:

  • conversationalSetting

  • customAgentId

  • defaultLocale

  • primaryAgentInteraction

  • additionalAgentInteractions

  • phone

Если вам нужно обновить другие поля после проверки своего агента,Свяжитесь с нами. (Сначала вы должны войти в систему с учетной записью Google Business Messages. Чтобы зарегистрироваться для учетной записи, см. Зарегистрироваться в бизнес-сообщениях .)

Пример: обновление отображаемого имени

загрязнение

curl -X PATCH \
"https://businesscommunications.googleapis.com/v1/brands/BRAND_ID/agents/AGENT_ID?updateMask=displayName" \
-H "Content-Type: application/json" \
-H "User-Agent: curl/business-communications" \
-H "$(oauth2l header --json PATH_TO_SERVICE_ACCOUNT_KEY businesscommunications)" \
-d "{
    'displayName': 'Growing Tree Bank',
}"

Node.js

const businesscommunications = require('businesscommunications');
const {google} = require('googleapis');

// Initialize the Business Communications API
let bcApi = new businesscommunications.businesscommunications_v1.Businesscommunications({});

// Set the scope that we need for the Business Communications API
const scopes = [
  'https://www.googleapis.com/auth/businesscommunications',
];

// Set the private key to the service account file
const privatekey = require('PATH_TO_SERVICE_ACCOUNT_KEY');

/**
 * Initializes the Google credentials for calling the
 * Business Messages API.
 */
async function initCredentials() {
  // Configure a JWT auth client
  let authClient = new google.auth.JWT(
    privatekey.client_email,
    null,
    privatekey.private_key,
    scopes,
  );

  return new Promise(function(resolve, reject) {
    // Authenticate request
    authClient.authorize(function(err, tokens) {
      if (err) {
        reject(false);
      } else {
        resolve(authClient);
      }
    });
  });
}

async function main() {
  let authClient = await initCredentials();

  let agentName = 'brands/BRAND_ID/agents/AGENT_ID';

  if (authClient) {
    // Setup the parameters for the API call
    const apiParams = {
      auth: authClient,
      name: agentName,
      updateMask: 'displayName',
      resource: {
        displayName: 'Growing Tree Bank',
      }
    };

    bcApi.brands.agents.patch(apiParams, {}, (err, response) => {
      if (err !== undefined && err !== null) {
        console.dir(err);
      } else {
        // Agent found
        console.log(response.data);
      }
    });
  }
  else {
    console.log('Authentication failure.');
  }
}

main();
Этот код основан на клиентской библиотеке Node.js Business Communications .

Джава

import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.services.businesscommunications.v1.BusinessCommunications;
import com.google.api.services.businesscommunications.v1.model.Agent;
import java.io.FileInputStream;
import java.util.Arrays;

class Main {
  /**
   * Initializes credentials used by the Business Communications API.
   */
  private static BusinessCommunications.Builder getBusinessCommunicationsBuilder() {
    BusinessCommunications.Builder builder = null;
    try {
      GoogleCredential credential = GoogleCredential
            .fromStream(new FileInputStream("PATH_TO_SERVICE_ACCOUNT_KEY"));

      credential = credential.createScoped(Arrays.asList(
          "https://www.googleapis.com/auth/businesscommunications"));

      credential.refreshToken();

      HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
      JacksonFactory jsonFactory = JacksonFactory.getDefaultInstance();

      // Create instance of the Business Communications API
      builder = new BusinessCommunications
          .Builder(httpTransport, jsonFactory, null)
          .setApplicationName(credential.getServiceAccountProjectId());

      // Set the API credentials and endpoint
      builder.setHttpRequestInitializer(credential);
    } catch (Exception e) {
      e.printStackTrace();
    }

    return builder;
  }

  public static void main(String args[]) {
    try {
      // Create client library reference
      BusinessCommunications.Builder builder = getBusinessCommunicationsBuilder();

      String agentName = "brands/BRAND_ID/agents/AGENT_ID";

      Agent agent = new Agent().setDisplayName("Growing Tree Bank");

      BusinessCommunications.Brands.Agents.Patch request = builder
          .build().brands().agents().patch(agentName, agent);

      request.setUpdateMask("displayName");

      Agent updatedAgent = request.execute();
      System.out.println(updatedAgent.toPrettyString());
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
}
Этот код основан на клиентской библиотеке Java Business Communications .

Питон

from oauth2client.service_account import ServiceAccountCredentials
from businesscommunications.businesscommunications_v1_client import (
    BusinesscommunicationsV1
)
from businesscommunications.businesscommunications_v1_messages import (
    Agent,
    BusinesscommunicationsBrandsAgentsPatchRequest,
)

SCOPES = ['https://www.googleapis.com/auth/businesscommunications']
SERVICE_ACCOUNT_FILE = 'PATH_TO_SERVICE_ACCOUNT_KEY'

credentials = ServiceAccountCredentials.from_json_keyfile_name(
    SERVICE_ACCOUNT_FILE, scopes=SCOPES)

client = BusinesscommunicationsV1(credentials=credentials)

agents_service = BusinesscommunicationsV1.BrandsAgentsService(client)

agent_name = 'brands/BRAND_ID/agents/AGENT_ID'

agent=Agent(
          displayName='Growing Tree Bank'
      )

updated_agent = agents_service.Patch(
        BusinesscommunicationsBrandsAgentsPatchRequest(
            agent=agent,
            name=agent_name,
            updateMask='displayName'
        )
    )

print(updated_agent)
Этот код основан на клиентской библиотеке Python Business Communications .

Пример: укажите группы NON_LOCAL и групп точек входа LOCATION

загрязнение

curl -X PATCH \
"https://businesscommunications.googleapis.com/v1/brands/BRAND_ID/agents/AGENT_ID?updateMask=businessMessagesAgent.entryPointConfigs" \
-H "Content-Type: application/json" \
-H "User-Agent: curl/business-communications" \
-H "$(oauth2l header --json PATH_TO_SERVICE_ACCOUNT_KEY businesscommunications)" \
-d "{
  'businessMessagesAgent': {
    'entryPointConfigs': [
      {
        'allowedEntryPoint': 'NON_LOCAL',
      },
      {
        'allowedEntryPoint': 'LOCATION',
      },
    ],
  },
}"

Node.js

const businesscommunications = require('businesscommunications');
const {google} = require('googleapis');

// Initialize the Business Communications API
let bcApi = new businesscommunications.businesscommunications_v1.Businesscommunications({});

// Set the scope that we need for the Business Communications API
const scopes = [
  'https://www.googleapis.com/auth/businesscommunications',
];

// Set the private key to the service account file
const privatekey = require('PATH_TO_SERVICE_ACCOUNT_KEY');

/**
 * Initializes the Google credentials for calling the
 * Business Messages API.
 */
async function initCredentials() {
  // Configure a JWT auth client
  let authClient = new google.auth.JWT(
    privatekey.client_email,
    null,
    privatekey.private_key,
    scopes,
  );

  return new Promise(function(resolve, reject) {
    // Authenticate request
    authClient.authorize(function(err, tokens) {
      if (err) {
        reject(false);
      } else {
        resolve(authClient);
      }
    });
  });
}

async function main() {
  let authClient = await initCredentials();

  let agentName = 'brands/BRAND_ID/agents/AGENT_ID';

  if (authClient) {
    // Setup the parameters for the API call
    const apiParams = {
      auth: authClient,
      name: agentName,
      updateMask: 'businessMessagesAgent.entryPointConfigs',
      resource: {
        businessMessagesAgent: {
          entryPointConfigs: [
            {
              allowedEntryPoint: 'LOCATION',
            },
            {
              allowedEntryPoint: 'NON_LOCAL',
            },
          ],
        }
      }
    };

    bcApi.brands.agents.patch(apiParams, {}, (err, response) => {
      if (err !== undefined && err !== null) {
        console.dir(err);
      } else {
        // Agent found
        console.log(response.data);
      }
    });
  }
  else {
    console.log('Authentication failure.');
  }
}

main();
Этот код основан на клиентской библиотеке Node.js Business Communications .

Джава

import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.services.businesscommunications.v1.BusinessCommunications;
import com.google.api.services.businesscommunications.v1.model.*;
import java.io.FileInputStream;
import java.util.Arrays;

class Main {
  /**
   * Initializes credentials used by the Business Communications API.
   */
  private static BusinessCommunications.Builder getBusinessCommunicationsBuilder() {
    BusinessCommunications.Builder builder = null;
    try {
      GoogleCredential credential = GoogleCredential
            .fromStream(new FileInputStream("PATH_TO_SERVICE_ACCOUNT_KEY"));

      credential = credential.createScoped(Arrays.asList(
          "https://www.googleapis.com/auth/businesscommunications"));

      credential.refreshToken();

      HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
      JacksonFactory jsonFactory = JacksonFactory.getDefaultInstance();

      // Create instance of the Business Communications API
      builder = new BusinessCommunications
          .Builder(httpTransport, jsonFactory, null)
          .setApplicationName(credential.getServiceAccountProjectId());

      // Set the API credentials and endpoint
      builder.setHttpRequestInitializer(credential);
    } catch (Exception e) {
      e.printStackTrace();
    }

    return builder;
  }

  public static void main(String args[]) {
    try {
      // Create client library reference
      BusinessCommunications.Builder builder = getBusinessCommunicationsBuilder();

      String agentName = "brands/BRAND_ID/agents/AGENT_ID";

      Agent agent = new Agent().setBusinessMessagesAgent(
          new BusinessMessagesAgent().setEntryPointConfigs(Arrays.asList(
              new BusinessMessagesEntryPointConfig()
                  .setAllowedEntryPoint(
                      "NON_LOCAL"),
              new BusinessMessagesEntryPointConfig()
                  .setAllowedEntryPoint(
                      "LOCATION"))));

      BusinessCommunications.Brands.Agents.Patch request = builder
          .build().brands().agents().patch(agentName, agent);

      request.setUpdateMask("businessMessagesAgent.entryPointConfigs");

      Agent updatedAgent = request.execute();
      System.out.println(updatedAgent.toPrettyString());
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
}
Этот код основан на клиентской библиотеке Java Business Communications .

Питон

from oauth2client.service_account import ServiceAccountCredentials
from businesscommunications.businesscommunications_v1_client import (
    BusinesscommunicationsV1
)
from businesscommunications.businesscommunications_v1_messages import (
    Agent,
    BusinessMessagesAgent,
    BusinessMessagesEntryPointConfig,
    BusinesscommunicationsBrandsAgentsPatchRequest,
)

SCOPES = ['https://www.googleapis.com/auth/businesscommunications']
SERVICE_ACCOUNT_FILE = 'PATH_TO_SERVICE_ACCOUNT_KEY'

credentials = ServiceAccountCredentials.from_json_keyfile_name(
    SERVICE_ACCOUNT_FILE, scopes=SCOPES)

client = BusinesscommunicationsV1(credentials=credentials)

agents_service = BusinesscommunicationsV1.BrandsAgentsService(client)

agent_name = 'brands/BRAND_ID/agents/AGENT_ID'

agent=Agent(
    businessMessagesAgent=BusinessMessagesAgent(
        entryPointConfigs=[BusinessMessagesEntryPointConfig(
            allowedEntryPoint=BusinessMessagesEntryPointConfig.AllowedEntryPointValueValuesEnum.NON_LOCAL
        ), BusinessMessagesEntryPointConfig(
            allowedEntryPoint=BusinessMessagesEntryPointConfig.AllowedEntryPointValueValuesEnum.LOCATION
        )]
    )
)

updated_agent = agents_service.Patch(
        BusinesscommunicationsBrandsAgentsPatchRequest(
            agent=agent,
            name=agent_name,
            updateMask='businessMessagesAgent.entryPointConfigs'
        )
    )

print(updated_agent)
Этот код основан на клиентской библиотеке Python Business Communications .

Пример: обновить приветственное сообщение

Если вы обновляете какое-либо поле в рамках conversationalSettings -такого как welcomeMessage -вы должны обновить все поля в объекте, и вы должны указать локали настроек (как двуххарактерный код ISO 639-1 ).

загрязнение

curl -X PATCH \
"https://businesscommunications.googleapis.com/v1/brands/BRAND_ID/agents/AGENT_ID?updateMask=businessMessagesAgent.conversationalSettings.en" \
-H "Content-Type: application/json" \
-H "User-Agent: curl/business-communications" \
-H "$(oauth2l header --json PATH_TO_SERVICE_ACCOUNT_KEY businesscommunications)" \
-d "{
    'businessMessagesAgent': {
        'conversationalSettings': {
            'en': {
                'welcomeMessage': {
                    'text': 'Thanks for contacting Growing Tree Bank. What can I help with today?',
                },
                'offlineMessage': {
                    'text': 'We\'re closed for the night. Please reach out to us again tomorrow.',
                },
                'privacyPolicy': {
                    'url': 'https://www.growingtreebank.com/privacy',
                },
                'conversationStarters': [
                    {
                        'suggestion': {
                            'reply': {
                                'text': 'Set up an account',
                                'postbackData': 'new-account',
                            },
                        },
                    },
                    {
                        'suggestion': {
                            'reply': {
                                'text': 'Look up account information',
                                'postbackData': 'account-lookup',
                            },
                        },
                    },
                ],
            },
        },
    },
}"

Node.js

const businesscommunications = require('businesscommunications');
const {google} = require('googleapis');

// Initialize the Business Communications API
let bcApi = new businesscommunications.businesscommunications_v1.Businesscommunications({});

// Set the scope that we need for the Business Communications API
const scopes = [
  'https://www.googleapis.com/auth/businesscommunications',
];

// Set the private key to the service account file
const privatekey = require('PATH_TO_SERVICE_ACCOUNT_KEY');

/**
 * Initializes the Google credentials for calling the
 * Business Messages API.
 */
async function initCredentials() {
  // Configure a JWT auth client
  let authClient = new google.auth.JWT(
    privatekey.client_email,
    null,
    privatekey.private_key,
    scopes,
  );

  return new Promise(function(resolve, reject) {
    // Authenticate request
    authClient.authorize(function(err, tokens) {
      if (err) {
        reject(false);
      } else {
        resolve(authClient);
      }
    });
  });
}

async function main() {
  let authClient = await initCredentials();

  let agentName = 'brands/BRAND_ID/agents/AGENT_ID';

  if (authClient) {
    // Setup the parameters for the API call
    const apiParams = {
      auth: authClient,
      name: agentName,
      updateMask: 'businessMessagesAgent.conversationalSettings.en',
      resource: {
        businessMessagesAgent: {
          conversationalSettings: {
            en: {
              privacyPolicy: { url: 'https://www.growingtreebank.com/privacy' },
              welcomeMessage: { text: 'Thanks for contacting Growing Tree Bank. What can I help with today?' },
              offlineMessage: { text: 'We\'re closed for the night. Please reach out to us again tomorrow.' },
              conversationStarters: [
                {
                  suggestion: {
                    reply: {
                      text: 'Set up an account',
                      postbackData: 'new-account',
                    },
                  },
                },
                {
                  suggestion: {
                    reply: {
                      text: 'Look up account information',
                      postbackData: 'account-lookup',
                    },
                  },
                },
              ],
            },
          }
        }
      }
    };

    bcApi.brands.agents.patch(apiParams, {}, (err, response) => {
      if (err !== undefined && err !== null) {
        console.dir(err);
      } else {
        // Agent found
        console.log(response.data);
      }
    });
  }
  else {
    console.log('Authentication failure.');
  }
}

main();
Этот код основан на клиентской библиотеке Node.js Business Communications .

Джава

import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.services.businesscommunications.v1.BusinessCommunications;
import com.google.api.services.businesscommunications.v1.model.*;
import com.google.common.collect.ImmutableMap;
import java.io.FileInputStream;
import java.util.Arrays;

class Main {
  /**
   * Initializes credentials used by the Business Communications API.
   */
  private static BusinessCommunications.Builder getBusinessCommunicationsBuilder() {
    BusinessCommunications.Builder builder = null;
    try {
      GoogleCredential credential = GoogleCredential
            .fromStream(new FileInputStream("PATH_TO_SERVICE_ACCOUNT_KEY"));

      credential = credential.createScoped(Arrays.asList(
          "https://www.googleapis.com/auth/businesscommunications"));

      credential.refreshToken();

      HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
      JacksonFactory jsonFactory = JacksonFactory.getDefaultInstance();

      // Create instance of the Business Communications API
      builder = new BusinessCommunications
          .Builder(httpTransport, jsonFactory, null)
          .setApplicationName(credential.getServiceAccountProjectId());

      // Set the API credentials and endpoint
      builder.setHttpRequestInitializer(credential);
    } catch (Exception e) {
      e.printStackTrace();
    }

    return builder;
  }

  public static void main(String args[]) {
    try {
      // Create client library reference
      BusinessCommunications.Builder builder = getBusinessCommunicationsBuilder();

      String agentName = "brands/BRAND_ID/agents/AGENT_ID";

      Agent agent = new Agent().setBusinessMessagesAgent(
          new BusinessMessagesAgent().setConversationalSettings(ImmutableMap.of("en",
              new ConversationalSetting()
                  .setPrivacyPolicy(new PrivacyPolicy().setUrl("https://www.growingtreebank.com/privacy"))
                  .setWelcomeMessage(new WelcomeMessage().setText("Thanks for contacting Growing Tree Bank. What can I help with today?"))
                  .setOfflineMessage(new OfflineMessage().setText("We're closed for the night. Please reach out to us again tomorrow."))
                  .setConversationStarters(Arrays.asList(
                      new ConversationStarters().setSuggestion(new Suggestion()
                          .setReply(new SuggestedReply()
                              .setText("Set up an account")
                              .setPostbackData("new-account"))),
                      new ConversationStarters().setSuggestion(new Suggestion()
                          .setReply(new SuggestedReply()
                              .setText("Look up account information")
                              .setPostbackData("account-lookup")))
                      )))));

      BusinessCommunications.Brands.Agents.Patch request = builder
          .build().brands().agents().patch(agentName, agent);

      request.setUpdateMask("businessMessagesAgent.conversationalSettings.en");

      Agent updatedAgent = request.execute();
      System.out.println(updatedAgent.toPrettyString());
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
}
Этот код основан на клиентской библиотеке Java Business Communications .

Питон

from oauth2client.service_account import ServiceAccountCredentials
from businesscommunications.businesscommunications_v1_client import (
    BusinesscommunicationsV1
)
from businesscommunications.businesscommunications_v1_messages import (
    Agent,
    BusinessMessagesAgent,
    ConversationStarters,
    ConversationalSetting,
    OfflineMessage,
    PrivacyPolicy,
    WelcomeMessage,
    BusinesscommunicationsBrandsAgentsPatchRequest,
)

SCOPES = ['https://www.googleapis.com/auth/businesscommunications']
SERVICE_ACCOUNT_FILE = 'PATH_TO_SERVICE_ACCOUNT_KEY'

credentials = ServiceAccountCredentials.from_json_keyfile_name(
    SERVICE_ACCOUNT_FILE, scopes=SCOPES)

client = BusinesscommunicationsV1(credentials=credentials)

agents_service = BusinesscommunicationsV1.BrandsAgentsService(client)

agent_name = 'brands/BRAND_ID/agents/AGENT_ID'

agent=Agent(
		businessMessagesAgent=BusinessMessagesAgent(
		  	conversationalSettings=BusinessMessagesAgent.ConversationalSettingsValue(
		        additionalProperties=[BusinessMessagesAgent.ConversationalSettingsValue.AdditionalProperty(
		            key='en',
		            value=ConversationalSetting(
		                privacyPolicy=PrivacyPolicy(url='https://www.growingtreebank.com/privacy'),
		                welcomeMessage=WelcomeMessage(text='Thanks for contacting Growing Tree Bank. What can I help with today?'),
		                offlineMessage=OfflineMessage(text='We\'re closed for the night. Please reach out to us again tomorrow.'),
		                conversationStarters=[
		                    ConversationStarters(
		                        suggestion=Suggestion(
		                            reply=SuggestedReply(text='Set up an account',
		                                postbackData='new-account')
		                        )
		                    ),
		                    ConversationStarters(
		                        suggestion=Suggestion(
		                            reply=SuggestedReply(text='Look up account information',
		                                postbackData='account-lookup')
		                        )
		                    )]
		                )
		            )
		        ]
		    )
		)
)

updated_agent = agents_service.Patch(
        BusinesscommunicationsBrandsAgentsPatchRequest(
            agent=agent,
            name=agent_name,
            updateMask='businessMessagesAgent.conversationalSettings.en'
        )
    )

print(updated_agent)
Этот код основан на клиентской библиотеке Python Business Communications .

Удалить агента

Когда вы удаляете агента, бизнес -сообщения удаляют все данные агента. Бизнес -сообщения не удаляют сообщения, отправляемые вашим агентом, которые находятся в пути или хранятся на устройстве пользователя. Сообщения пользователям не являются данными агента.

Удалить запросы не удастся, если у агента есть связанное местоположение или если вы пытались проверить агента один или несколько раз. Чтобы обновить местоположения, см. Добавить местоположения .

Вы не можете удалить агента, который проверяется. Чтобы удалить агента, который вы проверили или пытались проверить,Свяжитесь с нами. (Вы должны сначала войти в систему с учетной записью Business Messages Google. Чтобы зарегистрироваться для учетной записи, см. Зарегистрироваться в бизнес-сообщениях .)

Чтобы удалить агент, запустите следующую команду. Замените BRAND_ID и AGENT_ID на уникальные значения от name агента.

загрязнение


# This code deletes an agent.
# Read more: https://developers.google.com/business-communications/business-messages/reference/business-communications/rest/v1/brands.agents/delete

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

curl -X DELETE "https://businesscommunications.googleapis.com/v1/brands/__BRAND_ID__/agents/__AGENT_ID__" \
-H "Content-Type: application/json" \
-H "User-Agent: curl/business-communications" \
-H "$(oauth2l header --json ./service_account_key.json businesscommunications)"

Node.js


/**
 * This code snippet deletes an agent.
 * Read more: https://developers.google.com/business-communications/business-messages/reference/business-communications/rest/v1/brands.agents/delete
 *
 * This code is based on the https://github.com/google-business-communications/nodejs-businesscommunications Node.js
 * Business Communications client library.
 */

/**
 * Edit the values below:
 */
const BRAND_ID = 'EDIT_HERE';
const AGENT_ID = 'EDIT_HERE';
const PATH_TO_SERVICE_ACCOUNT_KEY = './service_account_key.json';

const businesscommunications = require('businesscommunications');
const {google} = require('googleapis');

// Initialize the Business Communications API
const bcApi = new businesscommunications.businesscommunications_v1.Businesscommunications({});

// Set the scope that we need for the Business Communications API
const scopes = [
  'https://www.googleapis.com/auth/businesscommunications',
];

// Set the private key to the service account file
const privatekey = require(PATH_TO_SERVICE_ACCOUNT_KEY);

async function main() {
  const authClient = await initCredentials();

  const agentName = 'brands/' + BRAND_ID + '/agents/' + AGENT_ID;

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

    bcApi.brands.agents.delete(apiParams, {}, (err, response) => {
      if (err !== undefined && err !== null) {
        console.dir(err);
      } else {
        // Agent removed
        console.log(response.data);
      }
    });
  }
  else {
    console.log('Authentication failure.');
  }
}

/**
 * Initializes the Google credentials for calling the
 * Business Messages API.
 */
 async function initCredentials() {
  // Configure a JWT auth client
  const authClient = new google.auth.JWT(
    privatekey.client_email,
    null,
    privatekey.private_key,
    scopes,
  );

  return new Promise(function(resolve, reject) {
    // Authenticate request
    authClient.authorize(function(err, tokens) {
      if (err) {
        reject(false);
      } else {
        resolve(authClient);
      }
    });
  });
}

main();

Джава

import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.services.businesscommunications.v1.BusinessCommunications;
import com.google.api.services.businesscommunications.v1.model.*;
import java.io.FileInputStream;
import java.util.Arrays;

class Main {
  /**
   * Initializes credentials used by the Business Communications API.
   */
  private static BusinessCommunications.Builder getBusinessCommunicationsBuilder() {
    BusinessCommunications.Builder builder = null;
    try {
      GoogleCredential credential = GoogleCredential
            .fromStream(new FileInputStream("PATH_TO_SERVICE_ACCOUNT_KEY"));

      credential = credential.createScoped(Arrays.asList(
          "https://www.googleapis.com/auth/businesscommunications"));

      credential.refreshToken();

      HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
      JacksonFactory jsonFactory = JacksonFactory.getDefaultInstance();

      // Create instance of the Business Communications API
      builder = new BusinessCommunications
          .Builder(httpTransport, jsonFactory, null)
          .setApplicationName(credential.getServiceAccountProjectId());

      // Set the API credentials and endpoint
      builder.setHttpRequestInitializer(credential);
    } catch (Exception e) {
      e.printStackTrace();
    }

    return builder;
  }

  public static void main(String args[]) {
    try {
      // Create client library reference
      BusinessCommunications.Builder builder = getBusinessCommunicationsBuilder();

      String agentName = "brands/BRAND_ID/agents/AGENT_ID";

      BusinessCommunications.Brands.Agents.Delete request
         = builder.build().brands().agents().delete(agentName);

      System.out.println(request.execute());
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
}
Этот код основан на клиентской библиотеке Java Business Communications .

Питон


"""This code deletes an agent.

Read more: https://developers.google.com/business-communications/business-messages/reference/business-communications/rest/v1/brands.agents/delete

This code is based on the https://github.com/google-business-communications/python-businessmessages
Python Business Messages client library.
"""

from oauth2client.service_account import ServiceAccountCredentials
from businesscommunications.businesscommunications_v1_client import BusinesscommunicationsV1
from businesscommunications.businesscommunications_v1_messages import (
    Agent,
    BusinesscommunicationsBrandsAgentsDeleteRequest,
)

# Edit the values below:
BRAND_ID = 'EDIT_HERE'
AGENT_ID = 'EDIT_HERE'
SCOPES = ['https://www.googleapis.com/auth/businesscommunications']
SERVICE_ACCOUNT_FILE = './service_account_key.json'

credentials = ServiceAccountCredentials.from_json_keyfile_name(
    SERVICE_ACCOUNT_FILE, scopes=SCOPES)

client = BusinesscommunicationsV1(credentials=credentials)

agents_service = BusinesscommunicationsV1.BrandsAgentsService(client)

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

agent = agents_service.Delete(BusinesscommunicationsBrandsAgentsDeleteRequest(
        name=agent_name
    ))

print(agent)

Для форматирования и вариантов стоимости см. brands.agents.delete .

Удалить бренд

Когда вы удаляете бренд, вы выполняете запрос Delete с API Business Communications. Удалить запросы терпят неудачу, если у вас есть один или несколько агентов или мест, связанных с брендом, даже если эти агенты принадлежат к другому продукту.

Чтобы удалить бренд, запустите следующую команду. Замените BRAND_ID на уникальное значение от name бренда.

загрязнение


# This code deletes a brand.
# Read more: https://developers.google.com/business-communications/business-messages/reference/business-communications/rest/v1/brands/delete

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

curl -X DELETE "https://businesscommunications.googleapis.com/v1/brands/__BRAND_ID__" \
-H "Content-Type: application/json" \
-H "User-Agent: curl/business-communications" \
-H "$(oauth2l header --json ./service_account_key.json businesscommunications)"

Node.js


/**
 * This code snippet deletes a brand.
 * Read more: https://developers.google.com/business-communications/business-messages/reference/business-communications/rest/v1/brands/delete
 *
 * This code is based on the https://github.com/google-business-communications/nodejs-businesscommunications Node.js
 * Business Communications client library.
 */

/**
 * Edit the values below:
 */
const BRAND_ID = 'EDIT_HERE';
const PATH_TO_SERVICE_ACCOUNT_KEY = './service_account_key.json';

const businesscommunications = require('businesscommunications');
const {google} = require('googleapis');

// Initialize the Business Communications API
const bcApi = new businesscommunications.businesscommunications_v1.Businesscommunications({});

// Set the scope that we need for the Business Communications API
const scopes = [
  'https://www.googleapis.com/auth/businesscommunications',
];

// Set the private key to the service account file
const privatekey = require(PATH_TO_SERVICE_ACCOUNT_KEY);

async function main() {
  const authClient = await initCredentials();

  const brandName = 'brands/' + BRAND_ID;

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

    bcApi.brands.delete(apiParams, {}, (err, response) => {
      if (err !== undefined && err !== null) {
        console.dir(err);
      } else {
        // Brand removed
        console.log(response.data);
      }
    });
  }
  else {
    console.log('Authentication failure.');
  }
}

/**
 * Initializes the Google credentials for calling the
 * Business Messages API.
 */
 async function initCredentials() {
  // Configure a JWT auth client
  const authClient = new google.auth.JWT(
    privatekey.client_email,
    null,
    privatekey.private_key,
    scopes,
  );

  return new Promise(function(resolve, reject) {
    // Authenticate request
    authClient.authorize(function(err, tokens) {
      if (err) {
        reject(false);
      } else {
        resolve(authClient);
      }
    });
  });
}

main();

Джава

import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.services.businesscommunications.v1.BusinessCommunications;
import com.google.api.services.businesscommunications.v1.model.*;
import java.io.FileInputStream;
import java.util.Arrays;

class Main {
  /**
   * Initializes credentials used by the Business Communications API.
   */
  private static BusinessCommunications.Builder getBusinessCommunicationsBuilder() {
    BusinessCommunications.Builder builder = null;
    try {
      GoogleCredential credential = GoogleCredential
            .fromStream(new FileInputStream("PATH_TO_SERVICE_ACCOUNT_KEY"));

      credential = credential.createScoped(Arrays.asList(
          "https://www.googleapis.com/auth/businesscommunications"));

      credential.refreshToken();

      HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
      JacksonFactory jsonFactory = JacksonFactory.getDefaultInstance();

      // Create instance of the Business Communications API
      builder = new BusinessCommunications
          .Builder(httpTransport, jsonFactory, null)
          .setApplicationName(credential.getServiceAccountProjectId());

      // Set the API credentials and endpoint
      builder.setHttpRequestInitializer(credential);
    } catch (Exception e) {
      e.printStackTrace();
    }

    return builder;
  }

  public static void main(String args[]) {
    try {
      // Create client library reference
      BusinessCommunications.Builder builder = getBusinessCommunicationsBuilder();

      String brandName = "brands/BRAND_ID";

      BusinessCommunications.Brands.Delete request = builder.build().brands().delete(brandName);

      System.out.println(request.execute());
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
}
Этот код основан на клиентской библиотеке Java Business Communications .

Питон


"""This code deletes a brand.

Read more: https://developers.google.com/business-communications/business-messages/reference/business-communications/rest/v1/brands/delete

This code is based on the https://github.com/google-business-communications/python-businessmessages
Python Business Messages client library.
"""

from oauth2client.service_account import ServiceAccountCredentials
from businesscommunications.businesscommunications_v1_client import BusinesscommunicationsV1
from businesscommunications.businesscommunications_v1_messages import (
    BusinesscommunicationsBrandsAgentsDeleteRequest
)

# Edit the values below:
BRAND_ID = 'EDIT_HERE'
SCOPES = ['https://www.googleapis.com/auth/businesscommunications']
SERVICE_ACCOUNT_FILE = './service_account_key.json'

credentials = ServiceAccountCredentials.from_json_keyfile_name(
    SERVICE_ACCOUNT_FILE, scopes=SCOPES)

client = BusinesscommunicationsV1(credentials=credentials)

agents_service = BusinesscommunicationsV1.BrandsAgentsService(client)

brand_name = 'brands/' + BRAND_ID

agent = agents_service.Delete(BusinesscommunicationsBrandsAgentsDeleteRequest(
        name=brand_name
    ))

print(agent)

Для форматирования и вариантов стоимости см. brands.delete .

Следующие шаги

Теперь, когда у вас есть агент, вы можете предпринять следующие шаги:

,

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

Агент - это разговорная сущность, с которой взаимодействуют пользователи. Вы создаете одного агента для каждого бренда, которым вы управляете. Вы создаете и управляете агентами с API Business Communications и контролируете обмен сообщениями для своих агентов с помощью API бизнес -сообщений.

Агент охватывает бизнес -функции бренда, такие как онлайн -поддержка и физические местоположения (если есть). Каждое сообщение содержит контекст, из которого пользователь инициировал разговор. Ваша инфраструктура маршрутизации сообщений может обнаружить, если пользователь просмотрел конкретное местоположение бизнеса или искал общую поддержку, и она может направлять сообщения в правильный пункт назначения.

Отношения агента/бренда

Например, если вы управляете растущим брендом Bank Tree Bank, который имеет веб -сайт и два места, вы создаете одного агента «растущего банка дерева». Пользователи могут встретиться с агентом с помощью обычных поисков на основе общего или местоположения, и контекста, в котором пользователь обнаружил, что агент передается вместе с каждым сообщением в ваш WebHook. Вы используете этот контекст, чтобы направить сообщение либо сотрудникам в месте, либо в команду поддержки веб -сайта, которые создают ответ и продолжают разговор с пользователем.

Ожидания

Прежде чем создать агента, поймите ожидания агентов в бизнес -сообщениях.

  • Агенты должны следовать руководству по дизайну, изложенному в дизайне разговоров для бизнес -сообщений .
  • У агентов должны быть представители человека, чтобы ответить на вопросы, когда автоматизация не может выполнить запрос или по запросу пользователей.

  • Агенты должны поддерживать рейтинг удовлетворенности клиентов (CSAT) не менее 80%, а частота ответа на торговлю (MRR) - по меньшей мере 95%, как указано в показателях .

Создать агент

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

Если вы управляете несколькими брендами, повторите шаги, чтобы создать агента для каждого бренда.

Предварительные условия

Прежде чем создавать агентов для брендов, которыми вы управляете, вам нужно собрать некоторую информацию:

Среда разработки

Информация о вашей среде разработки.

Детали бренда

Информация о бренде, которую представляет агент.

  • Имя бренда
  • Бренд -сайт
  • Параметры контакта на веб -сайте (как определено в OPTION )
  • Номер телефона с потребителем
  • Номера телефонов включены для отклонения вызова

Внешний вид агента и политика

Информация о том, как агент появляется пользователям и как он работает.

  • Имя агента, как вы хотите, чтобы оно отображалось в разговорах с пользователями
  • Политика конфиденциальности, как общедоступный URL, начиная с "https: //"
  • (Рекомендуется) Логотип агента (1024x1024 px), как общедоступный URL

    В разговоре логотипы отображаются как круги диаметром 1024 PX. Убедитесь, что ваш логотип хорошо отображается как круг.

  • (Необязательно) Идентификатор пользовательского агента, который идентифицирует бренд в сообщениях, которые получает WebHook

Взаимодействие агента

Информация о том, как ваш агент взаимодействует с пользователями.

  • Локаль, в котором обычно работает ваш агент, указанный двумя символом языкового кода ISO 639-1

  • Приветственное сообщение агента

    Что агент говорит, чтобы приветствовать пользователей?

  • Агент для разговора

    Список предложений в форме чипов разговора (как определено в предложении ), чтобы пользователь мог взаимодействовать с агентом

    • Текст отображается пользователю в чипе
    • Данные о отправке, строка, отправленная обратно в ваш веб -крюк в полезной нагрузке сообщения, если пользователь нажимает на чип
  • Автоматизированное время чата

    • Ежедневное время начала, как объект TimeOfDay

      Например, 8:15 утра

      {
        "hours": 8,
        "minutes": 15,
      }
      
    • Ежедневное время окончания, как объект TimeOfDay

      Например, 19:30

      {
        "hours": 19,
        "minutes": 30,
      }
      
    • Начальный день, первый день недели, который агент доступен для чата (как определено в DayOfWeek )

    • Конец, в последний день недели, который агент доступен для чата (как определено в DayOfWeek )

    • Часовой пояс.

Точки входа агента

Информация о том, где пользователи могут начать беседы с агентом.

  • Разрешенные точки входа агента, когда пользователи могут начать разговоры с агентами ( NON_LOCAL и/или LOCATION )

Информация о NON_LOCAL точках входа (не применяется к точке входа в Google Ads ).

  • Разрешены регионы (как коды региона CLDR ), чтобы ограничить региональный доступ к NON_LOCAL точкам входа.

    Независимо от региона, агент может иметь только один номер телефона, связанный с ним. Если вам нужен другой номер телефона на основе региона, для каждого региона должен быть создан другой агент.

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

Установить и проверить OAuth2l

Все запросы скручивания в документации этого сайта используют OAuth2L для аутентификации. Если вы хотите использовать командную строку для подключения к API -интерфейсам бизнес -сообщений и бизнес -сообщений, установите OAuth2L.

Чтобы установить OAuth2l с Python 3,

  1. Скачать OAuth2l .

  2. Измените каталог на "./oauth2l/python".

  3. Установите OAuth2L со следующей командой.

    sudo python setup.sh build && sudo python setup.py install
    
  4. Проверьте, что OAuth2L может генерировать токен авторизации.

    oauth2l header --json resources/bm-agent-service-account-credentials.json businesscommunications
    
  5. Убедитесь, что выход создает токен авторизации формы:

    Authorization: Bearer AUTHORIZATION_BEARER_TOKEN
    

Есть и другие способы установить OAuth2L для различных операционных систем. Независимо от вашего метода установки, убедитесь, что вы можете генерировать токен авторизации на основе учетной записи услуги JSON, прежде чем продолжить.

Создать агент

После того, как вы собрали свою информацию, пришло время создать своего агента.

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

    В терминале запустите следующую команду:

    загрязнение

    
    # This code creates a brand.
    # Read more: https://developers.google.com/business-communications/business-messages/reference/business-communications/rest/v1/brands/create
    
    # Make sure a service account key file exists at ./service_account_key.json
    
    curl -X POST "https://businesscommunications.googleapis.com/v1/brands" \
    -H "Content-Type: application/json" \
    -H "User-Agent: curl/business-communications" \
    -H "$(oauth2l header --json ./service_account_key.json businesscommunications)" \
    -d '{
      "displayName": "My first brand curl"
    }'
    

    Node.js

    
    /**
     * This code snippet creates a brand.
     * Read more: https://developers.google.com/business-communications/business-messages/reference/business-communications/rest/v1/brands/create
     *
     * This code is based on the https://github.com/google-business-communications/nodejs-businesscommunications Node.js
     * Business Communications client library.
     */
    
    /**
     * Edit the values below:
     */
    const PATH_TO_SERVICE_ACCOUNT_KEY = './service_account_key.json';
    
    const businesscommunications = require('businesscommunications');
    const {google} = require('googleapis');
    
    // Initialize the Business Communications API
    const bcApi = new businesscommunications.businesscommunications_v1.Businesscommunications({});
    
    // Set the scope that we need for the Business Communications API
    const scopes = [
      'https://www.googleapis.com/auth/businesscommunications',
    ];
    
    // Set the private key to the service account file
    const privatekey = require(PATH_TO_SERVICE_ACCOUNT_KEY);
    
    async function main() {
      const authClient = await initCredentials();
    
      if (authClient) {
        // Setup the parameters for the API call
        const apiParams = {
          auth: authClient,
          resource: {
            displayName: 'My first brand',
          },
        };
    
        bcApi.brands.create(apiParams, {}, (err, response) => {
          if (err !== undefined && err !== null) {
            console.dir(err);
          } else {
            // Brand created
            console.log(response.data);
          }
        });
      }
      else {
        console.log('Authentication failure.');
      }
    }
    
    /**
     * Initializes the Google credentials for calling the
     * Business Communcations API.
     */
     async function initCredentials() {
      // configure a JWT auth client
      const authClient = new google.auth.JWT(
        privatekey.client_email,
        null,
        privatekey.private_key,
        scopes,
      );
    
      return new Promise(function(resolve, reject) {
        // authenticate request
        authClient.authorize(function(err, tokens) {
          if (err) {
            reject('Failed to connect');
          } else {
            resolve(authClient);
          }
        });
      })
    }
    
    main();
    

    Джава

    import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
    import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
    import com.google.api.client.http.HttpTransport;
    import com.google.api.client.json.jackson2.JacksonFactory;
    import com.google.api.services.businesscommunications.v1.BusinessCommunications;
    import com.google.api.services.businesscommunications.v1.model.Brand;
    import java.io.FileInputStream;
    import java.util.Arrays;
    import java.util.UUID;
    
    class Main {
      /**
       * Initializes credentials used by the Business Communications API.
       */
      private static BusinessCommunications.Builder getBusinessCommunicationsBuilder() {
        BusinessCommunications.Builder builder = null;
        try {
          GoogleCredential credential = GoogleCredential
                .fromStream(new FileInputStream("PATH_TO_SERVICE_ACCOUNT_KEY"));
    
          credential = credential.createScoped(Arrays.asList(
              "https://www.googleapis.com/auth/businesscommunications"));
    
          credential.refreshToken();
    
          HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
          JacksonFactory jsonFactory = JacksonFactory.getDefaultInstance();
    
          // Create instance of the Business Communications API
          builder = new BusinessCommunications
              .Builder(httpTransport, jsonFactory, null)
              .setApplicationName(credential.getServiceAccountProjectId());
    
          // Set the API credentials and endpoint
          builder.setHttpRequestInitializer(credential);
        } catch (Exception e) {
          e.printStackTrace();
        }
    
        return builder;
      }
    
      public static void main(String args[]) {
        try {
          // Create client library reference
          BusinessCommunications.Builder builder = getBusinessCommunicationsBuilder();
    
          // Create a request to create a new brand
          BusinessCommunications.Brands.Create request = builder
              .build().brands().create(new Brand().setDisplayName("BRAND_NAME"));
    
          Brand brand = request.execute();
    
          // Print newly created brand object
          System.out.println(brand.toPrettyString());
        } catch (Exception e) {
          e.printStackTrace();
        }
      }
    }
    
    Этот код основан на клиентской библиотеке Java Business Communications .

    Питон

    
    """This code creates a brand.
    
    Read more: https://developers.google.com/business-communications/business-messages/reference/business-communications/rest/v1/brands/create
    
    This code is based on the https://github.com/google-business-communications/python-businessmessages
    Python Business Messages client library.
    """
    
    from oauth2client.service_account import ServiceAccountCredentials
    from businesscommunications.businesscommunications_v1_client import BusinesscommunicationsV1
    from businesscommunications.businesscommunications_v1_messages import (
        Brand)
    
    # Edit the values below:
    SCOPES = ['https://www.googleapis.com/auth/businesscommunications']
    SERVICE_ACCOUNT_FILE = './service_account_key.json'
    
    credentials = ServiceAccountCredentials.from_json_keyfile_name(
        SERVICE_ACCOUNT_FILE, scopes=SCOPES)
    
    client = BusinesscommunicationsV1(credentials=credentials)
    
    brands_service = BusinesscommunicationsV1.BrandsService(client)
    
    brand = brands_service.Create(Brand(displayName='My first brand'))
    
    print(brand)
    

    Храните значение name , которое возвращает API. Вам понадобится обновления или создания агентов.

    Чтобы обновить или искать бренды, см. brands .

  2. Создать агент. Замените BRAND_ID на роль name бренда, которая следует за «бренды/». Например, если name «бренды/12345», идентификатор бренда - «12345».

    В терминале запустите следующую команду:

    загрязнение

    
    # This code creates a Business Messages agent.
    # Read more: https://developers.google.com/business-communications/business-messages/guides/how-to/agents?method=api#create_the_agent
    
    # Replace the __BRAND_ID__ with a brand id that you can create agents for
    # Make sure a service account key file exists at ./service_account_key.json
    
    curl -X POST "https://businesscommunications.googleapis.com/v1/brands/__BRAND_ID__/agents" \
    -H "Content-Type: application/json" \
    -H "User-Agent: curl/business-communications" \
    -H "$(oauth2l header --json ./service_account_key.json businesscommunications)" \
    -d '{
      "displayName": "My first agent",
      "businessMessagesAgent": {
        "logoUrl": "https://developers.google.com/identity/images/g-logo.png",
        "entryPointConfigs": [
          {
            "allowedEntryPoint": "NON_LOCAL"
          }
        ],
        "customAgentId": "'$(uuidgen)'",
        "nonLocalConfig": {
          "regionCodes": [
            "US",
            "CA"
          ],
          "contactOption": {
            "url": "https://www.your-company-website.com",
            "options": [
              "EMAIL",
              "PHONE"
            ]
          },
          "enabledDomains": [
            "your-company-website.com"
          ],
          "phoneNumber": {
            "number": "+10000000000"
          },
          "callDeflectionPhoneNumbers": [
            {
              "number": "+10000000000"
            },
            {
              "number": "+10000000000"
            }
          ]
        },
        "conversationalSettings": {
          "en": {
            "welcomeMessage": {
              "text": "This is a sample welcome message"
            },
            "privacyPolicy": {
              "url": "https://www.your-company-website.com/privacy"
            },
            "conversationStarters": [
              {
                "suggestion": {
                  "reply": {
                    "text": "Option 1",
                    "postbackData": "postback_option_1"
                  }
                }
              }
            ]
          }
        },
        "defaultLocale": "en",
        "primaryAgentInteraction": {
          "interactionType": "HUMAN",
          "humanRepresentative": {
            "humanMessagingAvailability": {
              "hours": [
                {
                  "startTime": {
                    "hours": 8,
                    "minutes": 30
                  },
                  "endTime": {
                    "hours": 20,
                    "minutes": 0
                  },
                  "timeZone": "America/Los_Angeles",
                  "startDay": "MONDAY",
                  "endDay": "SATURDAY"
                }
              ]
            }
          }
        }
      }
    }'
    

    Node.js

    
    /**
     * This code snippet creates a Business Messages agent.
     * Read more: https://developers.google.com/business-communications/business-messages/guides/how-to/agents?method=api#create_the_agent
     *
     * This code is based on the https://github.com/google-business-communications/nodejs-businesscommunications Node.js
     * Business Communications client library.
     */
    
    /**
     * Edit the values below:
     */
    const BRAND_ID = 'EDIT_HERE';
    const PATH_TO_SERVICE_ACCOUNT_KEY = './service_account_key.json';
    
    const businesscommunications = require('businesscommunications');
    const {google} = require('googleapis');
    const uuidv4 = require('uuid').v4;
    
    // Initialize the Business Communications API
    const bcApi = new businesscommunications.businesscommunications_v1.Businesscommunications({});
    
    // Set the scope that we need for the Business Communications API
    const scopes = [
      'https://www.googleapis.com/auth/businesscommunications',
    ];
    
    // Set the private key to the service account file
    const privatekey = require(PATH_TO_SERVICE_ACCOUNT_KEY);
    
    async function main() {
      const authClient = await initCredentials();
      const brandName = 'brands/' + BRAND_ID;
    
      if (authClient) {
        const agentObject = {
          displayName: 'My first agent',
          businessMessagesAgent: {
            customAgentId: uuidv4(), // Optional
            logoUrl: 'https://developers.google.com/identity/images/g-logo.png',
            entryPointConfigs: [
              {
                allowedEntryPoint: 'NON_LOCAL',
              }
            ],
            nonLocalConfig: { // Configuration options for launching on non-local entry points
              // List of phone numbers for call deflection, values must be globally unique
              callDeflectionPhoneNumbers: [
                { number: '+10000000000' },
                { number: '+10000000001' },
              ],
              // Contact information for the agent that displays with the messaging button
              contactOption: {
                options: [
                  'EMAIL',
                  'PHONE'
                ],
                url: 'https://www.your-company-website.com',
              },
              // Domains enabled for messaging within Search, values must be globally unique
              enabledDomains: [ 'your-company-website.com' ],
              // Agent's phone number. Overrides the `phone` field
              // for conversations started from non-local entry points
              phoneNumber: { number: '+10000000000' },
              // List of CLDR region codes for countries where the agent is allowed to launch `NON_LOCAL` entry points
              regionCodes: [ 'US', 'CA' ]
            },
            // Must match a conversational setting locale
            defaultLocale: 'en',
            conversationalSettings: {
              en: {
                privacyPolicy: { url: 'https://www.your-company-website.com/privacy' },
                welcomeMessage: { text: 'This is a sample welcome message' },
                conversationStarters: [
                  {
                    suggestion: {
                      reply: {
                        text: 'Option 1',
                        postbackData: 'postback_option_1',
                      },
                    },
                  },
                ],
              },
            },
            primaryAgentInteraction: {
              interactionType: 'HUMAN',
              humanRepresentative: {
                humanMessagingAvailability: {
                  hours: [
                    {
                      startTime: {
                        hours: 8,
                        minutes: 30
                      },
                      startDay: 'MONDAY',
                      endDay: 'SATURDAY',
                      endTime: {
                        hours: 20,
                        minutes: 0
                      },
                      timeZone: 'America/Los_Angeles',
                    },
                  ],
                },
              },
            },
          },
        };
    
        // Setup the parameters for the API call
        const apiParams = {
          auth: authClient,
          parent: brandName,
          resource: agentObject
        };
    
        bcApi.brands.agents.create(apiParams, {}, (err, response) => {
          if (err !== undefined && err !== null) {
            console.dir(err);
          } else {
            // Agent created
            console.log(response.data);
          }
        });
      }
      else {
        console.log('Authentication failure.');
      }
    }
    
    /**
     * Initializes the Google credentials for calling the
     * Business Messages API.
     */
     async function initCredentials() {
      // Configure a JWT auth client
      const authClient = new google.auth.JWT(
        privatekey.client_email,
        null,
        privatekey.private_key,
        scopes,
      );
    
      return new Promise(function(resolve, reject) {
        // Authenticate request
        authClient.authorize(function(err, tokens) {
          if (err) {
            reject(false);
          } else {
            resolve(authClient);
          }
        });
      });
    }
    
    main();
    

    Джава

    import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
    import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
    import com.google.api.client.http.HttpTransport;
    import com.google.api.client.json.jackson2.JacksonFactory;
    import com.google.api.services.businesscommunications.v1.BusinessCommunications;
    import com.google.api.services.businesscommunications.v1.model.Brand;
    import com.google.common.collect.ImmutableMap;
    import java.io.FileInputStream;
    import java.util.Arrays;
    import java.util.UUID;
    
    class Main {
      /**
       * Initializes credentials used by the Business Communications API.
       */
      private static BusinessCommunications.Builder getBusinessCommunicationsBuilder() {
        BusinessCommunications.Builder builder = null;
        try {
          GoogleCredential credential = GoogleCredential
                .fromStream(new FileInputStream("PATH_TO_SERVICE_ACCOUNT_KEY"));
    
          credential = credential.createScoped(Arrays.asList(
              "https://www.googleapis.com/auth/businesscommunications"));
    
          credential.refreshToken();
    
          HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
          JacksonFactory jsonFactory = JacksonFactory.getDefaultInstance();
    
          // Create instance of the Business Communications API
          builder = new BusinessCommunications
              .Builder(httpTransport, jsonFactory, null)
              .setApplicationName(credential.getServiceAccountProjectId());
    
          // Set the API credentials and endpoint
          builder.setHttpRequestInitializer(credential);
        } catch (Exception e) {
          e.printStackTrace();
        }
    
        return builder;
      }
    
      public static void main(String args[]) {
        try {
          // Create client library reference
          BusinessCommunications.Builder builder = getBusinessCommunicationsBuilder();
    
          String brandName = "BRAND_ID";
    
          BusinessCommunications.Brands.Agents.Create request = builder
              .build().brands().agents().create(brandName,
                  new Agent()
                      .setDisplayName("AGENT_NAME")
                      .setBusinessMessagesAgent(new BusinessMessagesAgent()
                          .setCustomAgentId("CUSTOM_ID") // Optional
                          .setLogoUrl("LOGO_URL")
                          .setEntryPointConfigs(Arrays.asList(
                            new BusinessMessagesEntryPointConfig()
                                .setAllowedEntryPoint(
                                    "ENTRY_POINT_1"),
                            new BusinessMessagesEntryPointConfig()
                                .setAllowedEntryPoint(
                                    "ENTRY_POINT_2")
                          ))
                          // Configuration options for launching on non-local entry points
                          .setNonLocalConfig(new NonLocalConfig()
                            // List of phone numbers for call deflection, values must be globally unique
                            .setCallDeflectionPhoneNumbers(Arrays.asList(new Phone().setNumber("DEFLECTION_PHONE_NUMBER_1"),
                                new Phone().setNumber("DEFLECTION_PHONE_NUMBER_2")))
                            // Contact information for the agent that displays with the messaging button
                            .setContactOption(new ContactOption().setOptions(Arrays.asList(
                                "CONTACT_OPTION_1",
                                "CONTACT_OPTION_2")
                            ).setUrl("WEBSITE_URL"))
                            // Domains enabled for messaging within Search, values must be globally unique
                            .setEnabledDomains(Arrays.asList("ENABLED_DOMAIN_1", "ENABLED_DOMAIN_2"))
                            // Agent's phone number. Overrides the `phone` field for
                            // conversations started from non-local entry points
                            .setPhoneNumber(new Phone().setNumber("CONTACT_PHONE_NUMBER"))
                            // List of regions where this agent will be available
                            .setRegionCodes(Arrays.asList("REGION_CODE")))
                          .setDefaultLocale("LOCALE")
                          // Create a map between the language code and the initial conversation settings
                          .setConversationalSettings(ImmutableMap.of("LOCALE",
                            new ConversationalSetting()
                                .setPrivacyPolicy(new PrivacyPolicy().setUrl("PRIVACY_POLICY_URL"))
                                .setWelcomeMessage(new WelcomeMessage().setText("WELCOME_MESSAGE"))
                                .setConversationStarters(Arrays.asList(
                                    new ConversationStarters().setSuggestion(new Suggestion()
                                        .setReply(new SuggestedReply().setText("SUGGESTION_TEXT").setPostbackData("SUGGESTION_POSTBACK_DATA")))
                                ))))
                          .setPrimaryAgentInteraction(new SupportedAgentInteraction()
                              .setInteractionType(InteractionType.HUMAN.toString())
                              .setHumanRepresentative(new HumanRepresentative()
                                  .setHumanMessagingAvailability(new MessagingAvailability()
                                      // Create a list of available hours
                                      .setHours(Arrays.asList(new Hours()
                                        .setStartTime(new TimeOfDay().setHours(START_TIME_HOURS).setMinutes(START_TIME_MINUTES))
                                        .setStartDay("BEGINNING_DAY_OF_WEEK")
                                        .setEndDay("END_DAY_OF_WEEK")
                                        .setEndTime(new TimeOfDay().setHours(END_TIME_HOURS).setMinutes(END_TIME_MINUTES))
                                        .setTimeZone("TIME_ZONE"))))))
    
                      ));
    
          Agent agent = request.execute();
    
          System.out.println(agent.toPrettyString());
        } catch (Exception e) {
          e.printStackTrace();
        }
      }
    }
    
    Этот код основан на клиентской библиотеке Java Business Communications .

    Питон

    
    """This code creates a Business Messages agent.
    
    Read more: https://developers.google.com/business-communications/business-messages/guides/how-to/agents?method=api#create_the_agent
    
    This code is based on the https://github.com/google-business-communications/python-businessmessages
    Python Business Messages client library.
    """
    
    from oauth2client.service_account import ServiceAccountCredentials
    from businesscommunications.businesscommunications_v1_client import BusinesscommunicationsV1
    from businesscommunications.businesscommunications_v1_messages import (
        Agent, BusinesscommunicationsBrandsAgentsCreateRequest,
        BusinessMessagesAgent, BusinessMessagesEntryPointConfig,
        ContactOption, ConversationalSetting, ConversationStarters,
        Hours, HumanRepresentative, MessagingAvailability,
        NonLocalConfig, Phone, PrivacyPolicy, Suggestion,
        SuggestedReply, SupportedAgentInteraction,
        TimeOfDay, WelcomeMessage
    )
    
    # Edit the values below:
    BRAND_ID = 'EDIT_HERE'
    SCOPES = ['https://www.googleapis.com/auth/businesscommunications']
    SERVICE_ACCOUNT_FILE = './service_account_key.json'
    
    credentials = ServiceAccountCredentials.from_json_keyfile_name(
        SERVICE_ACCOUNT_FILE, scopes=SCOPES)
    
    client = BusinesscommunicationsV1(credentials=credentials)
    
    agents_service = BusinesscommunicationsV1.BrandsAgentsService(client)
    
    brand_name = 'brands/ '+ BRAND_ID
    
    agent = Agent(
        displayName='My first agent',
        businessMessagesAgent=BusinessMessagesAgent(
            customAgentId='CUSTOM_ID', # Optional
            logoUrl='https://developers.google.com/identity/images/g-logo.png',
            entryPointConfigs=[BusinessMessagesEntryPointConfig(
                allowedEntryPoint=BusinessMessagesEntryPointConfig.AllowedEntryPointValueValuesEnum.LOCATION
            ), BusinessMessagesEntryPointConfig(
                allowedEntryPoint=BusinessMessagesEntryPointConfig.AllowedEntryPointValueValuesEnum.NON_LOCAL
            )],
            nonLocalConfig=NonLocalConfig(
                # List of phone numbers for call deflection, values must be globally unique
                # Generating a random phone number for demonstration purposes
                # This should be replaced with a real brand phone number
                callDeflectionPhoneNumbers=[Phone(number='+10000000000'),
                  Phone(number='+10000000001')],
                # Contact information for the agent that displays with the messaging button
                contactOption=ContactOption(
                        options=[ContactOption.OptionsValueListEntryValuesEnum.EMAIL,
                            ContactOption.OptionsValueListEntryValuesEnum.PHONE],
                        url='https://www.your-company-website.com'
                    ),
                # Domains enabled for messaging within Search, values must be globally unique
                # Generating a random URL for demonstration purposes
                # This should be replaced with a real brand URL
                enabledDomains=['your-company-website.com'],
                # Agent's phone number. Overrides the `phone` field for conversations started from non-local entry points
                phoneNumber=Phone(number='+10000000000'),
                # List of CLDR region codes for countries where the agent is allowed to launch `NON_LOCAL` entry points.
                # Example is for launching in Canada and the USA
                regionCodes=['US', 'CA']
            ),
            defaultLocale='en',
            conversationalSettings=BusinessMessagesAgent.ConversationalSettingsValue(
                additionalProperties=[BusinessMessagesAgent.ConversationalSettingsValue.AdditionalProperty(
                    key='en',
                    value=ConversationalSetting(
                        privacyPolicy=PrivacyPolicy(url='https://www.your-company-website.com/privacy'),
                        welcomeMessage=WelcomeMessage(text='This is a sample welcome message'),
                        conversationStarters=[
                            ConversationStarters(
                                suggestion=Suggestion(
                                    reply=SuggestedReply(text='Option 1',
                                                         postbackData='postback_option_1')
                                )
                            )
                        ]
                    )
                )]
            ),
            primaryAgentInteraction=SupportedAgentInteraction(
                interactionType=SupportedAgentInteraction.InteractionTypeValueValuesEnum.HUMAN,
                humanRepresentative=HumanRepresentative(
                    humanMessagingAvailability=MessagingAvailability(hours=[
                            Hours(
                                startTime=TimeOfDay(hours=8, minutes=30),
                                startDay=Hours.StartDayValueValuesEnum.MONDAY,
                                endDay=Hours.EndDayValueValuesEnum.SATURDAY,
                                endTime=TimeOfDay(hours=20, minutes=0),
                                timeZone='America/Los_Angeles'
                            )
                        ])
                )
            ),
        )
    )
    
    new_agent = agents_service.Create(
        BusinesscommunicationsBrandsAgentsCreateRequest(
            agent=agent,
            parent=brand_name
        )
    )
    
    print(new_agent)
    

    Для форматирования и вариантов стоимости см. brands.agents .

  3. Если у бренда есть места, которые вы хотите связать со своим агентом, см. Добавить места .

Пример: создайте агента для растущего банка деревьев

curl -X POST "https://businesscommunications.googleapis.com/v1/brands" \
-H "Content-Type: application/json" \
-H "User-Agent: curl/business-communications" \
-H "$(oauth2l header --json /path/to/service/account/key.json businesscommunications)" \
-d "{
    'displayName': 'Growing Tree Bank'
}"

# Fetch returned brand name value of "brands/12345"

curl -X POST "https://businesscommunications.googleapis.com/v1/brands/12345/agents" \
-H "Content-Type: application/json" \
-H "User-Agent: curl/business-communications" \
-H "$(oauth2l header --json /path/to/service/account/key.json businesscommunications)" \
-d "{
    'displayName': 'Growing Tree Bank',
    'businessMessagesAgent': {
        'logoUrl': 'https://www.growingtreebank.com/images/logo.png',
        'entryPointConfigs': [
          {
            'allowedEntryPoint': 'NON_LOCAL',
          },
          {
            'allowedEntryPoint': 'LOCATION',
          },
        ],
        'customAgentId': 'growing-tree-bank',
        'nonLocalConfig': {
            'regionCodes': ['001'],
            'contactOption': {
                'url': 'https://www.growingtreebank.com',
                'options': [
                    'EMAIL',
                    'PHONE',
                ],
            },
            'enabledDomains': [
                'https://www.growingtreebank.com',
            ],
            'phoneNumber': {
                'number': '+12223334444',
            },
            'callDeflectionPhoneNumbers': [
                {
                    'number': '+12223334444',
                },
                {
                    'number': '+56667778888',
                },
            ],
        },
        'conversationalSettings': {
            'en': {
                'welcomeMessage': {
                    'text': 'Thanks for contacting Growing Tree Bank. What can I help with today?',
                },
                'privacyPolicy': {
                    'url': 'https://www.growingtreebank.com/privacy',
                },
                'conversationStarters': [
                    {
                        'suggestion': {
                            'reply': {
                                'text': 'Set up an account',
                                'postbackData': 'new-account',
                            },
                        },
                    },
                ],
            },
        },
        'defaultLocale': 'en',
        'primaryAgentInteraction': {
            'interactionType': 'BOT',
            'botRepresentative': {
                'botMessagingAvailability': {
                    'hours': [
                        {
                            'startTime': {
                                'hours': '8',
                                'minutes': '00',
                            },
                            'endTime': {
                                'hours': '17',
                                'minutes': '30',
                            },
                            'timeZone': 'America/Los_Angeles',
                            'startDay': 'MONDAY',
                            'endDay': 'FRIDAY',
                        },
                    ],
                },
            },
        },
    },
}"

Хранить важную информацию

Когда вы создаете агента, API Business Communications возвращает значения вашего агента, включая name и testUrls .

Установите веб-крюк на уровне агента

Вы получаете сообщения, отправленные вашему агенту в вашем веб -крючке. Если вы хотите, чтобы сообщения для конкретного агента попали в другой веб-крюк, вы можете установить веб-крюк на уровне агента.

Чтобы установить веб-крючок на уровне агента, используйте консоль разработчика .

Проверьте агент

У каждого агента есть тестовые URL -адреса, которые позволяют вам увидеть, как разговор с этим агентом кажется пользователям, и дает вам возможность проверить вашу инфраструктуру обмена сообщениями.

Testurl имеет url и surface атрибуты. Чтобы проверить с помощью устройства iOS, используйте тестовый URL с значением поверхности SURFACE_IOS_MAPS . Открытие URL -адреса на устройстве iOS, в котором установлено приложение Google Maps, открывает полностью функциональный разговор с агентом.

Устройства Android имеют два тестовых URL. URL -адреса с значением surface SURFACE_ANDROID_MAPS открывают разговоры на картах Google и представляют собой точки входа в разговор, которые появляются в картах Google. URL -адреса со значением surface SURFACE_ANDROID_WEB открытые разговоры в разговорном представлении наложений и представляют все другие точки входа.

Как только открывается разговорная поверхность, разговор включает в себя всю информацию о брендингах, которую увидят пользователи, и когда вы отправляете сообщение агенту, ваш WebHook получает сообщение , включая полную полезную нагрузку JSON, которую вы можете ожидать при общении с пользователями.

Чтобы открыть тестовый URL -адрес агента, нажмите на ссылку или используйте запуск агента Business Messages на мобильном устройстве.

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

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

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

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

загрязнение


# This code gets the agent.
# Read more: https://developers.google.com/business-communications/business-messages/reference/business-communications/rest/v1/brands.agents/get

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

curl -X GET \
"https://businesscommunications.googleapis.com/v1/brands/__BRAND_ID__/agents/__AGENT_ID__" \
-H "Content-Type: application/json" \
-H "User-Agent: curl/business-communications" \
-H "$(oauth2l header --json ./service_account_key.json businesscommunications)"

Node.js


/**
 * This code snippet gets an agent.
 * Read more: https://developers.google.com/business-communications/business-messages/reference/business-communications/rest/v1/brands.agents/get
 *
 * This code is based on the https://github.com/google-business-communications/nodejs-businesscommunications Node.js
 * Business Communications client library.
 */

/**
 * Edit the values below:
 */
const BRAND_ID = 'EDIT_HERE';
const AGENT_ID = 'EDIT_HERE';
const PATH_TO_SERVICE_ACCOUNT_KEY = './service_account_key.json';

const businesscommunications = require('businesscommunications');
const {google} = require('googleapis');

// Initialize the Business Communications API
const bcApi = new businesscommunications.businesscommunications_v1.Businesscommunications({});

// Set the scope that we need for the Business Communications API
const scopes = [
  'https://www.googleapis.com/auth/businesscommunications',
];

// Set the private key to the service account file
const privatekey = require(PATH_TO_SERVICE_ACCOUNT_KEY);

async function main() {
  const authClient = await initCredentials();

  const agentName = 'brands/' + BRAND_ID + '/agents/' + AGENT_ID;

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

    bcApi.brands.agents.get(apiParams, {}, (err, response) => {
      if (err !== undefined && err !== null) {
        console.dir(err);
      } else {
        // Agent found
        console.log(response.data);
      }
    });
  }
  else {
    console.log('Authentication failure.');
  }
}

/**
 * Initializes the Google credentials for calling the
 * Business Messages API.
 */
 async function initCredentials() {
  // Configure a JWT auth client
  const authClient = new google.auth.JWT(
    privatekey.client_email,
    null,
    privatekey.private_key,
    scopes,
  );

  return new Promise(function(resolve, reject) {
    // Authenticate request
    authClient.authorize(function(err, tokens) {
      if (err) {
        reject(false);
      } else {
        resolve(authClient);
      }
    });
  });
}

main();

Джава

import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.services.businesscommunications.v1.BusinessCommunications;
import com.google.api.services.businesscommunications.v1.model.Agent;
import java.io.FileInputStream;
import java.util.Arrays;

class Main {
  /**
   * Initializes credentials used by the Business Communications API.
   */
  private static BusinessCommunications.Builder getBusinessCommunicationsBuilder() {
    BusinessCommunications.Builder builder = null;
    try {
      GoogleCredential credential = GoogleCredential
            .fromStream(new FileInputStream("PATH_TO_SERVICE_ACCOUNT_KEY"));

      credential = credential.createScoped(Arrays.asList(
          "https://www.googleapis.com/auth/businesscommunications"));

      credential.refreshToken();

      HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
      JacksonFactory jsonFactory = JacksonFactory.getDefaultInstance();

      // Create instance of the Business Communications API
      builder = new BusinessCommunications
          .Builder(httpTransport, jsonFactory, null)
          .setApplicationName(credential.getServiceAccountProjectId());

      // Set the API credentials and endpoint
      builder.setHttpRequestInitializer(credential);
    } catch (Exception e) {
      e.printStackTrace();
    }

    return builder;
  }

  public static void main(String args[]) {
    try {
      // Create client library reference
      BusinessCommunications.Builder builder = getBusinessCommunicationsBuilder();

      String agentName = "brands/BRAND_ID/agents/AGENT_ID";

      BusinessCommunications.Brands.Agents.Get request = builder
        .build().brands().agents().get(agentName);

      Agent agent = request.execute();

      System.out.println(agent.toPrettyString());
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
}
Этот код основан на клиентской библиотеке Java Business Communications .

Питон


"""This code gets the agent.

Read more: https://developers.google.com/business-communications/business-messages/reference/business-communications/rest/v1/brands.agents/get

This code is based on the https://github.com/google-business-communications/python-businessmessages
Python Business Messages client library.
"""

from oauth2client.service_account import ServiceAccountCredentials
from businesscommunications.businesscommunications_v1_client import BusinesscommunicationsV1
from businesscommunications.businesscommunications_v1_messages import (
    Agent,
    BusinesscommunicationsBrandsAgentsGetRequest,
)

# Edit the values below:
BRAND_ID = 'EDIT_HERE'
AGENT_ID = 'EDIT_HERE'
SCOPES = ['https://www.googleapis.com/auth/businesscommunications']
SERVICE_ACCOUNT_FILE = './service_account_key.json'

credentials = ServiceAccountCredentials.from_json_keyfile_name(
    SERVICE_ACCOUNT_FILE, scopes=SCOPES)

client = BusinesscommunicationsV1(credentials=credentials)

agents_service = BusinesscommunicationsV1.BrandsAgentsService(client)

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

agent = agents_service.Get(BusinesscommunicationsBrandsAgentsGetRequest(
        name=agent_name
    ))

print(agent)

Перечислите все агенты для бренда

Если вы не знаете name агента, вы можете получить информацию для всех агентов, связанных с брендом, опустив значение AGENT_ID из URL -адреса запроса GET.

загрязнение


# This code lists all agents from a brand.
# Read more: https://developers.google.com/business-communications/business-messages/reference/business-communications/rest/v1/brands.agents/list

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

curl -X GET \
"https://businesscommunications.googleapis.com/v1/brands/__BRAND_ID__/agents/" \
-H "Content-Type: application/json" \
-H "User-Agent: curl/business-communications" \
-H "$(oauth2l header --json ./service_account_key.json businesscommunications)"

Node.js


/**
 * This code snippet lists the agents of a brand.
 * Read more: https://developers.google.com/business-communications/business-messages/reference/business-communications/rest/v1/brands.agents/list
 *
 * This code is based on the https://github.com/google-business-communications/nodejs-businesscommunications Node.js
 * Business Communications client library.
 */

/**
 * Edit the values below:
 */
const BRAND_ID = 'EDIT_HERE';
const PATH_TO_SERVICE_ACCOUNT_KEY = './service_account_key.json';

const businesscommunications = require('businesscommunications');
const {google} = require('googleapis');

// Initialize the Business Communications API
const bcApi = new businesscommunications.businesscommunications_v1.Businesscommunications({});

// Set the scope that we need for the Business Communications API
const scopes = [
  'https://www.googleapis.com/auth/businesscommunications',
];

// Set the private key to the service account file
const privatekey = require(PATH_TO_SERVICE_ACCOUNT_KEY);

async function main() {
  const authClient = await initCredentials();

  const brandName = 'brands/' + BRAND_ID;

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

    bcApi.brands.agents.list(apiParams, {}, (err, response) => {
      if (err !== undefined && err !== null) {
        console.dir(err);
      } else {
        // Agent found
        console.log(response.data);
      }
    });
  }
  else {
    console.log('Authentication failure.');
  }
}

/**
 * Initializes the Google credentials for calling the
 * Business Messages API.
 */
 async function initCredentials() {
  // Configure a JWT auth client
  const authClient = new google.auth.JWT(
    privatekey.client_email,
    null,
    privatekey.private_key,
    scopes,
  );

  return new Promise(function(resolve, reject) {
    // Authenticate request
    authClient.authorize(function(err, tokens) {
      if (err) {
        reject(false);
      } else {
        resolve(authClient);
      }
    });
  });
}

main();

Джава

import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.services.businesscommunications.v1.BusinessCommunications;
import com.google.api.services.businesscommunications.v1.model.Agent;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

class Main {
  /**
   * Initializes credentials used by the Business Communications API.
   */
  private static BusinessCommunications.Builder getBusinessCommunicationsBuilder() {
    BusinessCommunications.Builder builder = null;
    try {
      GoogleCredential credential = GoogleCredential
            .fromStream(new FileInputStream("PATH_TO_SERVICE_ACCOUNT_KEY"));

      credential = credential.createScoped(Arrays.asList(
          "https://www.googleapis.com/auth/businesscommunications"));

      credential.refreshToken();

      HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
      JacksonFactory jsonFactory = JacksonFactory.getDefaultInstance();

      // Create instance of the Business Communications API
      builder = new BusinessCommunications
          .Builder(httpTransport, jsonFactory, null)
          .setApplicationName(credential.getServiceAccountProjectId());

      // Set the API credentials and endpoint
      builder.setHttpRequestInitializer(credential);
    } catch (Exception e) {
      e.printStackTrace();
    }

    return builder;
  }

  public static void main(String args[]) {
    try {
      // Create client library reference
      BusinessCommunications.Builder builder = getBusinessCommunicationsBuilder();

      String brandName = "brands/BRAND_ID";

      BusinessCommunications.Brands.Agents.List request = builder
          .build().brands().agents().list(brandName);

      List agents = request.execute().getAgents();
      agents.stream().forEach(agent -> {
        try {
          System.out.println(agent.toPrettyString());
        } catch (IOException e) {
          e.printStackTrace();
        }
      });
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
}
Этот код основан на клиентской библиотеке Java Business Communications .

Питон


"""This code lists all agents from a brand.

Read more: https://developers.google.com/business-communications/business-messages/reference/business-communications/rest/v1/brands.agents/list

This code is based on the https://github.com/google-business-communications/python-businessmessages
Python Business Messages client library.
"""

from oauth2client.service_account import ServiceAccountCredentials
from businesscommunications.businesscommunications_v1_client import BusinesscommunicationsV1
from businesscommunications.businesscommunications_v1_messages import (
    Agent,
    BusinesscommunicationsBrandsAgentsGetRequest,
)

# Edit the values below:
BRAND_ID = 'EDIT_HERE'
SCOPES = ['https://www.googleapis.com/auth/businesscommunications']
SERVICE_ACCOUNT_FILE = './service_account_key.json'

credentials = ServiceAccountCredentials.from_json_keyfile_name(
    SERVICE_ACCOUNT_FILE, scopes=SCOPES)

client = BusinesscommunicationsV1(credentials=credentials)

agents_service = BusinesscommunicationsV1.BrandsAgentsService(client)

brand_name = 'brands/' + BRAND_ID

agents = agents_service.List(BusinesscommunicationsBrandsAgentsListRequest(
        parent=brand_name
    ))

print(agents)

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

Чтобы обновить агента, вы выполняете запрос на патч с API Business Communications. Когда вы делаете вызов API, вы включаете имена полей, которые вы редактируете в качестве значений для параметра URL «UpdateMask».

Например, если вы обновляете поля displayName и customAgentId , параметр URL «UpdateMask» - «UpdateMask = DisplayName, BusinessMessageAgent.customagentid».

Для форматирования и вариантов стоимости см. brands.agents.patch .

Если вы не знаете name агента, см. Список всех агентов для бренда .

После проверки агента вы можете обновить только следующие поля:

  • conversationalSetting

  • customAgentId

  • defaultLocale

  • primaryAgentInteraction

  • additionalAgentInteractions

  • phone

Если вам нужно обновить другие поля после проверки своего агента,Свяжитесь с нами. (Сначала вы должны войти в систему с учетной записью Google Business Messages. Чтобы зарегистрироваться для учетной записи, см. Зарегистрироваться в бизнес-сообщениях .)

Пример: обновление отображаемого имени

загрязнение

curl -X PATCH \
"https://businesscommunications.googleapis.com/v1/brands/BRAND_ID/agents/AGENT_ID?updateMask=displayName" \
-H "Content-Type: application/json" \
-H "User-Agent: curl/business-communications" \
-H "$(oauth2l header --json PATH_TO_SERVICE_ACCOUNT_KEY businesscommunications)" \
-d "{
    'displayName': 'Growing Tree Bank',
}"

Node.js

const businesscommunications = require('businesscommunications');
const {google} = require('googleapis');

// Initialize the Business Communications API
let bcApi = new businesscommunications.businesscommunications_v1.Businesscommunications({});

// Set the scope that we need for the Business Communications API
const scopes = [
  'https://www.googleapis.com/auth/businesscommunications',
];

// Set the private key to the service account file
const privatekey = require('PATH_TO_SERVICE_ACCOUNT_KEY');

/**
 * Initializes the Google credentials for calling the
 * Business Messages API.
 */
async function initCredentials() {
  // Configure a JWT auth client
  let authClient = new google.auth.JWT(
    privatekey.client_email,
    null,
    privatekey.private_key,
    scopes,
  );

  return new Promise(function(resolve, reject) {
    // Authenticate request
    authClient.authorize(function(err, tokens) {
      if (err) {
        reject(false);
      } else {
        resolve(authClient);
      }
    });
  });
}

async function main() {
  let authClient = await initCredentials();

  let agentName = 'brands/BRAND_ID/agents/AGENT_ID';

  if (authClient) {
    // Setup the parameters for the API call
    const apiParams = {
      auth: authClient,
      name: agentName,
      updateMask: 'displayName',
      resource: {
        displayName: 'Growing Tree Bank',
      }
    };

    bcApi.brands.agents.patch(apiParams, {}, (err, response) => {
      if (err !== undefined && err !== null) {
        console.dir(err);
      } else {
        // Agent found
        console.log(response.data);
      }
    });
  }
  else {
    console.log('Authentication failure.');
  }
}

main();
Этот код основан на клиентской библиотеке Node.js Business Communications .

Джава

import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.services.businesscommunications.v1.BusinessCommunications;
import com.google.api.services.businesscommunications.v1.model.Agent;
import java.io.FileInputStream;
import java.util.Arrays;

class Main {
  /**
   * Initializes credentials used by the Business Communications API.
   */
  private static BusinessCommunications.Builder getBusinessCommunicationsBuilder() {
    BusinessCommunications.Builder builder = null;
    try {
      GoogleCredential credential = GoogleCredential
            .fromStream(new FileInputStream("PATH_TO_SERVICE_ACCOUNT_KEY"));

      credential = credential.createScoped(Arrays.asList(
          "https://www.googleapis.com/auth/businesscommunications"));

      credential.refreshToken();

      HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
      JacksonFactory jsonFactory = JacksonFactory.getDefaultInstance();

      // Create instance of the Business Communications API
      builder = new BusinessCommunications
          .Builder(httpTransport, jsonFactory, null)
          .setApplicationName(credential.getServiceAccountProjectId());

      // Set the API credentials and endpoint
      builder.setHttpRequestInitializer(credential);
    } catch (Exception e) {
      e.printStackTrace();
    }

    return builder;
  }

  public static void main(String args[]) {
    try {
      // Create client library reference
      BusinessCommunications.Builder builder = getBusinessCommunicationsBuilder();

      String agentName = "brands/BRAND_ID/agents/AGENT_ID";

      Agent agent = new Agent().setDisplayName("Growing Tree Bank");

      BusinessCommunications.Brands.Agents.Patch request = builder
          .build().brands().agents().patch(agentName, agent);

      request.setUpdateMask("displayName");

      Agent updatedAgent = request.execute();
      System.out.println(updatedAgent.toPrettyString());
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
}
Этот код основан на клиентской библиотеке Java Business Communications .

Питон

from oauth2client.service_account import ServiceAccountCredentials
from businesscommunications.businesscommunications_v1_client import (
    BusinesscommunicationsV1
)
from businesscommunications.businesscommunications_v1_messages import (
    Agent,
    BusinesscommunicationsBrandsAgentsPatchRequest,
)

SCOPES = ['https://www.googleapis.com/auth/businesscommunications']
SERVICE_ACCOUNT_FILE = 'PATH_TO_SERVICE_ACCOUNT_KEY'

credentials = ServiceAccountCredentials.from_json_keyfile_name(
    SERVICE_ACCOUNT_FILE, scopes=SCOPES)

client = BusinesscommunicationsV1(credentials=credentials)

agents_service = BusinesscommunicationsV1.BrandsAgentsService(client)

agent_name = 'brands/BRAND_ID/agents/AGENT_ID'

agent=Agent(
          displayName='Growing Tree Bank'
      )

updated_agent = agents_service.Patch(
        BusinesscommunicationsBrandsAgentsPatchRequest(
            agent=agent,
            name=agent_name,
            updateMask='displayName'
        )
    )

print(updated_agent)
Этот код основан на клиентской библиотеке Python Business Communications .

Пример: укажите группы NON_LOCAL и групп точек входа LOCATION

загрязнение

curl -X PATCH \
"https://businesscommunications.googleapis.com/v1/brands/BRAND_ID/agents/AGENT_ID?updateMask=businessMessagesAgent.entryPointConfigs" \
-H "Content-Type: application/json" \
-H "User-Agent: curl/business-communications" \
-H "$(oauth2l header --json PATH_TO_SERVICE_ACCOUNT_KEY businesscommunications)" \
-d "{
  'businessMessagesAgent': {
    'entryPointConfigs': [
      {
        'allowedEntryPoint': 'NON_LOCAL',
      },
      {
        'allowedEntryPoint': 'LOCATION',
      },
    ],
  },
}"

Node.js

const businesscommunications = require('businesscommunications');
const {google} = require('googleapis');

// Initialize the Business Communications API
let bcApi = new businesscommunications.businesscommunications_v1.Businesscommunications({});

// Set the scope that we need for the Business Communications API
const scopes = [
  'https://www.googleapis.com/auth/businesscommunications',
];

// Set the private key to the service account file
const privatekey = require('PATH_TO_SERVICE_ACCOUNT_KEY');

/**
 * Initializes the Google credentials for calling the
 * Business Messages API.
 */
async function initCredentials() {
  // Configure a JWT auth client
  let authClient = new google.auth.JWT(
    privatekey.client_email,
    null,
    privatekey.private_key,
    scopes,
  );

  return new Promise(function(resolve, reject) {
    // Authenticate request
    authClient.authorize(function(err, tokens) {
      if (err) {
        reject(false);
      } else {
        resolve(authClient);
      }
    });
  });
}

async function main() {
  let authClient = await initCredentials();

  let agentName = 'brands/BRAND_ID/agents/AGENT_ID';

  if (authClient) {
    // Setup the parameters for the API call
    const apiParams = {
      auth: authClient,
      name: agentName,
      updateMask: 'businessMessagesAgent.entryPointConfigs',
      resource: {
        businessMessagesAgent: {
          entryPointConfigs: [
            {
              allowedEntryPoint: 'LOCATION',
            },
            {
              allowedEntryPoint: 'NON_LOCAL',
            },
          ],
        }
      }
    };

    bcApi.brands.agents.patch(apiParams, {}, (err, response) => {
      if (err !== undefined && err !== null) {
        console.dir(err);
      } else {
        // Agent found
        console.log(response.data);
      }
    });
  }
  else {
    console.log('Authentication failure.');
  }
}

main();
Этот код основан на клиентской библиотеке Node.js Business Communications .

Джава

import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.services.businesscommunications.v1.BusinessCommunications;
import com.google.api.services.businesscommunications.v1.model.*;
import java.io.FileInputStream;
import java.util.Arrays;

class Main {
  /**
   * Initializes credentials used by the Business Communications API.
   */
  private static BusinessCommunications.Builder getBusinessCommunicationsBuilder() {
    BusinessCommunications.Builder builder = null;
    try {
      GoogleCredential credential = GoogleCredential
            .fromStream(new FileInputStream("PATH_TO_SERVICE_ACCOUNT_KEY"));

      credential = credential.createScoped(Arrays.asList(
          "https://www.googleapis.com/auth/businesscommunications"));

      credential.refreshToken();

      HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
      JacksonFactory jsonFactory = JacksonFactory.getDefaultInstance();

      // Create instance of the Business Communications API
      builder = new BusinessCommunications
          .Builder(httpTransport, jsonFactory, null)
          .setApplicationName(credential.getServiceAccountProjectId());

      // Set the API credentials and endpoint
      builder.setHttpRequestInitializer(credential);
    } catch (Exception e) {
      e.printStackTrace();
    }

    return builder;
  }

  public static void main(String args[]) {
    try {
      // Create client library reference
      BusinessCommunications.Builder builder = getBusinessCommunicationsBuilder();

      String agentName = "brands/BRAND_ID/agents/AGENT_ID";

      Agent agent = new Agent().setBusinessMessagesAgent(
          new BusinessMessagesAgent().setEntryPointConfigs(Arrays.asList(
              new BusinessMessagesEntryPointConfig()
                  .setAllowedEntryPoint(
                      "NON_LOCAL"),
              new BusinessMessagesEntryPointConfig()
                  .setAllowedEntryPoint(
                      "LOCATION"))));

      BusinessCommunications.Brands.Agents.Patch request = builder
          .build().brands().agents().patch(agentName, agent);

      request.setUpdateMask("businessMessagesAgent.entryPointConfigs");

      Agent updatedAgent = request.execute();
      System.out.println(updatedAgent.toPrettyString());
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
}
Этот код основан на клиентской библиотеке Java Business Communications .

Питон

from oauth2client.service_account import ServiceAccountCredentials
from businesscommunications.businesscommunications_v1_client import (
    BusinesscommunicationsV1
)
from businesscommunications.businesscommunications_v1_messages import (
    Agent,
    BusinessMessagesAgent,
    BusinessMessagesEntryPointConfig,
    BusinesscommunicationsBrandsAgentsPatchRequest,
)

SCOPES = ['https://www.googleapis.com/auth/businesscommunications']
SERVICE_ACCOUNT_FILE = 'PATH_TO_SERVICE_ACCOUNT_KEY'

credentials = ServiceAccountCredentials.from_json_keyfile_name(
    SERVICE_ACCOUNT_FILE, scopes=SCOPES)

client = BusinesscommunicationsV1(credentials=credentials)

agents_service = BusinesscommunicationsV1.BrandsAgentsService(client)

agent_name = 'brands/BRAND_ID/agents/AGENT_ID'

agent=Agent(
    businessMessagesAgent=BusinessMessagesAgent(
        entryPointConfigs=[BusinessMessagesEntryPointConfig(
            allowedEntryPoint=BusinessMessagesEntryPointConfig.AllowedEntryPointValueValuesEnum.NON_LOCAL
        ), BusinessMessagesEntryPointConfig(
            allowedEntryPoint=BusinessMessagesEntryPointConfig.AllowedEntryPointValueValuesEnum.LOCATION
        )]
    )
)

updated_agent = agents_service.Patch(
        BusinesscommunicationsBrandsAgentsPatchRequest(
            agent=agent,
            name=agent_name,
            updateMask='businessMessagesAgent.entryPointConfigs'
        )
    )

print(updated_agent)
Этот код основан на клиентской библиотеке Python Business Communications .

Пример: обновить приветственное сообщение

Если вы обновляете какое-либо поле в рамках conversationalSettings -такого как welcomeMessage -вы должны обновить все поля в объекте, и вы должны указать локали настроек (как двуххарактерный код ISO 639-1 ).

загрязнение

curl -X PATCH \
"https://businesscommunications.googleapis.com/v1/brands/BRAND_ID/agents/AGENT_ID?updateMask=businessMessagesAgent.conversationalSettings.en" \
-H "Content-Type: application/json" \
-H "User-Agent: curl/business-communications" \
-H "$(oauth2l header --json PATH_TO_SERVICE_ACCOUNT_KEY businesscommunications)" \
-d "{
    'businessMessagesAgent': {
        'conversationalSettings': {
            'en': {
                'welcomeMessage': {
                    'text': 'Thanks for contacting Growing Tree Bank. What can I help with today?',
                },
                'offlineMessage': {
                    'text': 'We\'re closed for the night. Please reach out to us again tomorrow.',
                },
                'privacyPolicy': {
                    'url': 'https://www.growingtreebank.com/privacy',
                },
                'conversationStarters': [
                    {
                        'suggestion': {
                            'reply': {
                                'text': 'Set up an account',
                                'postbackData': 'new-account',
                            },
                        },
                    },
                    {
                        'suggestion': {
                            'reply': {
                                'text': 'Look up account information',
                                'postbackData': 'account-lookup',
                            },
                        },
                    },
                ],
            },
        },
    },
}"

Node.js

const businesscommunications = require('businesscommunications');
const {google} = require('googleapis');

// Initialize the Business Communications API
let bcApi = new businesscommunications.businesscommunications_v1.Businesscommunications({});

// Set the scope that we need for the Business Communications API
const scopes = [
  'https://www.googleapis.com/auth/businesscommunications',
];

// Set the private key to the service account file
const privatekey = require('PATH_TO_SERVICE_ACCOUNT_KEY');

/**
 * Initializes the Google credentials for calling the
 * Business Messages API.
 */
async function initCredentials() {
  // Configure a JWT auth client
  let authClient = new google.auth.JWT(
    privatekey.client_email,
    null,
    privatekey.private_key,
    scopes,
  );

  return new Promise(function(resolve, reject) {
    // Authenticate request
    authClient.authorize(function(err, tokens) {
      if (err) {
        reject(false);
      } else {
        resolve(authClient);
      }
    });
  });
}

async function main() {
  let authClient = await initCredentials();

  let agentName = 'brands/BRAND_ID/agents/AGENT_ID';

  if (authClient) {
    // Setup the parameters for the API call
    const apiParams = {
      auth: authClient,
      name: agentName,
      updateMask: 'businessMessagesAgent.conversationalSettings.en',
      resource: {
        businessMessagesAgent: {
          conversationalSettings: {
            en: {
              privacyPolicy: { url: 'https://www.growingtreebank.com/privacy' },
              welcomeMessage: { text: 'Thanks for contacting Growing Tree Bank. What can I help with today?' },
              offlineMessage: { text: 'We\'re closed for the night. Please reach out to us again tomorrow.' },
              conversationStarters: [
                {
                  suggestion: {
                    reply: {
                      text: 'Set up an account',
                      postbackData: 'new-account',
                    },
                  },
                },
                {
                  suggestion: {
                    reply: {
                      text: 'Look up account information',
                      postbackData: 'account-lookup',
                    },
                  },
                },
              ],
            },
          }
        }
      }
    };

    bcApi.brands.agents.patch(apiParams, {}, (err, response) => {
      if (err !== undefined && err !== null) {
        console.dir(err);
      } else {
        // Agent found
        console.log(response.data);
      }
    });
  }
  else {
    console.log('Authentication failure.');
  }
}

main();
Этот код основан на клиентской библиотеке Node.js Business Communications .

Джава

import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.services.businesscommunications.v1.BusinessCommunications;
import com.google.api.services.businesscommunications.v1.model.*;
import com.google.common.collect.ImmutableMap;
import java.io.FileInputStream;
import java.util.Arrays;

class Main {
  /**
   * Initializes credentials used by the Business Communications API.
   */
  private static BusinessCommunications.Builder getBusinessCommunicationsBuilder() {
    BusinessCommunications.Builder builder = null;
    try {
      GoogleCredential credential = GoogleCredential
            .fromStream(new FileInputStream("PATH_TO_SERVICE_ACCOUNT_KEY"));

      credential = credential.createScoped(Arrays.asList(
          "https://www.googleapis.com/auth/businesscommunications"));

      credential.refreshToken();

      HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
      JacksonFactory jsonFactory = JacksonFactory.getDefaultInstance();

      // Create instance of the Business Communications API
      builder = new BusinessCommunications
          .Builder(httpTransport, jsonFactory, null)
          .setApplicationName(credential.getServiceAccountProjectId());

      // Set the API credentials and endpoint
      builder.setHttpRequestInitializer(credential);
    } catch (Exception e) {
      e.printStackTrace();
    }

    return builder;
  }

  public static void main(String args[]) {
    try {
      // Create client library reference
      BusinessCommunications.Builder builder = getBusinessCommunicationsBuilder();

      String agentName = "brands/BRAND_ID/agents/AGENT_ID";

      Agent agent = new Agent().setBusinessMessagesAgent(
          new BusinessMessagesAgent().setConversationalSettings(ImmutableMap.of("en",
              new ConversationalSetting()
                  .setPrivacyPolicy(new PrivacyPolicy().setUrl("https://www.growingtreebank.com/privacy"))
                  .setWelcomeMessage(new WelcomeMessage().setText("Thanks for contacting Growing Tree Bank. What can I help with today?"))
                  .setOfflineMessage(new OfflineMessage().setText("We're closed for the night. Please reach out to us again tomorrow."))
                  .setConversationStarters(Arrays.asList(
                      new ConversationStarters().setSuggestion(new Suggestion()
                          .setReply(new SuggestedReply()
                              .setText("Set up an account")
                              .setPostbackData("new-account"))),
                      new ConversationStarters().setSuggestion(new Suggestion()
                          .setReply(new SuggestedReply()
                              .setText("Look up account information")
                              .setPostbackData("account-lookup")))
                      )))));

      BusinessCommunications.Brands.Agents.Patch request = builder
          .build().brands().agents().patch(agentName, agent);

      request.setUpdateMask("businessMessagesAgent.conversationalSettings.en");

      Agent updatedAgent = request.execute();
      System.out.println(updatedAgent.toPrettyString());
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
}
Этот код основан на клиентской библиотеке Java Business Communications .

Питон

from oauth2client.service_account import ServiceAccountCredentials
from businesscommunications.businesscommunications_v1_client import (
    BusinesscommunicationsV1
)
from businesscommunications.businesscommunications_v1_messages import (
    Agent,
    BusinessMessagesAgent,
    ConversationStarters,
    ConversationalSetting,
    OfflineMessage,
    PrivacyPolicy,
    WelcomeMessage,
    BusinesscommunicationsBrandsAgentsPatchRequest,
)

SCOPES = ['https://www.googleapis.com/auth/businesscommunications']
SERVICE_ACCOUNT_FILE = 'PATH_TO_SERVICE_ACCOUNT_KEY'

credentials = ServiceAccountCredentials.from_json_keyfile_name(
    SERVICE_ACCOUNT_FILE, scopes=SCOPES)

client = BusinesscommunicationsV1(credentials=credentials)

agents_service = BusinesscommunicationsV1.BrandsAgentsService(client)

agent_name = 'brands/BRAND_ID/agents/AGENT_ID'

agent=Agent(
		businessMessagesAgent=BusinessMessagesAgent(
		  	conversationalSettings=BusinessMessagesAgent.ConversationalSettingsValue(
		        additionalProperties=[BusinessMessagesAgent.ConversationalSettingsValue.AdditionalProperty(
		            key='en',
		            value=ConversationalSetting(
		                privacyPolicy=PrivacyPolicy(url='https://www.growingtreebank.com/privacy'),
		                welcomeMessage=WelcomeMessage(text='Thanks for contacting Growing Tree Bank. What can I help with today?'),
		                offlineMessage=OfflineMessage(text='We\'re closed for the night. Please reach out to us again tomorrow.'),
		                conversationStarters=[
		                    ConversationStarters(
		                        suggestion=Suggestion(
		                            reply=SuggestedReply(text='Set up an account',
		                                postbackData='new-account')
		                        )
		                    ),
		                    ConversationStarters(
		                        suggestion=Suggestion(
		                            reply=SuggestedReply(text='Look up account information',
		                                postbackData='account-lookup')
		                        )
		                    )]
		                )
		            )
		        ]
		    )
		)
)

updated_agent = agents_service.Patch(
        BusinesscommunicationsBrandsAgentsPatchRequest(
            agent=agent,
            name=agent_name,
            updateMask='businessMessagesAgent.conversationalSettings.en'
        )
    )

print(updated_agent)
Этот код основан на клиентской библиотеке Python Business Communications .

Удалить агента

Когда вы удаляете агента, бизнес -сообщения удаляют все данные агента. Бизнес -сообщения не удаляют сообщения, отправляемые вашим агентом, которые находятся в пути или хранятся на устройстве пользователя. Сообщения пользователям не являются данными агента.

Удалить запросы не удастся, если у агента есть связанное местоположение или если вы пытались проверить агента один или несколько раз. Чтобы обновить местоположения, см. Добавить местоположения .

Вы не можете удалить агента, который проверяется. Чтобы удалить агента, который вы проверили или пытались проверить,Свяжитесь с нами. (Вы должны сначала войти в систему с учетной записью Business Messages Google. Чтобы зарегистрироваться для учетной записи, см. Зарегистрироваться в бизнес-сообщениях .)

Чтобы удалить агент, запустите следующую команду. Замените BRAND_ID и AGENT_ID на уникальные значения от name агента.

загрязнение


# This code deletes an agent.
# Read more: https://developers.google.com/business-communications/business-messages/reference/business-communications/rest/v1/brands.agents/delete

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

curl -X DELETE "https://businesscommunications.googleapis.com/v1/brands/__BRAND_ID__/agents/__AGENT_ID__" \
-H "Content-Type: application/json" \
-H "User-Agent: curl/business-communications" \
-H "$(oauth2l header --json ./service_account_key.json businesscommunications)"

Node.js


/**
 * This code snippet deletes an agent.
 * Read more: https://developers.google.com/business-communications/business-messages/reference/business-communications/rest/v1/brands.agents/delete
 *
 * This code is based on the https://github.com/google-business-communications/nodejs-businesscommunications Node.js
 * Business Communications client library.
 */

/**
 * Edit the values below:
 */
const BRAND_ID = 'EDIT_HERE';
const AGENT_ID = 'EDIT_HERE';
const PATH_TO_SERVICE_ACCOUNT_KEY = './service_account_key.json';

const businesscommunications = require('businesscommunications');
const {google} = require('googleapis');

// Initialize the Business Communications API
const bcApi = new businesscommunications.businesscommunications_v1.Businesscommunications({});

// Set the scope that we need for the Business Communications API
const scopes = [
  'https://www.googleapis.com/auth/businesscommunications',
];

// Set the private key to the service account file
const privatekey = require(PATH_TO_SERVICE_ACCOUNT_KEY);

async function main() {
  const authClient = await initCredentials();

  const agentName = 'brands/' + BRAND_ID + '/agents/' + AGENT_ID;

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

    bcApi.brands.agents.delete(apiParams, {}, (err, response) => {
      if (err !== undefined && err !== null) {
        console.dir(err);
      } else {
        // Agent removed
        console.log(response.data);
      }
    });
  }
  else {
    console.log('Authentication failure.');
  }
}

/**
 * Initializes the Google credentials for calling the
 * Business Messages API.
 */
 async function initCredentials() {
  // Configure a JWT auth client
  const authClient = new google.auth.JWT(
    privatekey.client_email,
    null,
    privatekey.private_key,
    scopes,
  );

  return new Promise(function(resolve, reject) {
    // Authenticate request
    authClient.authorize(function(err, tokens) {
      if (err) {
        reject(false);
      } else {
        resolve(authClient);
      }
    });
  });
}

main();

Джава

import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.services.businesscommunications.v1.BusinessCommunications;
import com.google.api.services.businesscommunications.v1.model.*;
import java.io.FileInputStream;
import java.util.Arrays;

class Main {
  /**
   * Initializes credentials used by the Business Communications API.
   */
  private static BusinessCommunications.Builder getBusinessCommunicationsBuilder() {
    BusinessCommunications.Builder builder = null;
    try {
      GoogleCredential credential = GoogleCredential
            .fromStream(new FileInputStream("PATH_TO_SERVICE_ACCOUNT_KEY"));

      credential = credential.createScoped(Arrays.asList(
          "https://www.googleapis.com/auth/businesscommunications"));

      credential.refreshToken();

      HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
      JacksonFactory jsonFactory = JacksonFactory.getDefaultInstance();

      // Create instance of the Business Communications API
      builder = new BusinessCommunications
          .Builder(httpTransport, jsonFactory, null)
          .setApplicationName(credential.getServiceAccountProjectId());

      // Set the API credentials and endpoint
      builder.setHttpRequestInitializer(credential);
    } catch (Exception e) {
      e.printStackTrace();
    }

    return builder;
  }

  public static void main(String args[]) {
    try {
      // Create client library reference
      BusinessCommunications.Builder builder = getBusinessCommunicationsBuilder();

      String agentName = "brands/BRAND_ID/agents/AGENT_ID";

      BusinessCommunications.Brands.Agents.Delete request
         = builder.build().brands().agents().delete(agentName);

      System.out.println(request.execute());
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
}
Этот код основан на клиентской библиотеке Java Business Communications .

Питон


"""This code deletes an agent.

Read more: https://developers.google.com/business-communications/business-messages/reference/business-communications/rest/v1/brands.agents/delete

This code is based on the https://github.com/google-business-communications/python-businessmessages
Python Business Messages client library.
"""

from oauth2client.service_account import ServiceAccountCredentials
from businesscommunications.businesscommunications_v1_client import BusinesscommunicationsV1
from businesscommunications.businesscommunications_v1_messages import (
    Agent,
    BusinesscommunicationsBrandsAgentsDeleteRequest,
)

# Edit the values below:
BRAND_ID = 'EDIT_HERE'
AGENT_ID = 'EDIT_HERE'
SCOPES = ['https://www.googleapis.com/auth/businesscommunications']
SERVICE_ACCOUNT_FILE = './service_account_key.json'

credentials = ServiceAccountCredentials.from_json_keyfile_name(
    SERVICE_ACCOUNT_FILE, scopes=SCOPES)

client = BusinesscommunicationsV1(credentials=credentials)

agents_service = BusinesscommunicationsV1.BrandsAgentsService(client)

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

agent = agents_service.Delete(BusinesscommunicationsBrandsAgentsDeleteRequest(
        name=agent_name
    ))

print(agent)

Для форматирования и вариантов стоимости см. brands.agents.delete .

Удалить бренд

Когда вы удаляете бренд, вы выполняете запрос Delete с API Business Communications. Удалить запросы терпят неудачу, если у вас есть один или несколько агентов или мест, связанных с брендом, даже если эти агенты принадлежат к другому продукту.

Чтобы удалить бренд, запустите следующую команду. Замените BRAND_ID на уникальное значение от name бренда.

загрязнение


# This code deletes a brand.
# Read more: https://developers.google.com/business-communications/business-messages/reference/business-communications/rest/v1/brands/delete

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

curl -X DELETE "https://businesscommunications.googleapis.com/v1/brands/__BRAND_ID__" \
-H "Content-Type: application/json" \
-H "User-Agent: curl/business-communications" \
-H "$(oauth2l header --json ./service_account_key.json businesscommunications)"

Node.js


/**
 * This code snippet deletes a brand.
 * Read more: https://developers.google.com/business-communications/business-messages/reference/business-communications/rest/v1/brands/delete
 *
 * This code is based on the https://github.com/google-business-communications/nodejs-businesscommunications Node.js
 * Business Communications client library.
 */

/**
 * Edit the values below:
 */
const BRAND_ID = 'EDIT_HERE';
const PATH_TO_SERVICE_ACCOUNT_KEY = './service_account_key.json';

const businesscommunications = require('businesscommunications');
const {google} = require('googleapis');

// Initialize the Business Communications API
const bcApi = new businesscommunications.businesscommunications_v1.Businesscommunications({});

// Set the scope that we need for the Business Communications API
const scopes = [
  'https://www.googleapis.com/auth/businesscommunications',
];

// Set the private key to the service account file
const privatekey = require(PATH_TO_SERVICE_ACCOUNT_KEY);

async function main() {
  const authClient = await initCredentials();

  const brandName = 'brands/' + BRAND_ID;

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

    bcApi.brands.delete(apiParams, {}, (err, response) => {
      if (err !== undefined && err !== null) {
        console.dir(err);
      } else {
        // Brand removed
        console.log(response.data);
      }
    });
  }
  else {
    console.log('Authentication failure.');
  }
}

/**
 * Initializes the Google credentials for calling the
 * Business Messages API.
 */
 async function initCredentials() {
  // Configure a JWT auth client
  const authClient = new google.auth.JWT(
    privatekey.client_email,
    null,
    privatekey.private_key,
    scopes,
  );

  return new Promise(function(resolve, reject) {
    // Authenticate request
    authClient.authorize(function(err, tokens) {
      if (err) {
        reject(false);
      } else {
        resolve(authClient);
      }
    });
  });
}

main();

Джава

import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.services.businesscommunications.v1.BusinessCommunications;
import com.google.api.services.businesscommunications.v1.model.*;
import java.io.FileInputStream;
import java.util.Arrays;

class Main {
  /**
   * Initializes credentials used by the Business Communications API.
   */
  private static BusinessCommunications.Builder getBusinessCommunicationsBuilder() {
    BusinessCommunications.Builder builder = null;
    try {
      GoogleCredential credential = GoogleCredential
            .fromStream(new FileInputStream("PATH_TO_SERVICE_ACCOUNT_KEY"));

      credential = credential.createScoped(Arrays.asList(
          "https://www.googleapis.com/auth/businesscommunications"));

      credential.refreshToken();

      HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
      JacksonFactory jsonFactory = JacksonFactory.getDefaultInstance();

      // Create instance of the Business Communications API
      builder = new BusinessCommunications
          .Builder(httpTransport, jsonFactory, null)
          .setApplicationName(credential.getServiceAccountProjectId());

      // Set the API credentials and endpoint
      builder.setHttpRequestInitializer(credential);
    } catch (Exception e) {
      e.printStackTrace();
    }

    return builder;
  }

  public static void main(String args[]) {
    try {
      // Create client library reference
      BusinessCommunications.Builder builder = getBusinessCommunicationsBuilder();

      String brandName = "brands/BRAND_ID";

      BusinessCommunications.Brands.Delete request = builder.build().brands().delete(brandName);

      System.out.println(request.execute());
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
}
Этот код основан на клиентской библиотеке Java Business Communications .

Питон


"""This code deletes a brand.

Read more: https://developers.google.com/business-communications/business-messages/reference/business-communications/rest/v1/brands/delete

This code is based on the https://github.com/google-business-communications/python-businessmessages
Python Business Messages client library.
"""

from oauth2client.service_account import ServiceAccountCredentials
from businesscommunications.businesscommunications_v1_client import BusinesscommunicationsV1
from businesscommunications.businesscommunications_v1_messages import (
    BusinesscommunicationsBrandsAgentsDeleteRequest
)

# Edit the values below:
BRAND_ID = 'EDIT_HERE'
SCOPES = ['https://www.googleapis.com/auth/businesscommunications']
SERVICE_ACCOUNT_FILE = './service_account_key.json'

credentials = ServiceAccountCredentials.from_json_keyfile_name(
    SERVICE_ACCOUNT_FILE, scopes=SCOPES)

client = BusinesscommunicationsV1(credentials=credentials)

agents_service = BusinesscommunicationsV1.BrandsAgentsService(client)

brand_name = 'brands/' + BRAND_ID

agent = agents_service.Delete(BusinesscommunicationsBrandsAgentsDeleteRequest(
        name=brand_name
    ))

print(agent)

Для форматирования и вариантов стоимости см. brands.delete .

Следующие шаги

Теперь, когда у вас есть агент, вы можете предпринять следующие шаги: