Agents zum Verwalten von Marken erstellen

Nachdem Sie sich als Partner registriert haben, können Sie Unterhaltungen für Marken aktivieren, die Sie verwalten, indem Sie Business Messages-Agents für sie erstellen.

Ein Agent ist eine dialogorientierte Entität, mit der Nutzer interagieren. Sie erstellen einen Agent für jede von Ihnen verwaltete Marke. Sie erstellen und verwalten Agents mit der Business Communications API und steuern die Nachrichtenfunktion für Ihre Agents mit der Business Messages API.

Ein Agent umfasst die Geschäftsfunktionen einer Marke, z. B. den Onlinesupport und die physischen Standorte (falls vorhanden). Jede Nachricht enthält den Kontext, über den der Nutzer die Unterhaltung initiiert hat. Ihre Infrastruktur für die Nachrichtenweiterleitung kann erkennen, ob der Nutzer einen bestimmten Unternehmensstandort aufgerufen oder allgemeine Supportinformationen gesucht hat, und Nachrichten an das richtige Ziel weiterleiten.

Die Beziehung zwischen Agent und Marke

Wenn Sie beispielsweise die Marke Growing Tree Bank verwalten, die eine Website und zwei Standorte hat, erstellen Sie einen einzelnen Agent namens „Growing Tree Bank“. Nutzer können über allgemeine oder standortbasierte Suchanfragen auf den Agent stoßen. Der Kontext, in dem der Nutzer den Agent gefunden hat, wird mit jeder Nachricht an den Webhook übergeben. Sie verwenden diesen Kontext, um die Nachricht entweder an die Mitarbeiter an einem Standort oder an das Website-Supportteam weiterzuleiten, das eine Antwort erstellt und die Unterhaltung mit dem Nutzer fortsetzt.

Erwartungen

Bevor Sie einen Agent erstellen, sollten Sie sich mit den Erwartungen an Agents in Business Messages vertraut machen.

  • Kundenservicemitarbeiter sollten die unter Konversationsdesign für Business Messages beschriebenen Richtlinien beachten.
  • Agents sollten menschliche Ansprechpartner zur Verfügung haben, die Fragen beantworten können, wenn die Automatisierung eine Anfrage nicht ausführen kann oder von Nutzern angefordert wird.

  • Kundenservicemitarbeiter sollten eine Kundenzufriedenheitsbewertung von mindestens 80 % und eine Händlerantwortrate von mindestens 95% aufrechterhalten, wie unter Messwerte beschrieben.

Agent erstellen

Zum Erstellen eines Agents müssen Sie Informationen zur Marke und dazu, wie der Agent Nutzern angezeigt werden soll, erfassen und senden.

Wenn Sie mehrere Marken verwalten, wiederholen Sie die Schritte, um für jede Marke einen Agent zu erstellen.

Voraussetzungen

Bevor Sie Agents für von Ihnen verwaltete Marken erstellen, benötigen Sie einige Informationen:

Entwicklungsumgebung

Informationen zu Ihrer Entwicklungsumgebung.

Markendetails

Informationen zu der Marke, die der Agent repräsentiert.

  • Name der Marke
  • Markenwebsite
  • Kontaktoptionen auf der Website (wie in OPTION definiert)
  • Telefonnummer für Nutzer
  • Telefonnummern für die Anrufweiterleitung aktiviert

Agent-Darstellung und Richtlinien

Informationen dazu, wie der Agent den Nutzern angezeigt wird und wie er funktioniert.

  • Agent-Name, wie er in Unterhaltungen mit Nutzern erscheinen soll
  • Datenschutzerklärung als öffentlich verfügbare URL, die mit „https://“ beginnt
  • (Empfohlen) Agent-Logo (1.024 × 1.024 Pixel), als öffentlich verfügbare URL

    In einer Unterhaltung werden Logos als Kreise mit einem Durchmesser von 1.024 Pixeln angezeigt. Ihr Logo muss als Kreis angezeigt werden.

  • (Optional) Benutzerdefinierte Agent-ID, die die Marke in Nachrichten identifiziert, die der Webhook erhält

Interaktion mit dem Kundenservicemitarbeiter

Informationen dazu, wie der Agent mit Nutzern interagiert.

  • Die Sprache, in der der Agent normalerweise arbeitet, angegeben durch einen zweistelligen ISO 639-1-Sprachcode

  • Willkommensnachricht für Kundenservicemitarbeiter

    Was sagt der Agent zur Begrüßung der Nutzer?

  • Gesprächseinstiege für Kundenservicemitarbeiter

    Eine Liste von Vorschlägen in Form von Konversations-Chips (wie unter SuggestedReply definiert) für den Nutzer zur Interaktion mit dem Agent

    • Text, der dem Nutzer im Chip angezeigt wird
    • Postback-Daten, der String, der in der Nachrichtennutzlast an den Webhook zurückgesendet wird, wenn der Nutzer auf den Chip tippt
  • Automatisierte Zeiten und Livechat-Zeiten

    • Tägliche Startzeit als TimeOfDay-Objekt

      Beispiel: 8:15 Uhr ist

      {
        "hours": 8,
        "minutes": 15,
      }
      
    • Tägliche Endzeit als TimeOfDay-Objekt

      Beispiel: 19:30 Uhr ist

      {
        "hours": 19,
        "minutes": 30,
      }
      
    • Starttag – der erste Tag der Woche, an dem der Agent für den Chat verfügbar ist (wie in DayOfWeek definiert)

    • Endtag: der letzte Tag der Woche, an dem der Agent für einen Chat verfügbar ist (wie in DayOfWeek definiert)

    • Zeitzone, in der der Agent arbeitet (wie in der IANA Time Zone Database definiert, z. B. „America/Los_Angeles“)

Einstiegspunkte für Kundenservicemitarbeiter

Informationen darüber, wo Nutzer Unterhaltungen mit dem Agent starten können.

  • Zulässige Agent-Einstiegspunkte, an denen Nutzer Unterhaltungen mit Agents starten können (NON_LOCAL und/oder LOCATION)

Informationen zu NON_LOCAL-Einstiegspunkten (gilt nicht für den Google Ads-Einstiegspunkt)

  • Zulässige Regionen (als CLDR-Regionscodes), um den regionalen Zugriff auf NON_LOCAL-Einstiegspunkte zu beschränken.

    Unabhängig von der Region kann einem Agent nur eine Telefonnummer zugeordnet werden. Wenn Sie je nach Region eine andere Telefonnummer benötigen, muss für jede Region ein anderer Agent erstellt werden.

    Verwenden Sie 001 als World-Regionscode, um NON_LOCAL-Einstiegspunkte in allen verfügbaren Regionen zu aktivieren.

oauth2l installieren und testen

Alle curl-Anforderungen in der Dokumentation dieser Website verwenden oauth2l zur Authentifizierung. Wenn Sie die Verbindung zu den Business Communications und Business Messages APIs über die Befehlszeile herstellen möchten, installieren Sie oauth2l.

Um oauth2l mit Python 3 zu installieren,

  1. Laden Sie oauth2l herunter.

  2. Ändern Sie das Verzeichnis in "./oauth2l/python".

  3. Installieren Sie oauth2l mit dem folgenden Befehl.

    sudo python setup.sh build && sudo python setup.py install
    
  4. Testen Sie, ob oauth2l ein Autorisierungstoken generieren kann.

    oauth2l header --json resources/bm-agent-service-account-credentials.json businesscommunications
    
  5. Prüfen Sie, ob die Ausgabe ein Autorisierungstoken im folgenden Format erstellt:

    Authorization: Bearer AUTHORIZATION_BEARER_TOKEN
    

Es gibt andere Möglichkeiten, oauth2l für verschiedene Betriebssysteme zu installieren. Unabhängig von der Installationsmethode muss ein Autorisierungstoken basierend auf den JSON-Anmeldedaten des Dienstkontos generiert werden, bevor Sie fortfahren.

Agent erstellen

Nachdem Sie alle Informationen zusammengestellt haben, können Sie den Agent erstellen.

  1. Erstellen Sie die Marke, die der Agent repräsentiert. Wenn die Marke bereits vorhanden ist, rufen Sie die name der Marke ab und fahren Sie mit dem nächsten Schritt fort.

    Führen Sie in einem Terminal den folgenden Befehl aus:

    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();
        }
      }
    }
    
    Dieser Code basiert auf der Java Business Communications-Clientbibliothek.

    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)
    

    Speichert den name-Wert, den die API zurückgibt. Sie benötigen ihn, um Aktualisierungen vorzunehmen oder Agents zu erstellen.

    Informationen zum Aktualisieren oder Suchen von Marken finden Sie unter brands.

  2. Erstellen Sie den Agent. Ersetzen Sie BRAND_ID durch den Teil des name-Werts der Marke, der auf „brands/“ folgt. Wenn name beispielsweise „brands/12345“ ist, ist die Marken-ID „12345“.

    Führen Sie in einem Terminal den folgenden Befehl aus:

    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();
        }
      }
    }
    
    Dieser Code basiert auf der Java Business Communications-Clientbibliothek.

    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)
    

    Informationen zu Formatierungs- und Wertoptionen finden Sie unter brands.agents.

  3. Wenn die Marke Standorte hat, die Sie mit dem Agent verknüpfen möchten, finden Sie weitere Informationen unter Standorte hinzufügen.

Beispiel: Agent für die Growing Tree Bank erstellen

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

Wichtige Informationen speichern

Wenn Sie einen Agent erstellen, gibt die Business Communications API die Werte des Agents zurück, einschließlich name und testUrls.

Webhook auf Agent-Ebene festlegen

Sie erhalten Nachrichten, die an Ihren Agent gesendet werden, an Ihrem Webhook. Wenn Sie möchten, dass Nachrichten für einen bestimmten Agent stattdessen an einem anderen Webhook ankommen, können Sie einen Webhook auf Agent-Ebene festlegen.

Verwenden Sie zum Festlegen eines Webhooks auf Agent-Ebene die Entwicklerkonsole.

Agent testen

Jeder Agent hat Test-URLs, mit denen Sie sehen können, wie eine Unterhaltung mit diesem Agent für Nutzer aussieht. Außerdem haben Sie die Möglichkeit, Ihre Messaging-Infrastruktur zu prüfen.

Eine TestUrl hat die Attribute url und surface. Verwenden Sie zum Testen mit einem iOS-Gerät die Test-URL mit dem Oberflächenwert SURFACE_IOS_MAPS. Wenn Sie die URL auf einem iOS-Gerät öffnen, auf dem die Google Maps App installiert ist, wird eine voll funktionsfähige Unterhaltung mit dem Agent geöffnet.

Android-Geräte haben zwei Test-URLs. URLs mit dem surface-Wert SURFACE_ANDROID_MAPS offene Unterhaltungen in Google Maps und stellen dialogorientierte Einstiegspunkte in Google Maps dar. URLs mit dem surface-Wert SURFACE_ANDROID_WEB öffnen Unterhaltungen in einer Overlay-Konversationsansicht und stellen alle anderen Einstiegspunkte dar.

Sobald eine Unterhaltungsoberfläche geöffnet ist, enthält die Unterhaltung alle Branding-Informationen, die Nutzer sehen würden. Wenn Sie eine Nachricht an den Agent senden, empfängt Ihr Webhook die Nachricht, einschließlich der vollständigen JSON-Nutzlast, die Sie bei der Kommunikation mit Nutzern erwarten können.

Tippen Sie zum Öffnen der Test-URL eines Agents auf einen Link oder verwenden Sie den Business Messages Agent Launcher auf einem Mobilgerät.

Agent-Informationen abrufen

Wenn Sie Informationen zu einem Agent wie agentTestUrl abrufen möchten, können Sie die Informationen aus der Business Communications API abrufen, sofern Sie den name-Wert des Agents haben.

Informationen zu einem einzelnen Agent abrufen

Führen Sie den folgenden Befehl aus, um Agent-Informationen abzurufen. Ersetzen Sie BRAND_ID und AGENT_ID durch die eindeutigen Werte aus der name des Agents.

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();
    }
  }
}
Dieser Code basiert auf der Java Business Communications-Clientbibliothek.

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)

Alle Agents für eine Marke auflisten

Wenn Sie die name des Agents nicht kennen, können Sie Informationen zu allen Agents abrufen, die mit einer Marke verknüpft sind. Dazu lassen Sie den Wert AGENT_ID aus einer GET-Anfrage-URL weg.

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();
    }
  }
}
Dieser Code basiert auf der Java Business Communications-Clientbibliothek.

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)

Agent-Informationen aktualisieren

Wenn Sie einen Agent aktualisieren möchten, führen Sie eine PATCH-Anfrage mit der Business Communications API aus. Dabei fügen Sie die Namen der Felder, die Sie bearbeiten, als Werte für den URL-Parameter „updateMask“ hinzu.

Wenn Sie beispielsweise die Felder displayName und customAgentId aktualisieren, lautet der URL-Parameter „updateMask“ „updateMask=displayName,businessMessagesAgent.customAgentId“.

Informationen zu Formatierungs- und Wertoptionen finden Sie unter brands.agents.patch.

Wenn Sie den name eines Agents nicht kennen, lesen Sie Alle Agents für eine Marke auflisten.

Nachdem Sie einen Agent verifiziert haben, können Sie nur die folgenden Felder aktualisieren:

  • conversationalSetting

  • customAgentId

  • defaultLocale

  • primaryAgentInteraction

  • additionalAgentInteractions

  • phone

Wenn Sie nach der Bestätigung des Agents weitere Felder aktualisieren müssen, setzen Sie sich mit uns in Verbindung. Sie müssen sich zuerst mit einem Google-Konto für Business Messages anmelden. Informationen zur Registrierung für ein Konto finden Sie unter Mit Business Messages registrieren.)

Beispiel: Anzeigenamen aktualisieren

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();
Dieser Code basiert auf der Node.js-Business Communications-Clientbibliothek.

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();
    }
  }
}
Dieser Code basiert auf der Java Business Communications-Clientbibliothek.

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)
Dieser Code basiert auf der Python Business Communications-Clientbibliothek.

Beispiel: Einstiegspunktgruppen NON_LOCAL und LOCATION angeben

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();
Dieser Code basiert auf der Node.js-Business Communications-Clientbibliothek.

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();
    }
  }
}
Dieser Code basiert auf der Java Business Communications-Clientbibliothek.

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)
Dieser Code basiert auf der Python Business Communications-Clientbibliothek.

Beispiel: Willkommensnachricht aktualisieren

Wenn Sie ein Feld in conversationalSettings aktualisieren, z. B. welcomeMessage, müssen Sie alle Felder im Objekt aktualisieren. Außerdem müssen Sie die Sprache der Einstellungen als zweistelligen ISO 639-1-Sprachcode angeben.

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();
Dieser Code basiert auf der Node.js-Business Communications-Clientbibliothek.

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();
    }
  }
}
Dieser Code basiert auf der Java Business Communications-Clientbibliothek.

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)
Dieser Code basiert auf der Python Business Communications-Clientbibliothek.

Agent löschen

Wenn Sie einen Agent löschen, löscht Business Messages alle Agent-Daten. Business Messages löscht keine von Ihrem Agent gesendeten Nachrichten, die sich auf dem Gerät eines Nutzers übertragen oder dort gespeichert sind. Nachrichten an Nutzer sind keine Agent-Daten.

Löschanfragen schlagen fehl, wenn dem Agent ein Standort zugeordnet ist oder wenn Sie mindestens einmal versucht haben, den Agent zu bestätigen. Informationen zum Aktualisieren von Standorten finden Sie unter Standorte hinzufügen.

Sie können einen verifizierten Agent nicht löschen. Wenn Sie einen Agent löschen möchten, den Sie bestätigt haben oder den Sie bestätigen wollten, setzen Sie sich mit uns in Verbindung. Sie müssen sich zuerst mit einem Google-Konto für Business Messages anmelden. Informationen zur Registrierung für ein Konto finden Sie unter Mit Business Messages registrieren.)

Führen Sie den folgenden Befehl aus, um einen Agent zu löschen. Ersetzen Sie BRAND_ID und AGENT_ID durch die eindeutigen Werte aus der name des Agents.

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();
    }
  }
}
Dieser Code basiert auf der Java Business Communications-Clientbibliothek.

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)

Informationen zu Formatierungs- und Wertoptionen finden Sie unter brands.agents.delete.

Marke löschen

Wenn Sie eine Marke löschen, führen Sie eine DELETE-Anfrage über die Business Communications API aus. Löschanfragen schlagen fehl, wenn ein oder mehrere Agents oder Standorte mit der Marke verknüpft sind, auch wenn diese Agents zu einem anderen Produkt gehören.

Führen Sie den folgenden Befehl aus, um eine Marke zu löschen. Ersetzen Sie BRAND_ID durch den eindeutigen Wert aus name der Marke.

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();
    }
  }
}
Dieser Code basiert auf der Java Business Communications-Clientbibliothek.

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)

Informationen zu Formatierungs- und Wertoptionen finden Sie unter brands.delete.

Nächste Schritte

Nachdem Sie einen Agent erstellt haben, können Sie die folgenden Schritte ausführen: