Administrar los agentes

Un agente de RCS para empresas es la entidad conversacional que representa tu marca y que interactúa con los usuarios. Puedes usar la API de RBM Management para crear agentes, enviarlos para su verificación y lanzamiento, y administrar su ciclo de vida general. Dado que cada agente debe pertenecer a una marca propietaria, debes crear una marca antes de crear un agente.

Los fragmentos de código de esta página se tomaron de las muestras de Java y las muestras de Node.js.

Creación y definición de agentes

Crea un agente

Para crear un agente de RBM, debes definir su información básica.

Si deseas obtener más información, consulta brands.agents.create.

cURL

curl -v -X POST "https://businesscommunications.googleapis.com/v1/$BRAND_ID/agents" \
  -H "Content-Type: application/json" \
  -H "User-Agent: curl/business-messaging" \
  -H "`oauth2l header --json rbm-developer-service-account-credentials.json businesscommunications`" \
  -d "{
    'displayName': 'My test agent',
    'rcsBusinessMessagingAgent': {
      'description': 'My agent description',
      'logoUri': 'https://agent-logos.storage.googleapis.com/_/kt90w53vzw2QSxK6PG1uCeJf',
      'heroUri': 'https://agent-logos.storage.googleapis.com/_/kt90vzob74GQcfeHoEQbVRTP',
      'phoneNumbers': [
        {
            'phoneNumber': {
                'number': '+44800088088'
            },
            'label': 'My number'
        }
      ],
      'emails': [
        {
            'address': 'support@demo.test',
            'label': 'My email'
        }
      ],
      'websites': [
        {
            'uri': 'https://a.demo.test/',
            'label': 'My site'
        }
      ],
      'privacy': {
        'uri': 'https://a.demo.test/privacy',
        'label': 'My privacy policy'
      },
      'termsConditions': {
        'uri': 'https://a.demo.test/terms',
        'label': 'My terms'
      },
      'color': '#FFFFFF',
      'billingConfig': {
        'billingCategory': 'CONVERSATIONAL'
      },
      'agentUseCase': 'TRANSACTIONAL',
      'hostingRegion': 'EUROPE'
    }
  }"
Este código es un fragmento de nuestra muestra de la API de RBM Management.

Node.js

const businessCommunicationsApiHelper =
  require('@google/rbm-businesscommunications');

const privateKey =
  require('../../resources/businesscommunications-service-account-credentials.json');

businessCommunicationsApiHelper.initBusinessCommunucationsApi(privateKey);

const newAgentDetails = {
  displayName: 'My new agent',
  name: brandId + '/agents/',
  rcsBusinessMessagingAgent: {
    description: 'This is the agent description that will be displayed in the Agent info tab in Messages',
    logoUri: 'https://agent-logos.storage.googleapis.com/_/kt90w53vzw2QSxK6PG1uCeJf',
    heroUri: 'https://agent-logos.storage.googleapis.com/_/kt90vzob74GQcfeHoEQbVRTP',
    phoneNumbers: [
      {
        phoneNumber: {
          number: '+12223334444'
        },
        label: 'Call support'
      }
    ],
    // It's recommended to provide at least one contact method (phone or email) because
    // this is required for launch. For any phone, email, or website provided, a corresponding label
    // must also be included.
    privacy: {
      "uri": 'https://policies.google.com/privacy',
      "label": 'Our privacy policy'
    },
    termsConditions: {
      "uri": 'https://policies.google.com/terms',
      "label": 'Our Terms and Conditions'
    },
    color: '#0B78D0',
    billingConfig: { billingCategory: 'NON_CONVERSATIONAL' },
    agentUseCase: 'TRANSACTIONAL',
    hostingRegion: 'EUROPE'
  }
};

businessCommunicationsApiHelper.createAgent(brandId, newAgentDetails).then((response) => {

}).catch((err) => {
  console.log(err);
});

Java

Brand brand = api.getBrand(brandId);
logger.info("Brand to operate on: " + brand);
String displayName = flags.getOrDefault("agent_name", "Test RBM Agent: " + now.getSecond());
String suffix = flags.getOrDefault("agent_data_suffix", "API");
RcsBusinessMessagingAgent agentData = AgentFactory.createRbmAgent(suffix);
Agent agent = api.createRbmAgent(brand, displayName, agentData);
logger.info("RBM agent has been created: " + agent);

Este código devuelve la información del agente nuevo y un identificador único asignado al agente:

{
  name: 'brands/40bd963f-ff92-425c-b273-8f0892d2d017/agents/my_new_agent_dxuewtvy_agent',
  displayName: 'My new agent',
  rcsBusinessMessagingAgent: {
    description: 'This is the agent description that will be displayed in the Agent info tab in Messages',
    logoUri: 'https://agent-logos.storage.googleapis.com/_/kt90w53vzw2QSxK6PG1uCeJf',
    heroUri: 'https://agent-logos.storage.googleapis.com/_/kt90vzob74GQcfeHoEQbVRTP',
    phoneNumbers: [ [Object] ],
    privacy: {
      uri: 'https://policies.google.com/privacy',
      label: 'Our privacy policy'
    },
    termsConditions: {
      uri: 'https://policies.google.com/terms',
      label: 'Our Terms and Conditions'
    },
    color: '#0B78D0',
    billingConfig: { billingCategory: 'NON_CONVERSATIONAL' },
    agentUseCase: 'MULTI_USE',
    hostingRegion: 'EUROPE'
  }
}

Cómo buscar la definición de un agente

Puedes recuperar un agente especificando su identificador único (name). Para obtener más detalles, consulta brands.agents.list.

Node.js

const businessCommunicationsApiHelper =
  require('@google/rbm-businesscommunications');

const privateKey =
  require('../../resources/businesscommunications-service-account-credentials.json');

businessCommunicationsApiHelper.initBusinessCommunucationsApi(privateKey);

// Retrieve details of the first agent (if one has already been created)
businessCommunicationsApiHelper.getAgent(agent.name).then((response) => {

}).catch((err) => {
  console.log(err);
});

Java

Agent agent = api.getAgent(flags.get("agent_id"));
logger.info("Agent: " + agent);

Este código devuelve la información del agente:

{
  name: 'brands/40bd963f-ff92-425c-b273-8f0892d2d017/agents/my_new_agent_dxuewtvy_agent',
  displayName: 'My new agent',
  rcsBusinessMessagingAgent: {
    description: 'This is the agent description that will be displayed in the Agent info tab in Messages',
    logoUri: 'https://agent-logos.storage.googleapis.com/_/kt90w53vzw2QSxK6PG1uCeJf',
    heroUri: 'https://agent-logos.storage.googleapis.com/_/kt90vzob74GQcfeHoEQbVRTP',
    phoneNumbers: [ [Object] ],
    privacy: {
      uri: 'https://policies.google.com/privacy',
      label: 'Our privacy policy'
    },
    termsConditions: {
      uri: 'https://policies.google.com/terms',
      label: 'Our Terms and Conditions'
    },
    color: '#0B78D0',
    billingConfig: { billingCategory: 'NON_CONVERSATIONAL' },
    agentUseCase: 'MULTI_USE',
    hostingRegion: 'EUROPE'
  }
}

Verificación y lanzamiento

Envía la información de verificación

Se requiere la verificación de marca para lanzar el agente. Debes enviar información de verificación antes de realizar una solicitud de lanzamiento. Ten en cuenta que no es necesario que esperes la aprobación de la marca antes de realizar la solicitud de lanzamiento. La aprobación de la marca se realiza como parte del proceso de aprobación del lanzamiento. En el caso de ciertos operadores, también debes proporcionar un token de verificación válido emitido por una autoridad de verificación.

Si deseas obtener más información, consulta brands.agents.requestVerification.

cURL

curl -v "https://businesscommunications.googleapis.com/v1/brands/$BRAND_ID/agents/$AGENT_ID:requestVerification" \
-H "Content-Type: application/json" \
-H "x-http-method-override: POST" \
-H "User-Agent: curl/business-messaging" \
-H "$(oauth2l header --json PATH_TO_SERVICE_ACCOUNT_KEY businesscommunications)" \
-d "{
  'agentVerificationContact': {
     ...
   },
   'agentVerificationToken':
     {'tokenBase64Encoded': '$TOKEN'}
}"

Node.js

const businessCommunicationsApiHelper =
  require('@google/rbm-businesscommunications');

const privateKey =
  require('../../resources/businesscommunications-service-account-credentials.json');

businessCommunicationsApiHelper.initBusinessCommunucationsApi(privateKey);

let agentVerificationContact = {
  partnerName: 'Alice',
  partnerEmailAddress: 'alice@thepartner.com',
  brandContactName: 'Bob',
  brandContactEmailAddress: 'bob@thebrand.com',
  brandWebsiteUrl: 'https://thebrand.com/'
};

businessCommunicationsApiHelper.verifyAgent(agent.name, agentVerificationContact).then((response) => {

}).catch((err) => {
  console.log(err);
});

Java

AgentVerificationContact contact = AgentFactory.createRbmAgentVerification();
AgentVerification verification = api.requestAgentVerification(agent.getName(), contact);
logger.info("Verification requested: " + verification);

Este código devuelve la información de verificación:

{
  "name": "brands/40bd963f-ff92-425c-b273-8f0892d2d017/agents/my_new_agent_ciymyd2b_agent",
  "verificationState": "VERIFICATION_STATE_UNVERIFIED",
  "agentVerificationContact": {
    "partnerName": "Alice",
    "partnerEmailAddress": "alice@thepartner.com",
    "brandContactName": "Bob",
    "brandContactEmailAddress": "bob@thebrand.com",
    "brandWebsiteUrl": "https://thebrand.com/"
  },
  "agentVerificationTokens": [
    {
      "verificationAuthorityDisplayName": "Example Verification Authority",
      "expirationTime": "2027-06-16T13:45:14Z",
      "status": "ACTIVE",
      "countryCode": "US",
      "tokenBase64Encoded": "...",
      "certificateChainUri": "https://rbm.goog/certificates?v=5&kid=6CAE185529AABAC216565E99A8DE22504B086209"
    }
  ]
}

Cómo consultar la información de verificación de un agente

Puedes recuperar el estado de la verificación de la marca de un agente. Para obtener más información, consulta brands.agents.getVerification.

Node.js

const businessCommunicationsApiHelper =
  require('@google/rbm-businesscommunications');

const privateKey =
  require('../../resources/businesscommunications-service-account-credentials.json');

businessCommunicationsApiHelper.initBusinessCommunucationsApi(privateKey);

businessCommunicationsApiHelper.getAgentVerification(agent.name).then((response) => {

}).catch((err) => {
  console.log(err);
});

Java

AgentVerification verification = api.getAgentVerification(agent.getName());
logger.info("RBM agent verification: " + verification);

Este código devuelve el estado de verificación y la información del socio:

{
  "name": "brands/40bd963f-ff92-425c-b273-8f0892d2d017/agents/my_new_agent_ciymyd2b_agent/verification",
  "verificationState": "VERIFICATION_STATE_UNVERIFIED",
  "agentVerificationContact": {
    "partnerName": "John Doe",
    "partnerEmailAddress": "john.doe@gmail.com",
    "brandContactName": "Bob",
    "brandContactEmailAddress": "bob@brand.com",
    "brandWebsiteUrl": "https://www.brand.com"
  },
  "agentVerificationTokens": [
    {
      "verificationAuthorityDisplayName": "Example Verification Authority",
      "expirationTime": "2027-06-16T13:45:14Z",
      "status": "ACTIVE",
      "countryCode": "US",
      "tokenBase64Encoded": "...",
      "certificateChainUri": "https://rbm.goog/certificates?v=5&kid=6CAE185529AABAC216565E99A8DE22504B086209"
    }
  ]
}

Actualiza y borra tokens de verificación

Si ya lanzaste un agente, puedes actualizarlo con un token de verificación. Para agregar o actualizar un token, llama al método updateVerification (con una solicitud PATCH) y especifica la máscara de actualización agent_verification_tokens.

cURL

curl -v -X PATCH "https://businesscommunications.googleapis.com/v1/brands/$BRAND_ID/agents/$AGENT_ID/verification?updateMask=agent_verification_tokens" \
-H "Content-Type: application/json" \
-H "x-http-method-override: PATCH" \
-H "User-Agent: curl/business-messaging" \
-H "$(oauth2l header --json PATH_TO_SERVICE_ACCOUNT_KEY businesscommunications)" \
-d "{
   'agentVerificationTokens': [
     {'tokenBase64Encoded': '$TOKEN'}
   ]
}"

Si tu agente se lanza en varios países, es posible que debas especificar varios tokens (uno para cada país) emitidos por las autoridades de verificación aprobadas para esas regiones. Para especificar un token adicional, llama al método updateVerification y proporciona todos los tokens que desees asociar con el agente, incluidos los que ya están asociados con él.

Para borrar todos los tokens asociados con un agente, envía una lista vacía en tu solicitud de PATCH:

cURL

curl -v -X PATCH "https://businesscommunications.googleapis.com/v1/brands/$BRAND_ID/agents/$AGENT_ID/verification?updateMask=agent_verification_tokens" \
-H "Content-Type: application/json" \
-H "x-http-method-override: PATCH" \
-H "User-Agent: curl/business-messaging" \
-H "$(oauth2l header --json PATH_TO_SERVICE_ACCOUNT_KEY businesscommunications)" \
-d "{}"

Soluciona problemas relacionados con errores de tokens de verificación

Cuando administres tokens de verificación y solicites lanzamientos, es posible que se produzcan los siguientes errores:

  • Falta el token para el lanzamiento: Si solicitas un lanzamiento en un operador que requiere un token, pero el agente no tiene uno, recibirás un 400 error (por ejemplo, "Verification token matching agent <...> and carrier country US is missing").
  • Datos del agente que no coinciden: El ID, el nombre, el logotipo y el banner del agente en su perfil deben coincidir exactamente con los datos incorporados en el token. Si intentas adjuntar un token que no coincide o solicitas un lanzamiento con un token que no coincide, recibirás un 400 error (por ejemplo, "Agent ID mismatch. Request agent ID: <...>, Token agent ID: <...>").

Envía un agente para su lanzamiento

Puedes enviar un agente para su lanzamiento en uno o más operadores. Algunos lanzamientos son administrados por Google y otros, directamente por los operadores. Es posible que los lanzamientos administrados por el operador tengan requisitos adicionales. Consulta Lanzamientos administrados por Google y lanzamientos administrados por el operador para obtener más información.

Antes de lanzar un agente por primera vez, debes enviar información de verificación. Esto permite que Google, los operadores o ambos verifiquen con el contacto de tu marca que tienes autorización para administrar el agente en su nombre. Consulta la verificación de marca para obtener más detalles.

Una vez que envíes la información de verificación y completes los requisitos previos para el lanzamiento, podrás enviar una solicitud de lanzamiento.

Puedes enviar un agente para su lanzamiento en uno o más operadores. El cuestionario de lanzamiento completo debe proporcionarse como parte de la solicitud de lanzamiento. Para obtener más información, consulta brands.agents.requestLaunch.

cURL

curl -v -X POST "https://businesscommunications.googleapis.com/v1/$AGENT_ID:requestLaunch" \
  -H "Content-Type: application/json" \
  -H "User-Agent: curl/business-messaging" \
  -H "`oauth2l header --json rbm-developer-service-account-credentials.json businesscommunications`" \
  -d "{
    'agentLaunch': {
      'rcsBusinessMessaging': {
        'questionnaire': {
          'contacts': [
            {
              'name': 'John Doe',
              'title': 'Product Owner',
              'email': 'support@demo.test'
            }
          ],
          'optinDescription': 'Thanks for your request.',
          'triggerDescription': 'Promotional messages will be triggered in a timely manner.',
          'interactionsDescription': 'Promotional messages are one way.',
          'optoutDescription': 'Sorry to see you go.',
          'agentAccessInstructions': 'Thanks for your request.',
          'videoUris': [
            'https://d2q4iodazzzt8b.cloudfront.net/MicrosoftTeamsvideo2_1758533835.mp4'
          ],
          'screenshotUris': [
            'https://rm.virbm.com/Il9ChvVEhS1na5mr/ee9bc94b468a40688fb7fc71cb1c069c.png'
          ]
        },
        'launchDetails': {
          '/v1/regions/$CARRIER_ID': {}
        }
      }
    }
  }"
Este código es un fragmento de nuestra muestra de la API de RBM Management.

Node.js

const businessCommunicationsApiHelper =
  require('@google/rbm-businesscommunications');

const privateKey =
  require('../../resources/businesscommunications-service-account-credentials.json');

businessCommunicationsApiHelper.initBusinessCommunucationsApi(privateKey);
  
let agentLaunch = {
  questionnaire: {
    contacts: [
      {
        name: 'James Bond',
        title: 'Mr 0 0 7',
        email: 'someone@somewhere.com'
      }
    ],
    optinDescription: 'Users accepted our terms of service online.',
    triggerDescription: 'We are reaching preregistered users',
    interactionsDescription: 'This agent does not do much.',
    optoutDescription: 'Reply stop and we stop.',
    agentAccessInstructions: 'This is a a simple agent that reaches registered users.',
    videoUris: [
      'https://www.google.com/a/video'
    ],
    screenshotUris: [
      'https://www.google.com/a/screenshot'
    ]
  },
  launchDetails: {}
};

businessCommunicationsApiHelper.launchAgent(agent.name, agentLaunch).then((response) => {

}).catch((err) => {
  console.log(err);
});

Java

Optional<Questionnaire> q = Optional.of(AgentFactory.createRbmQuestionnaire());
AgentLaunch launch = api.requestRbmAgentLaunch(agent.getName(), regionIds, q);
logger.info("RBM agent updated launch: " + launch);

Este código devuelve la información de lanzamiento del agente:

{
  "name": "brands/40bd963f-ff92-425c-b273-8f0892d2d017/agents/my_new_agent_7jo0trhw_agent/launch",
  "rcsBusinessMessaging": {
    "questionnaire": {
      "contacts": [
        {
          "name": "James Bond",
          "title": "Mr O O 7",
          "email": "someone@somewhere.com"
        }
      ],
      "optinDescription": "Users accepted our terms of service online.",
      "triggerDescription": "We are reaching preregistered users",
      "interactionsDescription": "This agent does not do much.",
      "optoutDescription": "Reply stop and we stop.",
      "agentAccessInstructions": "This is a a simple agent that reaches registered users.",
      "videoUris": [
        "https://www.google.com/a/video"
      ],
      "screenshotUris": [
        "https://www.google.com/a/screenshot"
      ]
    },
    "launchDetails": {
      "/v1/regions/some-carrier": {
        "launchState": "LAUNCH_STATE_PENDING",
        "updateTime": "2023-02-24T15:02:13.903554Z"
      }
    },
    "launchRegion": "NORTH_AMERICA"
  }
}

Ten en cuenta que launchRegion dejó de estar disponible y se quitará pronto.

Lanza un agente en una o más regiones

Para lanzar un agente en una o más regiones cuando el agente no se lanzó antes, llama al método requestLaunch con un objeto que contenga un mapa de solo claves para todas las regiones en las que deseas lanzar el agente. El uso de un mapa vacío permite mantener la coherencia interna de la API en los objetos que se usan entre las llamadas a la API.

curl -X POST \
"https://businesscommunications.googleapis.com/v1/brands/BRAND_ID/agents/AGENT_ID:requestLaunch" \
-H "Content-Type: application/json" \
-H "$(oauth2l header --json PATH_TO_SERVICE_ACCOUNT_KEY businesscommunications)" \
-d "{
  'name': 'brands/BRAND_ID/agents/AGENT_ID/launch',
  'rcsBusinessMessaging': {
    'questionnaire': {
      'contacts': [
        {
          'name': 'Contact person 000',
          'title': 'Contact manager 000',
          'email': 'user@domain.com000'
        }
      ],
      'optinDescription': 'Opt-in description 0',
      'triggerDescription': 'Trigger description 0',
      'optoutDescription': 'Opt-out description 0',
      'agentAccessInstructions': 'Agent instructions 0',
      'videoUris': [
        'https://www.youtube.com/watch?v=NN75im_us4k'
      ],
      'screenshotUris': [
        'https://www.youtube.com/watch?v=NN75im_us4k'
      ]
    },
    'launchDetails': {
      '/v1/regions/fi-rcs': {}
    }
  }
}"

Para lanzar un agente en una o más regiones (cuando el agente ya se lanzó anteriormente), llama al método requestLaunch con un objeto que contenga un mapa de solo claves de todas las regiones en las que ya se lanzó el agente y todas las regiones en las que se quiere lanzar el agente. Usar un mapa vacío permite mantener la coherencia interna de la API en los objetos que se usan entre las llamadas a la API.

curl -X POST \
"https://businesscommunications.googleapis.com/v1/brands/BRAND_ID/agents/AGENT_ID:requestLaunch" \
-H "Content-Type: application/json" \
-H "$(oauth2l header --json PATH_TO_SERVICE_ACCOUNT_KEY businesscommunications)" \
-d "{
  'name': 'brands/BRAND_ID/agents/AGENT_ID/launch',
  'rcsBusinessMessaging': {
    'launchDetails': {
      '/v1/regions/fi-rcs': {},
      '/v1/regions/vodafone-idea-india': {}
    }
  }
}"

Si un agente llama al método requestLaunch, pero no incluye todas las regiones en las que ya se lanzó como claves, se arroja un error 400 - Bad Request.

Cómo consultar el estado de lanzamiento de un agente

Puedes recuperar el estado de lanzamiento actual de un agente. Para obtener más información, consulta brands.agents.getLaunch.

Node.js

const businessCommunicationsApiHelper =
  require('@google/rbm-businesscommunications');

const privateKey =
  require('../../resources/businesscommunications-service-account-credentials.json');

businessCommunicationsApiHelper.initBusinessCommunucationsApi(privateKey);

businessCommunicationsApiHelper.getAgentLaunch(agent.name).then((response) => {

}).catch((err) => {
  console.log(err);
});

Java

AgentLaunch launch = api.getAgentLaunch(agent.getName());
logger.info("RBM agent launch: " + launch);

Si el operador rechaza el lanzamiento, el socio puede volver a solicitarlo (la solicitud tiene el estado UNSPECIFIED y el backend tiene el estado REJECTED).

Este código devuelve la información y el estado del lanzamiento para cada operador objetivo:

{
  "name": "brands/40bd963f-ff92-425c-b273-8f0892d2d017/agents/my_new_agent_7jo0trhw_agent/launch",
  "rcsBusinessMessaging": {
    "questionnaire": {
      "contacts": [
        {
          "name": "James Bond",
          "title": "Mr O O 7",
          "email": "someone@somewhere.com"
        }
      ],
      "optinDescription": "Users accepted our terms of service online.",
      "triggerDescription": "We are reaching preregistered users",
      "interactionsDescription": "This agent does not do much.",
      "optoutDescription": "Reply stop and we stop.",
      "agentAccessInstructions": "This is a a simple agent that reaches registered users.",
      "videoUris": [
        "https://www.google.com/a/video"
      ],
      "screenshotUris": [
        "https://www.google.com/a/screenshot"
      ]
    },
    "launchDetails": {
      "/v1/regions/some-carrier": {
        "launchState": "LAUNCH_STATE_PENDING",
        "updateTime": "2023-02-24T15:02:13.903554Z"
      }
    },
    "launchRegion": "NORTH_AMERICA"
  }
}

Ten en cuenta que launchRegion dejó de estar disponible y se quitará pronto.

Agregar operadores adicionales al lanzamiento de un agente

Después de recuperar la información de lanzamiento actual de tu agente con la llamada a la API de brands.agents.getLaunch, puedes agregar más operadores objetivo para ampliar el alcance de tu agente. Consulta brands.agents.updateLaunch para obtener más información.

Node.js

const businessCommunicationsApiHelper =
  require('@google/rbm-businesscommunications');

const privateKey =
  require('../../resources/businesscommunications-service-account-credentials.json');

businessCommunicationsApiHelper.initBusinessCommunucationsApi(privateKey);');

// To launch an agent to further carriers, we need to first obtain the existing
// launch information and extend it with the new carrier(s).
businessCommunicationsApiHelper.getAgentLaunch(agent.name).then((response) => {
  let existingLaunch = response.data.rcsBusinessMessaging;

  // Now we add the new carrier to the existing launch
  existingLaunch.launchDetails[config.launchCarrier2] = null;

  // And we submit the launch again
  businessCommunicationsApiHelper.launchAgent(agent.name, existingLaunch).then((response) => {
    console.log('Launch details are:');
    console.log(JSON.stringify(response.data, null, 2));
  }).catch((err) => {
    console.log(err);
  });
}).catch((err) => {
  console.log(err);
});

Este código devuelve la información de lanzamiento actualizada:

{
  "name": "brands/40bd963f-ff92-425c-b273-8f0892d2d017/agents/my_new_agent_7jo0trhw_agent/launch",
  "rcsBusinessMessaging": {
    "questionnaire": {
      "contacts": [
        {
          "name": "James Bond",
          "title": "Mr O O 7",
          "email": "someone@somewhere.com"
        }
      ],
      "optinDescription": "Users accepted our terms of service online.",
      "triggerDescription": "We are reaching preregistered users",
      "interactionsDescription": "This agent does not do much.",
      "optoutDescription": "Reply stop and we stop.",
      "agentAccessInstructions": "This is a a simple agent that reaches registered users.",
      "videoUris": [
        "https://www.google.com/a/video"
      ],
      "screenshotUris": [
        "https://www.google.com/a/screenshot"
      ]
    },
    "launchDetails": {
      "/v1/regions/some-carrier": {
        "launchState": "LAUNCH_STATE_PENDING",
        "updateTime": "2023-02-24T15:02:13.903554Z"
      },
      "/v1/regions/another-carrier": {
        "launchState": "LAUNCH_STATE_PENDING",
        "updateTime": "2023-02-24T15:04:50.456552Z"
      }
    },
    "launchRegion": "NORTH_AMERICA"
  }
}

Después del lanzamiento y mantenimiento

Enumera todos los agentes creados para una marca

El desarrollador puede recuperar una lista de todos los agentes que creó para una marca. Para obtener más información, consulta brands.agents.list.

Node.js

const businessCommunicationsApiHelper =
  require('@google/rbm-businesscommunications');

const privateKey =
  require('../../resources/businesscommunications-service-account-credentials.json');

businessCommunicationsApiHelper.initBusinessCommunucationsApi(privateKey);

businessCommunicationsApiHelper.listAgents(brand.name).then((response) => {
  console.log('Current agents are:');
  console.log(response.data);
  datastore.saveJsonData('agents', response.data.agents);
}).catch((err) => {
  console.log(err);
});

Java

Brand brand = api.getBrand(brandId);
logger.info("Brand: " + brand);
ListAgentsResponse response = api.listAllAgents(brand);
List<Agent> agents = response.getAgents().stream()
  .sorted(Comparator.comparing(Agent::getName)).collect(Collectors.toList());
logger.info(String.format("Found %d agents", response.getAgents().size()));
for (Agent agent : agents) {
  logger.info(String.format("Agent [%s]: '%s'", agent.getName(), agent.getDisplayName()));
}

Este código devuelve una lista de todos los agentes que pertenecen a la marca:

{
  agents: [
    {
      name: 'brands/40bd963f-ff92-425c-b273-8f0892d2d017/agents/my_new_agent_4fpd1psz_agent',
      displayName: 'My new agent',
      rcsBusinessMessagingAgent: [Object]
    },
    {
      name: 'brands/40bd963f-ff92-425c-b273-8f0892d2d017/agents/my_new_agent_ciymyd2b_agent',
      displayName: 'My second agent',
      rcsBusinessMessagingAgent: [Object]
    },
    {
      name: 'brands/40bd963f-ff92-425c-b273-8f0892d2d017/agents/my_new_agent_helof85o_agent',
      displayName: 'My third agent',
      rcsBusinessMessagingAgent: [Object]
    }
  ]
}

Incluir agentes archivados

De forma predeterminada, la lista de todos los agentes excluye a los que archivó el socio. Para incluir agentes archivados en los resultados, establece el parámetro includeArchived en true.

Node.js

El método `listAgents` acepta un objeto de configuración opcional para incluir agentes archivados.
const businessCommunicationsApiHelper =
 require('@google/rbm-businesscommunications');

const privateKey =
 require('../../resources/businesscommunications-service-account-credentials.json');

businessCommunicationsApiHelper.initBusinessCommunicationsApi(privateKey);

// To list all agents including archived ones, set includeArchived to true
const listOptions = {
  includeArchived: true
};

businessCommunicationsApiHelper.listAgents(brand.name, listOptions).then((response) => {
 console.log('Current agents (including archived) are:');
 console.log(response.data);
 datastore.saveJsonData('agents', response.data.agents);
}).catch((err) => {
 console.log(err);
});

Java

El método `listAllAgents` incluye un parámetro booleano para el control de visibilidad.
// To list all agents including archived ones, pass 'true' for the includeArchived parameter
boolean includeArchived = true;
Brand brand = api.getBrand(brandId);
logger.info("Brand: " + brand);

// Call listAllAgents with the brand and the includeArchived flag
ListAgentsResponse response = api.listAllAgents(brand, includeArchived);

List agents = response.getAgents().stream()
 .sorted(Comparator.comparing(Agent::getName)).collect(Collectors.toList());

logger.info(String.format("Found %d agents (including archived)", response.getAgents().size()));
for (Agent agent : agents) {
 logger.info(String.format("Agent [%s]: '%s' (Archived: %s)",
    agent.getName(), agent.getDisplayName(), agent.getIsArchived()));
}

Cómo inhabilitar un agente

Para anular el lanzamiento de un agente en una región específica, llama al método updateLaunch, especifica la región objetivo en el mapa de la llamada y configura launchState como LAUNCH_STATE_UNLAUNCHED.

curl -X PATCH \
"https://businesscommunications.googleapis.com/v1/brands/BRAND_ID/agents/AGENT_ID/launch" \
-H "Content-Type: application/json" \
-H "$(oauth2l header --json PATH_TO_SERVICE_ACCOUNT_KEY businesscommunications)" \
-d "{
  'rcsBusinessMessaging': {
    'launchDetails': {
      '/v1/regions/fi-rcs': {
        'launchState': 'LAUNCH_STATE_UNLAUNCHED'
      },
      '/v1/regions/vodafone-idea-india': {
        'launchState': 'LAUNCH_STATE_UNLAUNCHED'
      }
    }
  }
}"

Borra un agente

Por motivos de seguridad, ya no se pueden borrar los agentes de RBM. Si necesitas ayuda, comunícate con el equipo de asistencia al cliente de RCS para empresas.

Archiva o desarchiva agentes

Para mantener un espacio de trabajo limpio y organizado, puedes archivar los agentes que ya no se usan. Si archivas un agente, se ocultará de los resultados de detección de la API predeterminada.

Archivar es un cambio solo de visibilidad. No borra el agente ni afecta su estado de lanzamiento subyacente. Puedes desarchivar un agente en cualquier momento para restablecer su visibilidad y continuar con su administración.

Para asegurarte de que los agentes activos no se oculten accidentalmente, se aplican las siguientes reglas:

  • Elegibilidad: Solo puedes archivar agentes que estén en estado inactivo: UNLAUNCHED, SUSPENDED o REJECTED.
  • Restricciones: No puedes archivar un agente que esté en estado LAUNCHED o PENDING en ningún operador. Si intentas archivar un agente de este tipo, se rechazará la solicitud con un error.

Actualiza el estado del archivo

Para archivar o desarchivar un agente, usa el método patch. Debes incluir el parámetro updateMask=is_archived en la URL para especificar el campo que se actualizará. Para archivar, establece el valor booleano isArchived en true y, para desarchivar, establécelo en false.

Método: PATCH /v1/brands/{brandId}/agents/{agentId} Agrega is_archived a la máscara de actualización.

{
  "isArchived": true
}

Cómo mostrar una lista de agentes con filtros

De forma predeterminada, el método list oculta los agentes archivados. Para incluirlos en tus resultados, usa el parámetro include_archived.

Método: GET /v1/brands/{brandId}/agents?include_archived=true