Creare agenti per gestire i brand

Dopo aver effettuato la registrazione come partner, puoi abilitare le conversazioni per i brand che gestisci creando per loro agenti Business Messages.

Un agente è un'entità conversazionale con cui gli utenti interagiscono. Crei un agente per ogni brand che gestisci. Puoi creare e gestire gli agenti con l'API Business Communications e controllare la messaggistica per i tuoi agenti con l'API Business Messages.

Un agente si occupa delle funzioni aziendali di un brand, come l'assistenza online e le eventuali sedi fisiche. Ogni messaggio contiene il contesto da cui l'utente ha avviato la conversazione. La tua infrastruttura di routing dei messaggi è in grado di rilevare se l'utente ha visualizzato una sede specifica dell'attività o ha cercato assistenza generale e può indirizzare i messaggi alla destinazione corretta.

La relazione tra agente e brand

Ad esempio, se gestisci il brand Growing Tree Bank, che ha un sito web e due sedi, crei un solo agente "Growing Tree Bank". Gli utenti possono incontrare l'agente tramite ricerche generali o basate sulla località; il contesto in cui l'utente lo ha trovato viene trasmesso insieme a ogni messaggio al webhook. Puoi utilizzare questo contesto per indirizzare il messaggio al personale in una sede o al team di assistenza del sito web, che crea una risposta e continua la conversazione con l'utente.

Aspettative

Prima di creare un agente, scopri le aspettative degli agenti su Business Messages.

  • Gli agenti devono seguire le linee guida di progettazione descritte in Progettazione della conversazione per Business Messages.
  • Gli agenti devono avere rappresentanti umani disponibili per rispondere alle domande quando l'automazione non è in grado di soddisfare una richiesta o quando viene richiesto dagli utenti.

  • Gli agenti devono mantenere una valutazione della soddisfazione del cliente (CSAT) di almeno l'80% e un tasso di risposta dei commercianti (MRR) di almeno il 95%, come descritto nella sezione Metriche.

Crea un agente

Per creare un agente, devi raccogliere e inviare informazioni sul brand e su come vuoi che venga visualizzato dagli utenti.

Se gestisci più brand, ripeti i passaggi per creare un agente per ogni brand.

Prerequisiti

Prima di creare agenti per i brand che gestisci, devi raccogliere alcune informazioni:

Ambiente di sviluppo

Informazioni sull'ambiente di sviluppo.

Dettagli del brand

Informazioni sul brand rappresentato dall'agente.

  • Nome brand
  • Sito web del brand
  • Opzioni di contatto sul sito web (come definite in OPTION)
  • Numero di telefono rivolto ai consumatori
  • Numeri di telefono abilitati per la deviazione delle chiamate

Aspetto e criteri dell'agente

Informazioni su come l'agente viene visualizzato dagli utenti e sul suo funzionamento.

  • Nome dell'agente, così come vuoi che venga visualizzato nelle conversazioni con gli utenti
  • Norme sulla privacy, indicate come URL disponibili pubblicamente che iniziano con "https://"
  • (Consigliato) Logo dell'agente (1024 x 1024 px), come URL disponibile pubblicamente

    In una conversazione, i loghi vengono visualizzati come cerchi con un diametro di 1024 px. Assicurati che il tuo logo venga visualizzato correttamente come un cerchio.

  • (Facoltativo) ID agente personalizzato, che identifica il brand nei messaggi ricevuti dal webhook

Interazione con l'agente

Informazioni su come l'agente interagisce con gli utenti.

  • Le impostazioni internazionali in cui opera generalmente l'agente, specificate da un codice lingua ISO 639-1 a due caratteri.

  • Messaggio di benvenuto dell'agente

    Cosa dice l'agente per salutare gli utenti?

  • Spunti di conversazione con l'agente

    Un elenco di suggerimenti, sotto forma di chip di conversazione (come definiti in SuggestedReply), per consentire all'utente di interagire con l'agente

    • Testo mostrato all'utente nel chip
    • Dati postback, la stringa reinviata al webhook nel payload del messaggio se l'utente tocca il chip
  • Orari automatici e della chat dal vivo

    • Ora di inizio giornaliera, come oggetto TimeOfDay

      Ad esempio, 8:15 è

      {
        "hours": 8,
        "minutes": 15,
      }
      
    • Ora di fine giornaliera, come oggetto TimeOfDay

      Ad esempio, 19:30 corrisponde

      {
        "hours": 19,
        "minutes": 30,
      }
      
    • Giorno di inizio, il primo giorno della settimana in cui l'agente è disponibile per la chat (come definito in DayOfWeek)

    • Giorno di fine, l'ultimo giorno della settimana in cui l'agente è disponibile per la chat (come definito in DayOfWeek)

    • Fuso orario in cui opera l'agente (come definito nel database dei fusi orari IANA, ad esempio "America/Los_Angeles")

Punti di contatto dell'agente

Informazioni su dove gli utenti possono avviare conversazioni con l'agente.

  • Punti di ingresso dell'agente consentiti, in cui gli utenti possono avviare conversazioni con gli agenti (NON_LOCAL e/o LOCATION)

Informazioni sui punti di contatto NON_LOCAL (non si applicano al punto di ingresso di Google Ads).

  • Regioni consentite (come codici regione CLDR) per limitare l'accesso a livello di regione a NON_LOCAL punti di ingresso.

    Indipendentemente dalla regione, un agente può avere un solo numero di telefono associato. Se hai bisogno di un numero di telefono diverso in base alla regione, è necessario creare un agente diverso per ogni regione.

    Per attivare i punti di ingresso di NON_LOCAL in tutte le regioni disponibili, utilizza 001 come prefisso internazionale.

Installare e testare oauth2l

Tutte le richieste curl nella documentazione di questo sito utilizzano oauth2l per l'autenticazione. Se vuoi utilizzare la riga di comando per connetterti alle API Business Communications e Business Messages, installa oauth2l.

Per installare oauth2l con Python 3,

  1. Scarica oauth2l.

  2. Cambia la directory in "./oauth2l/python".

  3. Installa oauth2l con il comando seguente.

    sudo python setup.sh build && sudo python setup.py install
    
  4. Verifica che oauth2l possa generare un token di autorizzazione.

    oauth2l header --json resources/bm-agent-service-account-credentials.json businesscommunications
    
  5. Verifica che l'output crei un token di autorizzazione nel formato:

    Authorization: Bearer AUTHORIZATION_BEARER_TOKEN
    

Esistono altri modi per installare oauth2l per diversi sistemi operativi. Indipendentemente dal metodo di installazione, prima di procedere assicurati di poter generare un token di autorizzazione in base alle credenziali JSON dell'account di servizio.

Crea l'agente

Dopo aver raccolto le informazioni, puoi creare l'agente.

  1. Crea il brand rappresentato dall'agente. Se il brand esiste già, scarica il name del brand e vai al passaggio successivo.

    In un terminale, esegui questo comando:

    cURL

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

    Node.js

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

    Java

    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();
        }
      }
    }
    
    Questo codice si basa sulla libreria client di Java Business Communications.

    Python

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

    Archivia il valore name restituito dall'API. Ti servirà per effettuare aggiornamenti o creare agenti.

    Per aggiornare o cercare brand, visita il sito brands.

  2. Crea l'agente. Sostituisci BRAND_ID con la parte del valore name del brand che segue "brand/". Ad esempio, se name è "brands/12345", l'ID brand è "12345".

    In un terminale, esegui questo comando:

    cURL

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

    Node.js

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

    Java

    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();
        }
      }
    }
    
    Questo codice si basa sulla libreria client di Java Business Communications.

    Python

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

    Per informazioni su formattazione e opzioni dei valori, consulta brands.agents.

  3. Se il brand dispone di sedi che vuoi associare al tuo agente, consulta Aggiungere località.

Esempio: creare un agente per 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',
                        },
                    ],
                },
            },
        },
    },
}"

Memorizza le informazioni importanti

Quando crei un agente, l'API Business Communications restituisce i valori dell'agente, tra cui name e testUrls.

Imposta un webhook a livello di agente

Ricevi i messaggi inviati all'agente nel webhook. Se vuoi che i messaggi per un agente specifico arrivino a un webhook diverso, puoi impostare un webhook a livello di agente.

Per impostare un webhook a livello di agente, utilizza la Console per gli sviluppatori.

Testa un agente

Ogni agente ha URL di test che ti consentono di vedere come viene visualizzata una conversazione con l'agente con l'agente e di verificare la tua infrastruttura di messaggistica.

Un TestUrl ha gli attributi url e surface. Per eseguire il test con un dispositivo iOS, utilizza l'URL del test con un valore iniziale di SURFACE_IOS_MAPS. L'apertura dell'URL su un dispositivo iOS su cui è installata l'app Google Maps apre una conversazione completamente funzionale con l'agente.

I dispositivi Android hanno due URL di test. Gli URL con un valore surface pari a SURFACE_ANDROID_MAPS conversazioni aperte in Google Maps e rappresentano punti di contatto conversazionali visualizzati in Google Maps. Gli URL con un valore surface pari a SURFACE_ANDROID_WEB aprono le conversazioni in una visualizzazione conversazionale overlay e rappresentano tutti gli altri punti di ingresso.

Una volta aperta una piattaforma conversazionale, la conversazione include tutte le informazioni di branding visibili agli utenti e, quando invii un messaggio all'agente, il tuo webhook riceve il messaggio, incluso il payload JSON completo che puoi aspettarti durante la comunicazione con gli utenti.

Per aprire l'URL di test di un agente, tocca un link o utilizza l'Avvio app di Business Messages Agent su un dispositivo mobile.

Recupera informazioni sull'agente

Per ottenere informazioni su un agente, ad esempio agentTestUrl, puoi recuperare le informazioni dall'API Business Communications, a condizione che tu disponga del valore name dell'agente.

Richiedi informazioni per un singolo agente

Per ottenere informazioni sull'agente, esegui questo comando. Sostituisci BRAND_ID e AGENT_ID con i valori univoci del valore name dell'agente.

cURL


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

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

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

Node.js


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

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

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

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

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

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

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

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

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

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

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

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

main();

Java

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

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

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

      credential.refreshToken();

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

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

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

    return builder;
  }

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

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

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

      Agent agent = request.execute();

      System.out.println(agent.toPrettyString());
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
}
Questo codice si basa sulla libreria client di Java Business Communications.

Python


"""This code gets the agent.

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

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

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

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

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

client = BusinesscommunicationsV1(credentials=credentials)

agents_service = BusinesscommunicationsV1.BrandsAgentsService(client)

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

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

print(agent)

Elencare tutti gli agenti per un brand

Se non conosci il valore name dell'agente, puoi ottenere informazioni per tutti gli agenti associati a un brand omettendo il valore AGENT_ID dall'URL di una richiesta GET.

cURL


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

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

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

Node.js


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

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

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

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

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

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

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

  const brandName = 'brands/' + BRAND_ID;

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

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

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

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

main();

Java

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

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

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

      credential.refreshToken();

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

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

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

    return builder;
  }

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

      String brandName = "brands/BRAND_ID";

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

      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();
    }
  }
}
Questo codice si basa sulla libreria client di Java Business Communications.

Python


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

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

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

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

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

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

client = BusinesscommunicationsV1(credentials=credentials)

agents_service = BusinesscommunicationsV1.BrandsAgentsService(client)

brand_name = 'brands/' + BRAND_ID

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

print(agents)

Aggiorna informazioni agente

Per aggiornare un agente, esegui una richiesta PATCH con l'API Business Communications. Quando effettui la chiamata API, includi i nomi dei campi che stai modificando come valori per il parametro URL "updateMask".

Ad esempio, se aggiorni i campi displayName e customAgentId, il parametro URL "updateMask" è "updateMask=displayName,businessMessageAgent.customAgentId".

Per informazioni su formattazione e opzioni dei valori, consulta brands.agents.patch.

Se non conosci il name di un agente, consulta l'articolo Elencare tutti gli agenti per un brand.

Dopo aver verificato un agente, puoi aggiornare solo i seguenti campi:

  • conversationalSetting

  • customAgentId

  • defaultLocale

  • primaryAgentInteraction

  • additionalAgentInteractions

  • phone

Se devi aggiornare altri campi dopo la verifica dell'agente, contattaci. Devi prima accedere con un Account Google di Business Messages. Per creare un account, consulta Registrazione con Business Messages.

Esempio: aggiornare il nome visualizzato

cURL

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

Node.js

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

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

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

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

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

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

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

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

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

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

main();
Questo codice si basa sulla libreria client di Node.js Business Communications.

Java

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

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

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

      credential.refreshToken();

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

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

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

    return builder;
  }

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

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

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

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

      request.setUpdateMask("displayName");

      Agent updatedAgent = request.execute();
      System.out.println(updatedAgent.toPrettyString());
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
}
Questo codice si basa sulla libreria client di Java Business Communications.

Python

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

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

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

client = BusinesscommunicationsV1(credentials=credentials)

agents_service = BusinesscommunicationsV1.BrandsAgentsService(client)

agent_name = 'brands/BRAND_ID/agents/AGENT_ID'

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

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

print(updated_agent)
Questo codice si basa sulla libreria client di Python Business Communications.

Esempio: specifica i gruppi di punti di ingresso NON_LOCAL e LOCATION

cURL

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

Node.js

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

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

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

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

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

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

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

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

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

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

main();
Questo codice si basa sulla libreria client di Node.js Business Communications.

Java

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

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

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

      credential.refreshToken();

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

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

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

    return builder;
  }

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

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

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

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

      request.setUpdateMask("businessMessagesAgent.entryPointConfigs");

      Agent updatedAgent = request.execute();
      System.out.println(updatedAgent.toPrettyString());
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
}
Questo codice si basa sulla libreria client di Java Business Communications.

Python

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

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

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

client = BusinesscommunicationsV1(credentials=credentials)

agents_service = BusinesscommunicationsV1.BrandsAgentsService(client)

agent_name = 'brands/BRAND_ID/agents/AGENT_ID'

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

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

print(updated_agent)
Questo codice si basa sulla libreria client di Python Business Communications.

Esempio: aggiornare il messaggio di benvenuto

Se aggiorni un campo all'interno di conversationalSettings, ad esempio welcomeMessage, devi aggiornare tutti i campi dell'oggetto e devi specificare le impostazioni internazionali delle impostazioni (sotto forma di un codice lingua ISO 639-1 a due caratteri).

cURL

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

Node.js

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

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

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

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

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

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

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

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

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

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

main();
Questo codice si basa sulla libreria client di Node.js Business Communications.

Java

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

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

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

      credential.refreshToken();

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

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

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

    return builder;
  }

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

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

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

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

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

      Agent updatedAgent = request.execute();
      System.out.println(updatedAgent.toPrettyString());
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
}
Questo codice si basa sulla libreria client di Java Business Communications.

Python

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

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

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

client = BusinesscommunicationsV1(credentials=credentials)

agents_service = BusinesscommunicationsV1.BrandsAgentsService(client)

agent_name = 'brands/BRAND_ID/agents/AGENT_ID'

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

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

print(updated_agent)
Questo codice si basa sulla libreria client di Python Business Communications.

Elimina un agente

Quando elimini un agente, Business Messages elimina tutti i dati dell'agente. Business Messages non elimina i messaggi inviati dal tuo agente in transito o archiviati sul dispositivo di un utente. I messaggi inviati agli utenti non sono dati degli agenti.

Le richieste di eliminazione non vanno a buon fine se all'agente è associata una località o se hai tentato di verificare l'agente una o più volte. Per aggiornare le località, consulta Aggiungere località.

Non puoi eliminare un agente verificato. Per eliminare un agente che hai verificato o che hai tentato di verificare, contattaci. Devi prima accedere con un Account Google di Business Messages. Per creare un account, consulta Registrazione con Business Messages.

Per eliminare un agente, esegui questo comando. Sostituisci BRAND_ID e AGENT_ID con i valori univoci del valore name dell'agente.

cURL


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

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

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

Node.js


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

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

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

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

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

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

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

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

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

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

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

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

main();

Java

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

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

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

      credential.refreshToken();

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

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

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

    return builder;
  }

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

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

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

      System.out.println(request.execute());
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
}
Questo codice si basa sulla libreria client di Java Business Communications.

Python


"""This code deletes an agent.

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

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

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

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

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

client = BusinesscommunicationsV1(credentials=credentials)

agents_service = BusinesscommunicationsV1.BrandsAgentsService(client)

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

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

print(agent)

Per informazioni su formattazione e opzioni dei valori, consulta brands.agents.delete.

Eliminare un brand

Quando elimini un brand, esegui una richiesta DELETE con l'API Business Communications. Le richieste di eliminazione non vanno a buon fine se uno o più agenti o sedi sono associati al brand, anche se gli agenti appartengono a un altro prodotto.

Per eliminare un brand, esegui questo comando. Sostituisci BRAND_ID con il valore univoco del name del brand.

cURL


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

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

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

Node.js


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

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

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

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

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

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

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

  const brandName = 'brands/' + BRAND_ID;

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

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

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

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

main();

Java

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

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

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

      credential.refreshToken();

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

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

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

    return builder;
  }

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

      String brandName = "brands/BRAND_ID";

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

      System.out.println(request.execute());
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
}
Questo codice si basa sulla libreria client di Java Business Communications.

Python


"""This code deletes a brand.

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

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

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

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

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

client = BusinesscommunicationsV1(credentials=credentials)

agents_service = BusinesscommunicationsV1.BrandsAgentsService(client)

brand_name = 'brands/' + BRAND_ID

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

print(agent)

Per informazioni su formattazione e opzioni dei valori, consulta brands.delete.

Passaggi successivi

Ora che hai un agente, puoi procedere nel seguente modo: