Create agents to manage brands

After you register as a partner, you can enable conversations for brands you manage by creating Business Messages agents for them.

An agent is a conversational entity that users interact with. You create one agent for each brand you manage. You create and manage agents with the Business Communications API, and you control messaging for your agents with the Business Messages API.

An agent encompasses a brand's business functions, such as online support, and physical locations (if any). Each message contains the context from which the user initiated the conversation. Your message routing infrastructure can detect if the user viewed a specific business location or looked for general support, and it can route messages to the correct destination.

The agent/brand relationship

For example, if you manage the Growing Tree Bank brand, which has a website and two locations, you create a single "Growing Tree Bank" agent. Users can encounter the agent through general or location-based searches, and the context in which the user found the agent is passed along with each message to your webhook. You use that context to route the message either to staff at a location or to the website support team, who create a response and continue the conversation with the user.

Expectations

Before you create an agent, understand the expectations of agents on Business Messages.

  • Agents should follow the design guidance outlined in Conversation design for Business Messages.
  • Agents should have human representatives available to answer questions when automation is unable to fulfill a request or when requested by users.

  • Agents should maintain a customer satisfaction rating (CSAT) of at least 80% and a merchant response rate (MRR) of at least 95% as outlined in Metrics.

Create an agent

To create an agent, you need to gather and submit information about the brand and how you want the agent to appear to users.

If you manage multiple brands, repeat the steps to create an agent for each brand.

Prerequisites

Before you create agents for brands you manage, you need to gather some information:

Development environment

Information about your development environment.

Brand details

Information about the brand the agent represents.

  • Brand name
  • Brand website
  • Contact options on website (as defined in OPTION)
  • Consumer-facing phone number
  • Phone numbers enabled for call deflection

Agent appearance and policies

Information about how the agent appears to users and how it operates.

  • Agent name, as you want it to appear in conversations with users
  • Privacy policy, as a publicly available URL starting with "https://"
  • (Recommended) Agent logo (1024x1024 px), as a publicly available URL

    In a conversation, logos display as 1024 px diameter circles. Make sure that your logo displays well as a circle.

  • (Optional) Custom Agent ID, which identifies the brand in messages the webhook receives

Agent interaction

Information about how your agent interacts with users.

  • The locale that your agent typically operates in, specified by a two-character ISO 639-1 language code

  • Agent welcome message

    What does the agent say to greet users?

  • Agent conversation starters

    A list of suggestions, in the form of conversation chips (as defined in SuggestedReply), for the user to engage with the agent

    • Text displayed to the user in the chip
    • Postback data, the string sent back to your webhook in the message payload if the user taps the chip
  • Automated and live chat times

    • Daily start time, as a TimeOfDay object

      For example, 8:15 AM is

      {
        "hours": 8,
        "minutes": 15,
      }
      
    • Daily end time, as a TimeOfDay object

      For example, 7:30 PM is

      {
        "hours": 19,
        "minutes": 30,
      }
      
    • Start day, the first day of the week the agent is available for chat (as defined in DayOfWeek)

    • End day, the last day of the week the agent is available for chat (as defined in DayOfWeek)

    • Time zone the agent operates in (as defined in the IANA Time Zone Database, for example "America/Los_Angeles")

Agent entry points

Information about where users can start conversations with the agent.

  • Allowed agent entry points, where users can start conversations with agents (NON_LOCAL and/or LOCATION)

Information about NON_LOCAL entry points (does not apply to the Google Ads entry point).

  • Allowed regions (as CLDR region codes), to restrict regional access to NON_LOCAL entry points.

    Regardless of region, an agent can only have one phone number associated with it. If you need a different phone number based on region, a different agent must be created for each region.

    To enable NON_LOCAL entry points in all available regions, use 001 for the World region code.

Install and test oauth2l

All curl requests in this site's documentation use oauth2l for authentication. If you want to use the command line to connect with the Business Communications and Business Messages APIs, install the oauth2l.

To install oauth2l with Python 3,

  1. Download oauth2l.

  2. Change the directory to "./oauth2l/python".

  3. Install oauth2l with the following command.

    sudo python setup.sh build && sudo python setup.py install
    
  4. Test that oauth2l can generate an authorization token.

    oauth2l header --json resources/bm-agent-service-account-credentials.json businesscommunications
    
  5. Verify that the output creates an authorization token of the form:

    Authorization: Bearer AUTHORIZATION_BEARER_TOKEN
    

There are other ways to install oauth2l for different operating systems. Regardless of your installation method, ensure that you can generate an authorization token based on the service account JSON credentials before proceeding.

Create the agent

Once you've gathered your information, it's time to create your agent.

  1. Create the brand that the agent represents. If the brand already exists, get the brand's name and skip to the next step.

    In a terminal, run the following command:

    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();
        }
      }
    }
    
    This code is based on the Java Business Communications client library.

    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)
    

    Store the name value that the API returns. You'll need it to make updates or create agents.

    To update or look up brands, see brands.

  2. Create the agent. Replace BRAND_ID with the part of the brand's name value that follows "brands/". For example, if name is "brands/12345", the brand ID is "12345".

    In a terminal, run the following command:

    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();
        }
      }
    }
    
    This code is based on the Java Business Communications client library.

    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)
    

    For formatting and value options, see brands.agents.

  3. If the brand has locations that you want to associate with your agent, see Add locations.

Example: Create an agent for 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',
                        },
                    ],
                },
            },
        },
    },
}"

Store important information

When you create an agent, the Business Communications API returns your agent's values, including name and testUrls.

Set an agent-level webhook

You receive messages sent to your agent at your webhook. If you want messages for a specific agent to arrive at a different webhook instead, you can set an agent-level webhook.

To set an agent-level webhook, use the Developer Console.

Test an agent

Each agent has test URLs that let you see how a conversation with that agent appears to users and give you the opportunity to verify your messaging infrastructure.

A TestUrl has url and surface attributes. To test with an iOS device, use the test URL with a surface value of SURFACE_IOS_MAPS. Opening the URL on an iOS device that has Google Maps app installed opens a fully functional conversation with the agent.

Android devices have two test URLs. URLs with a surface value of SURFACE_ANDROID_MAPS open conversations in Google Maps and represent conversational entry points that appear in Google Maps. URLs with a surface value of SURFACE_ANDROID_WEB open conversations in an overlay conversational view and represent all other entry points.

Once a conversational surface opens, the conversation includes all the branding information that users would see, and when you send a message to the agent, your webhook receives the message, including the full JSON payload you can expect when communicating with users.

To open an agent's test URL, tap a link or use the Business Messages Agent Launcher on a mobile device.

Get agent information

To get information about an agent, such as the agentTestUrl, you can get the information from the Business Communications API, as long as you have the agent's name value.

Get info for a single agent

To get agent information, run the following command. Replace BRAND_ID and AGENT_ID with the unique values from the agent's name.

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();
    }
  }
}
This code is based on the Java Business Communications client library.

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)

List all agents for a brand

If you don't know the agent's name, you can get information for all agents associated with a brand by omitting the AGENT_ID value from a GET request URL.

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();
    }
  }
}
This code is based on the Java Business Communications client library.

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)

Update agent information

To update an agent, you perform a PATCH request with the Business Communications API. When you make the API call, you include the names of the fields you're editing as values for the "updateMask" URL parameter.

For example, if you update the displayName and customAgentId fields, the "updateMask" URL parameter is "updateMask=displayName,businessMessagesAgent.customAgentId".

For formatting and value options, see brands.agents.patch.

If you don't know an agent's name, see List all agents for a brand.

After you verify an agent, you can only update the following fields:

  • conversationalSetting

  • customAgentId

  • defaultLocale

  • primaryAgentInteraction

  • additionalAgentInteractions

  • phone

If you need to update other fields after you verify your agent, contact us. (You must first sign in with a Business Messages Google account. To register for an account, see Register with Business Messages.)

Example: Update display name

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();
This code is based on the Node.js Business Communications client library.

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();
    }
  }
}
This code is based on the Java Business Communications client library.

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)
This code is based on the Python Business Communications client library.

Example: Specify NON_LOCAL and LOCATION entry point groups

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();
This code is based on the Node.js Business Communications client library.

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();
    }
  }
}
This code is based on the Java Business Communications client library.

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)
This code is based on the Python Business Communications client library.

Example: Update welcome message

If you update any field within conversationalSettings—such as welcomeMessage— you must update all fields within the object, and you must specify the locale of the settings (as a two-character ISO 639-1 language code).

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();
This code is based on the Node.js Business Communications client library.

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();
    }
  }
}
This code is based on the Java Business Communications client library.

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)
This code is based on the Python Business Communications client library.

Delete an agent

When you delete an agent, Business Messages deletes all agent data. Business Messages doesn't delete messages sent by your agent that are in transit to or stored on a user's device. Messages to users aren't agent data.

Delete requests fail if the agent has an associated location or if you've attempted to verify the agent one or more times. To update locations, see Add locations.

You cannot delete an agent that is verified. To delete an agent that you've verified or attempted to verify, contact us. (You must first sign in with a Business Messages Google account. To register for an account, see Register with Business Messages.)

To delete an agent, run the following command. Replace BRAND_ID and AGENT_ID with the unique values from the agent's name.

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();
    }
  }
}
This code is based on the Java Business Communications client library.

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)

For formatting and value options, see brands.agents.delete.

Delete a brand

When you delete a brand, you perform a DELETE request with the Business Communications API. Delete requests fail if you have one or more agents or locations associated with the brand, even if those agents belong to a different product.

To delete a brand, run the following command. Replace BRAND_ID with the unique value from the brand's name.

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();
    }
  }
}
This code is based on the Java Business Communications client library.

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)

For formatting and value options, see brands.delete.

Next steps

Now that you have an agent, you can take the following steps: