This is the multi-page printable view of this section. Click here to print.

Return to the regular view of this page.

Aura Bot utilities

Aura Bot utilities

Description of aura-bot-utilities

Introduction

aura-bot-utilities is a package belonging to aura-common-utilities that includes utilities for handling different tasks over aura-bot.

Find more information in the Github repository:
https://github.com/Telefonica/aura-common-utilities/tree/master/packages/aura-bot-utilities/

How to install aura-bot-utilities package

$ git clone https://github.com/Telefonica/aura-common-utilities.git

$ cd aura-common-utilities/packages/aura-bot-utilities

How to import an utility from this package

To import an utility from the aura-bot-utilities package, execute the following command:

import { ... } from '@telefonica/aura-bot-utilities/lib/[*utility-name*]';

For example:

import { generateAttachment, getReference, getTextFromResolution } from '@telefonica/aura-bot-utilities/lib/aura-bot-library-util';

Available utilities

List of utilities in the aura-bot-utilities package:

1 - aura-bot-kpis

aura-bot-kpis utility

aura-bot-kpis utility allows managing KPI entities in aura-bot and aura-groot.

Introduction

The aura-bot-kpis utility contains the necessary utilities to manage KPI entities in aura-bot and aura-groot.

Find more information in the Github repository: https://github.com/Telefonica/aura-common-utilities/tree/master/packages/aura-bot-utilities/src/aura-bot-kpis/

These guidelines will allow you to get a copy of the project running on your local machine for development and testing purposes.

Run tests

This project uses Jest for BBDD testing.

Unit tests

$ npm run test

Style tests

These tests perform the validation coding rules defined in Aura using the eslint tool.

You can validate the code using:

$ npm run lint

Coverage tests

You can run the coverage tests using:

$ npm run test

The threshold established to validate the coverage is as follows:

  • lines: 90%
  • functions: 90%
  • statements: 90%
  • branches: 70%

Versioning

We use [SemVer] (http://semver.org/) for versioning.

More information regarding latest versions:

$ npm show @telefonica/aura-bot-kpis

2 - aura-bot-library-util

aura-bot-library-util utility

aura-bot-library-util utility contains different utility files for aura-bot libraries

Introduction

aura-bot-library-util utility is an NPM library with utility functions provided by the Aura Bot Global Team to make it easier the development of dialogs in aura-bot.

Find more information in the Github repository: https://github.com/Telefonica/aura-common-utilities/tree/master/packages/aura-bot-utilities/src/aura-bot-library-util/

This library only contains utilities used in the dialogs, not needed by the bot itself.

To use it, just define the dependency with @telefonica/aura-bot-library-util in your package.json file. It is published as a private library in NPM, so request a valid NPM token to access it.

The utility files included in aura-bot-library-util utility are described in the following sections.

CurrencyUtils

aura-bot-library-util/currency-util.ts

getLocalizedCurrency

It returns money amounts formatted with country specific settings.

param type description mandatory
locale string Country locale code yes
amount number Total amount to be formatted yes
currency string Country currency code yes

    const amount: string = getLocalizedCurrency('es-es', 460.56, 'EUR');

    /* 460.56 € */

    const amount: string = getLocalizedCurrency('es-uy', 460.56, 'UYU');

    /* $ 461 */

Datautils

aura-bot-library-util/data-unit-util.ts

getDataAndUnit

It returns converted internet data amount and unit from bytes quantity, following the country specific settings.

param type description mandatory
content TurnContext Step context yes
configuration Configuration Dialog config variables yes
data number Data amount yes
forcePoint boolean It indicates if the decimals will be separated by points no

    const [dataQt, dataUnit] = getDataAndUnit(context, config, 1536)
    const [dataQt, dataUnit] = getDataAndUnit(context, config, 1536, true)

    /*
     * Result depending on AURA_DEFAULT_LOCALE env var
     * pt-br - ['1,5', 'GB']
     * en-gb - ['1.50', 'GB']
    */

LocaleUtils

aura-bot-library-util/locale-util.ts

getLiteral

This intermediate method generates a getText function ready to receive resources keys and sequential params.

param type description mandatory
context TurnContext step context yes
library string libraryName no

    /* If we need to convert only one text in function scope, we can use it as one line function */

    const text: string = getLiteral(context, 'services')('services.find.moreinfo', param1, param2);
    const text: string = getLiteral(context)('services:services.find.moreinfo', param1, param2);

    /* When we need to convert several texts in function scope for the same library,
    we can preassign result function to variable and proceed all along dialog step */

    const getServicesText: Function = getLiteral(context, 'services');

    const text: string = getServicesText('services.find.moreinfo', param1, param2);

    /* if we need to convert several texts in function scope for several libraries */

    const getText: Function = getLiteral(context);

    const text: string = getText('services:services.find.moreinfo', param1, param2);
    const errorText: string = getText('errors:error.notFound');

getTextByKeys

Factory function used mainly in graphs to retrieve converted text objects, avoiding redundancy.

param type description mandatory
context TurnContext step context yes
libraryName string libraryName yes

    const getGraphText: Function = getTextByKeys(context, 'graphics');

    const texts: any = getGraphTexts(['of', 'remaining'], { unit: 'data.gb' })

    /* Output
        {
            of: 'graphics:of', // converted text,
            remaining: 'graphics:remaining', // converted text,
            unit: graphics:data.gb, // converted text
        }
    */

withLocale

It encapsulates all data we need to call LocaleManager instance getText method.

param type description mandatory
context TurnContext step context yes
fn Function function to be executed at the end yes
library string libraryName no

For instance, getLiteral function passes an inline arrow function to simply receive the params that the result function was invoked with:


    /**
     * handy method to retrieve text.
     *
     * @param  {TurnContext} context The dialog step context.
     * @param  {string} libraryName? Library name.
     */
    export function getLiteral(context: TurnContext, libraryName?: string) {
        return withLocale(
            context,
            ({ getText, library }: any, literal: string, ...args: any[]) => getText(`${library ? library + ':' : ''}${literal}`, args),
            libraryName
        );
    }

This way, we can compose any method that fits our dialog text composition specific needs. A trivial working code sample could be:


    const _getText: Function = withLocale(stepContext.context, intermediateFunc)

    function intermediateFunc({ getText }, obj: any, params: string[], isError?: boolean) {
        const finalTextKey: string = isError ? obj.error : obj.text;
        return getText(finalTextKey, params);
    }

    const obj = {
        text: 'services:services.some.text',
        error: 'errors:error.message.error'
    }

    const text: string = _getText(obj, ['first', 'second']);
    const errorText: string = _getText(obj, [], true);

getErrorMessage

It composes a full error message with fallback text when required.

param type description mandatory
context TurnContext step context yes
statusCode number request code, if existing nullable
objErr StatusCodeMessagesMap Custom error messages no
    export interface StatusCodeMessagesMap {
        default: string;
        code400?: string;
        code404?: string;
    }
    try {
        //Do stuff
    } catch (error) {
        const messageMap: StatusCodeMessageMap = {
            default: 'services:services.custom.error',
            code400: 'services:services.error.badRequest',
            code404: 'services:services.error.notFound'
        }

        const errorMessage: string = getErrorMessage(stepContext.context, error.code, messageMap)
    }

sendLoggerErrorAndActivity

It sends full logged error message activity.

param type description mandatory
context TurnContext step context yes
logger any log function yes
objErr StatusCodeMessagesMap Custom error messages yes
dialogId string Current dialog ID yes
error any error to print yes
    try {
        /* [...] */
    }  catch (error ) {

        const messageMap: StatusCodeMessageMap = {
            default: 'services:services.custom.error',
            code400: 'services:services.error.badRequest',
            code404: 'services:services.error.notFound'
        }


        sendLoggerErrorAndActivity(
            context,
            this.logger,
            messageMap,
            ServicesFindDialog.id,
            error
        )
    }

LibraryUtil

aura-bot-library-util/library-util.ts

excludeDialogs

It excludes dialogs provided in an array.

param type description mandatory
dialogNames string[] Array with dialog’s ids yes
options any Options to customize function behavior yes
excludeDialogs(dialogNames: string[], options: any);

readLocaleFolder

Ir returns an object with locale name as key and file content as value.

param type description mandatory
localePath string localePath Base path where locale files are looked for yes
readLocaleFolder(localePath: string);

readEnv

It returns an object with env variables from current environment.

param type description mandatory
configuration any Object with configuration information yes
envPath string Path pointing to environment configuration yes
readEnv(configuration: any, envPath: string);

readDialogConfig

It returns an object with dialog config from current environment.

param type description mandatory
configuration any Object with configuration information yes
configPath string Path pointing to dialog configuration yes
readDialogConfig(configuration: any, configPath: string);

replaceToDialogByIntent

Given an intent, it replaces the current dialog by the intent that matches with it. This method triggers the main dialog and keeps the context-filter functionality in the replaced one.

param type description mandatory
stepContext WaterfallStepContext step context yes
intent string intent which the dialog will be triggered yes
await replaceToDialogByIntent(stepContext: WaterfallStepContext, intent: string);

generateSasUrl

It generates and returns the URL of the blob resource, applying expiration.

param type description mandatory
fileName string Blob file name yes
remoteContainerPath string Full container’s path yes
expiration number Expiration time in minutes no
configuration Configuration Environment configuration yes
correlator string Correlator no
await generateSasUrl(fileName: string, remoteContainerPath: string,
    configuration: Configuration, corr?: string, expiration?: number);

uploadFileUrl

It uploads a file to Azure Storage from an URL.

param type description mandatory
sourceUrlFile string URL that contains the file yes
remoteFilePath string Blob remote path yes
configuration Configuration Environment configuration yes
correlator string Correlator no
containerName string Storage container name no
await uploadFileUrl(sourceUrlFile: string, remoteFilePath: string,
    configuration: Configuration, corr?: string, containerName?: string) ;

ResourcesUtils

aura-bot-library-util/resources-util.ts

getImageUrl

It intercalates supported resolution folder path into image path, following channel image resolution settings.

param type description mandatory
context TurnContext step context yes
libraryName string Library proper name yes
url string Full path of the image default version in the library root folder yes
configuration Configuration Env variables yes
    // Current supported resolutions.
    enum SupportedResolutions {
        HDPI = 'hdpi',
        XHDPI = 'xhdpi',
        XXHDPI = 'xxhdpi',
        XXXHDPI = 'xxxhdpi'
    }

    // Taking channelData imageSettings resolution == xxxhdpi

    getImageUrl(context, 'services', 'images/default/imageName.png', configuration);

    // https://<storageUrl>/libraries/services/images/xxxhdpi/imageName.png?<params>

getResourcePath

It gets the whole resource path uploaded to blob-storage, that is accessible, to be included in cards.

param type description mandatory
configuration any Env variables yes
libraryName string Library proper name yes
baseFilePath string Base file access path yes
const uri: string = DialogUtils.getResourcePath('generic', resource, this.configuration);

3 - aura-minibot-service

aura-minibot-service utility

aura-minibot-service simplifies how aura-mini-bot and aura-mini-groot are generated.

Introduction

The aura-minibot-service utility contains the common elements needed by aura-bot and aura-groot to generate their mini versions: scripts, mock classes and templates, etc.

Find more information in the Github repository: https://github.com/Telefonica/aura-common-utilities/tree/master/packages/aura-bot-utilities/src/aura-mini-bot-service/

These guidelines will allow you to get a copy of the project running on your local machine for development and testing purposes.

Run tests

This project uses Jest for BBDD testing.

Unit tests

$ npm run test

Style tests

These tests perform the validation coding rules defined in Aura using the eslint tool.

You can validate the code using:

$ npm run lint

Coverage tests

You can run the coverage tests using:

$ npm run test

The threshold established to validate the coverage is as follows:

  • lines: 90%
  • functions: 90%
  • statements: 90%
  • branches: 70%

Versioning

We use [SemVer] (http://semver.org/) for versioning.

More information regarding latest versions:

$ npm show @telefonica/aura-minibot-service

4 - aura-movistar-libraries

aura-movistar-libraries utility

aura-movistar-libraries utility contains utilities to use with dialogs in Movistar channels

Introduction

aura-movistar-libraries utility is an NPM library that contains utility functions provided by Aura Global Team to be used with dialogs in Movistar channels:

  • Movistar Home
  • Movistar Plus
  • Set-top-box (STB)

Find more information in the Github repository: https://github.com/Telefonica/aura-common-utilities/tree/master/packages/aura-bot-utilities/src/aura-movistar-libraries-utilities/

To use it, just define the dependency with @telefonica/aura-movistar-libraries-utilities in your package.json. It is published as a private library in npm, so request a valid NPM token to access it.

models/intent-models

It contains all the necessary classes and interfaces for Movistar use cases. Some of these classes and interfaces are: MovistarPlusResolution, MovistarStatus, SuggestionAction, etc.

utils/movistar-payload-utils

It contains the functions executed to fill the payload of the message depending on the settings/payloadType in the intent configuration.

The principal functions are: getPayloadDefault, getPayloadCommunications, getPayloadTV and getPayloadWifi.

utils/movistar-resolution-utils

It contains the function to make a query to the Movistar plus resolution API. This query returns a MovistarPlusResolution object that contains suggestions, actions, sound, payload, etc.

Object example returned by getMovistarPlusResolution with intent intent.common.greetings in the STB channel:

{
      "intent":"intent.common.greetings",
      "entities":[

      ],
      "resources":[
         {
            "type":"title",
            "name":"tv.notUnderstand",
            "params":{

            }
         }
      ],
      "status":"ok",
      "payload":{
         "type":"",
         "data":{

         },
         "data_additional":{

         },
         "action":"NONE",
         "status":{
            "code":"470",
            "message":"Intent not Supported Error - General Code",
            "info":{ 

            }
         }
      },
      "user_action":{

      },
      "suggestions":[
         {
            "intent":"intent.tv.display",
            "entities":[
               {
                  "entity":"Canal Cocina",
                  "type":"ent.audiovisual_channel",
                  "score":1,
                  "canon":"Canal Cocina",
                  "label":""
               }
            ],
            "resources":[
               {
                  "type":"title",
                  "name":"tv.switchToChannel.suggestion.title",
                  "params":{
                     "channels":"Canal Cocina"
                  }
               },
               {
                  "type":"button",
                  "name":"tv.switchToChannel.suggestion.button",
                  "params":{
                     "channels":"Canal Cocina"
                  }
               }
            ]
         }
        /// More suggestions were returned but are ommited in this example object
      ],
      "sound":"none"
   }

utils/movistar-utils

A compendium of utilities which formats activity’s channelData to be compatible with Movistar channels.

The principal function of this file is getMovistarMessage. It returns a properly formed channelData message for the Movistar channels, depending on the input parameters and the settings field in the configuration of the intent. All other functions are auxiliary of this principal.

Example of object returned by getMovistarMessage with input params:

Input params

  • Context: Context of the dialog
  • Text: null
  • MovistarConfig:
{
   "type":"common",
   "action":"COMMON.GREETINGS",
   "locales":{
      "success":[
         "common:common.greetings.main"
      ],
      "error":[
         "common:common.error.main"
      ]
   },
   "needTvResolution":true
}

Output message

{
   "text":"Hola, buenas",
   "channelData":{
      "intent":{
         "id":"intent.common.greetings",
         "name":"intent.common.greetings",
         "entities":[

         ]
      },
      "content":{
         "text":"Hola, buenas",
         "speak":"Hola, buenas",
         "sound":"positive",
         "actions":[

         ]
      },
      "dialogContext":[
         {
            "text":"Quiero ver Canal Cocina",
            "value":{
               "intent":"intent.tv.display",
               "entities":[
                  {
                     "entity":"Canal Cocina",
                     "type":"ent.audiovisual_channel",
                     "score":1,
                     "canon":"Canal Cocina",
                     "label":""
                  }
               ]
            }
         }
         /// More suggestions were returned but are ommited in this example object
      ],
      "customData":{
         "type":"common",
         "action":"COMMON.GREETINGS",
         "data":{

         },
         "data_additional":{

         },
         "status":{
            "code":"200",
            "message":"Success - General Code",
            "info":{

            }
         }
      },
      "fullScreen":false,
      "version":"1.0.0"
   },
   "inputHint":"acceptingInput",
   "attachments":[
      {
         "contentType":"application/vnd.microsoft.card.hero",
         "content":{
            "buttons":[
               {
                  "type":"postBack",
                  "title":"Quiero ver Canal Cocina",
                  "value":{
                     "name":"Quiero ver Canal Cocina",
                     "text":"Ver Canal Cocina",
                     "type":"suggestion",
                     "intent":"intent.tv.display",
                     "entities":[
                        {
                           "entity":"Canal Cocina",
                           "type":"ent.audiovisual_channel",
                           "score":1,
                           "canon":"Canal Cocina",
                           "label":""
                        }
                     ],
                     "inputIntent":"intent.common.greetings",
                     "inputEntities":[

                     ]
                  }
               }
               /// More suggestions were returned but are ommited in this example object
            ]
         },
         "name":"SUGGESTIONS"
      }
   ]
}

suggestionType

Formerly, there was a differentiation between channels based on their prefix. This implementation was quite strict and to parameterize this behavior a new configuration variable has been developed.

SuggestionType must be configured for channels Movistar-Plus, Set-on-Box and Set-on-Box-Haac and its value can be either actions or attachments describing where suggestions must be placed in activity’s channelData.

  • ‘actions’: Movistar-Plus
  • ‘attachment’: Set-on-Box, Set-on-Box-Haac

5 - Aura Bot Common library

Aura Bot Common library

Aura Bot common is a core library that contains utilities for the integration of different components with Aura

Introduction

Aura Bot common is a helper library published in NPM that includes useful utilities to handle conversations both in aura-bot and in the dialogs.

Find more information in the Github repository:
https://github.com/Telefonica/aura-common-utilities/tree/master/packages/aura-bot-utilities/src/aura-bot-common

The Aura Bot common library holds models and utility code shared between aura-bot and the libraries. It contains two different types of methods: external and internal, which are described in the following sections.

5.1 - Aura utils

Aura utils

Aura utils is an utility found in Aura Bot common library to manage dialogs and prompts

Introduction

Aura utils utility allows managing Aura dialogs and prompts.

Find more information in the Github repository: https://github.com/Telefonica/aura-common-utilities/tree/master/packages/aura-bot-utilities/src/aura-bot-common/utils

It contains different methods, described in the following sections.

DialogUtils

Generic tools for any dialog.

setDataActiveDialog

It saves data between steps of a waterfall. Only valid in the same dialog.

param type description mandatory
context WaterfallStepContext Context in a step of a Waterfall yes
keyData string Key to recover data saved yes
data any Data to be saved yes
DialogUtils.setDataActiveDialog(stepContext, KEY_DESCRIPTION, description);

getDataActiveDialog

It gets data between the steps of a Waterfall through an identifier.

param type description mandatory
context WaterfallStepContext Context in a step of a Waterfall yes
keyData string Key to recover data saved yes
const description = DialogUtils.getDataActiveDialog(stepContext, KEY_DESCRIPTION);

getResourcePath

It gets the whole resource path uploaded to blob-storage to be included in cards.

param type description mandatory
libraryName string Original file name, that was uploaded to the blob-storage. yes
baseFilePath string Path in Azure Storage from library name (static-resources/libraries/library_name) to resource name. yes
configuration Configuration Set of of configuration variables. yes
const uriGenericRaw= DialogUtils.getResourcePath('generic', `${this.configuration.GENERIC_RESOURCES_BASE_PATH}/config/${this.configuration.GENERIC_RAW_NAME}`, this.configuration)

If we need a full URL image path including device resolution, getImageUrl method from @telefonica/aura-bot-library-util should be used instead.

It returns true if the passed URL is a deeplink, and false otherwise.

param type description mandatory
url string URL to check. yes
const isDeepLink = DialogUtils.isDeeplink('http://movistar.es/campain/ahora.html')

PromptUtils

getRetriesValidator

It gets a validator function that will be called each time the user responds to the prompt. In this function, it controls the number of retries to show the prompt.

If attempt is allowed, it is the recognizer that will let an attempt (when there are not results) or the dialog the will manage the result found.

If the retries exceed to maxRetries parameter, the control will be returned to dialog, managing results or not.

If an attempt is shown, the configured retryPrompt (or the same prompt as default) will be shown.

param type description mandatory
maxRetries number Number of retries to show the prompt yes
// Create a ChoicePrompt without retries
const myPrompt = new ChoicePrompt(ID_PROMPT,PromptUtils.getRetriesControl(0));

getRetriesValidatorAndOverwriteRecognizerResult

This validator function is similar to getRetriesValidator but also overwrites the recognizer result obtained by the prompt recognizer with a previous stored value.

This recognizer result value can be set with the function ContextUtils.setPromptRecognizedResult. By default, the result is: prompt-check-recognizer-middleware.

param type description mandatory
maxRetries number Number of retries to show the prompt yes
// Create a ChoicePrompt with 3 retries and use of ordinals control overwriting promptRecognizedResult with the value of aura-bot.
const myPrompt = new ChoicePrompt(ID_PROMPT,PromptUtils.getRetriesValidatorAndOverwriteRecognizerResult(3));

getAbsolutePath

It returns an absolute normalized file path.

param type description mandatory
filePath string File path to convert yes
const path: string = getAbsolutePath('/test/demo_path.txt');

5.2 - Bridge utils

Bridge utils

Bridge utils is a utility found in Aura Bot common library to manage aura-bridge

Introduction

Bridge utils utility includes methods for managing aura-bridge.

Find more information in the Github repository: https://github.com/Telefonica/aura-common-utilities/tree/master/packages/aura-bot-utilities/src/aura-bot-common/utils

It contains different methods, described in the following sections.

getAsyncCallbackUrl

This method is used for use cases that use asynchronous APIs and have to send a callback URL. It builds the URL with the parameters expected by the end point of aura-bridge, which will be the one that receives the event.

This returns the URL to send as callback parameter.

    function getAsyncCallbackUrl(context: TurnContext,
        configuration: Configuration, callbackId?: string, apiKeyHeader: boolean = false): string
param type description mandatory
context TurnContext Context where the channel data will be taken from yes
configuration Configuration Environment configuration yes
callbackId string Request identifier no
apiKeyHeader boolean Flag to indicate if APIKey is in header (true) or as parameter (false). By default, true no

Example of use:

const callbackUrl = getAsyncCallbackUrl(stepContext.context, this.configuration, callbackId);

getAsyncCallbackUrlDataEncrypt

This method builds the URL with the parameters expected by the endpoint for async-callbacks in aura-bridge.

   function getAsyncCallbackUrlDataEncrypt(auraId: string, channelId: string, conversationId: string, corr: string, configuration: Configuration, version: string, messageId: string, callbackId?: string, apiKeyHeader: boolean = false): string
param type description mandatory
auraId string Aura identifier yes
channelId string Channel identifier yes
conversationId string Conversation identifier yes
corr string Correlator yes
configuration Configuration Environment configuration yes
version string Request version yes
messageId string Original request version yes
callbackId string Request identifier no
apiKeyHeader boolean Flag to indicate if APIKey is in header (true) or as parameter (false). By default, true no

Example of use:

const callbackUrl = getAsyncCallbackUrlDataEncript( auraId, channelId, conversationId, corr, configuration, version, messageId, callbackId, true);

5.3 - Aura channelData utils

Aura channelData utils

channelData utils Aura utils is an utility found in Aura Bot common library in charge of managing Aura Bot channelData

Introduction

channelData utils utility allows managing Aura channelData.

Find more information in the Github repository: https://github.com/Telefonica/aura-common-utilities/tree/master/packages/aura-bot-utilities/src/aura-bot-common/utils

It contains different methods, described in the following sections.

getAuraModality

It returns the modality associated to a context. Otherwise, it returns an error if the channel could not be retrieved and injected into the message.

param type description mandatory
context TurnContext Context where the channel data will be taken from yes

Types of AuraModality:

export enum AuraModality {
    text = 'text',
    voice = 'voice',
    form = 'form'
}

Example of use:

const modality = ChannelDataUtils.getAuraModality(context);

getFullAura

It returns fullAura object from auraMode.

param type description mandatory
context TurnContext Context where the channel data will be taken from yes

Example of use:

const fullAura = ChannelDataUtils.getFullAura(context);

getAppContext

It gets AppContext from client and returns an structure with certain information about the client such as: device, application, location, channel, etc.

param type description mandatory
context TurnContext Context where the channel data will be taken from yes

Example of use:

const appContext = ChannelDataUtils.getAppContext(context);

getCustomContent

It returns a boolean if it is a custom content.

param type description mandatory
context TurnContext Context where the channel data will be taken from yes

Example of use:

const isCustomContent: boolean = ChannelDataUtils.getCustomContent(context);

getAuraId

It gets Aura id from the activiy.

param type description mandatory
context TurnContext Context where the channel data will be taken from yes
channelsConfig AuraChannelsConfiguration Channels configuration to obtain channelUserSeparator in case the function needs it no

Example of use:

const auraId: string = ChannelDataUtils.getAuraId(context);

getAuraCommandIntent

It gets the auraCommand intent.

param type description mandatory
context TurnContext Context where the channel data will be taken from yes

Example of use:

const auraCommandIntent: string = ChannelDataUtils.getAuraCommandIntent(context);

getChannelConfiguration

It gets the complete channel configuration from id or name.

param type description mandatory
channelsConfiguration AuraChannelsConfiguration Channels configuration. yes
channelId string Channel identifier. yes
channelName string Channel name. yes

Example of use:

const channel: ChannelConfiguration = ChannelDataUtils.getChannelConfiguration(channelsConfiguration, channelId, channelName);

getChannelId

It gets the channel Id.

param type description mandatory
context TurnContext Context where the channel data will be taken from yes

Example of use:

const channelId: string = ChannelDataUtils.getChannelId(context);

getChannelName

It gets the channel name.

param type description mandatory
context TurnContext Context where the channel data will be taken from yes

Example of use:

const channelName: string = ChannelDataUtils.getChannelName(context);

getChannelPrefix

It gets the channel prefix.

param type description mandatory
context TurnContext Context where the channel data will be taken from yes

Example of use:

const channelPrefix: string = ChannelDataUtils.getChannelPrefix(context);

getDeviceId

It gets the device Id.

param type description mandatory
context TurnContext Context where the channel data will be taken from yes

Example of use:

const deviceId: string = ChannelDataUtils.getDeviceId(context);

getAccountNumber

It gets the account number from userContext.

param type description mandatory
context TurnContext Context where the channel data will be taken from yes

Example of use:

const accountNumber: string = ChannelDataUtils.getAccountNumber(context);

getRequestVersion

It returns the channelData version. If it is not found, AURA_CHANNELDATA_DEFAULT_VERSION will be returned.

param type description mandatory
context TurnContext Context where the channel data will be taken from yes

Example of use:

const version: string = ChannelDataUtils.getRequestVersion(context);

setAppContext

It sets AppContext in channelData. In certain scenarios, it will be necessary to overwrite it to keep the track of changes that have occurred (e.g., in the applied contextFilters).

param type description mandatory
context TurnContext Context where the channel data will be taken from yes
appContext any New appContext to overwrite yes

Example of use:

ChannelDataUtils.setAppContext(context, appContext);

getActions

It gets actions from channelData. If exists, target will only extract actions for this target.

param type description mandatory
context TurnContext Context where the channel data will be taken from yes
target string Optional parameter to filter the actions by target no

Example of use:

const actions = ChannelDataUtils.getActions(context);

getStatusFromMessage

It gets status to message activity.channelData.status.

param type description mandatory
activity Partial Activity. yes

Example of use:

const status: AuraResponseStatus = ChannelDataUtils.getStatusFromMessage(activity): ;

getPayloadEvent

It gets the payload event.

param type description mandatory
context TurnContext Context where the channel data will be taken from. yes

Example of use:

const payload: ChannelDataPayload.PayloadEvent = ChannelDataUtils.getPayloadEvent(context);

getPayloadAsyncCallback

It gets the payload asyncCallback.

param type description mandatory
context TurnContext Context where the channel data will be taken from. yes

Example of use:

const payload = ChannelDataUtils.getPayloadAsyncCallback(context);

getPayloadBridgeUser

It gets the bridge user.

param type description mandatory
context TurnContext Context where the channel data will be taken from. yes

Example of use:

const payload: ChannelDataPayload.PayloadEvent = ChannelDataUtils.getPayloadBridgeUser(context);

Methods to be used only by Aura Bot

setAuraCommad

It sets an auraCommand, adding to the channelData attribute the auraCommand object with the type and value attributes.

param type description mandatory
context TurnContext Context where the channel data will be taken from yes
auraCommand AuraCommand AuraCommand to be set yes

Example of use:

ChannelDataUtils.setAuraCommad(this.context, new AuraCommand(AuraCommandType.TYPE, commandValue))

setResponseVersion

It sets the channelData version.

param type description mandatory
target TurnContext Partial
configuration Configuration Set of of configuration variables. yes
version string Version to be set no

Example of use:

const currentResponseVersion: string = ChannelDataUtils.setResponseVersion(activity, ConfigurationManager.instance.environmentConfiguration);

checkRequestVersion

It determines whether the version is major than AURA_RESPONSE_VERSION or not.

param type description mandatory
context TurnContext Context where the channel data will be taken from yes
configuration Configuration Set of configuration variables. yes

Example of use:

const check: boolean = ChannelDataUtils.checkRequestVersion(context, ConfigurationManager.instance.environmentConfiguration);

setStatusToMessage

It sets status to message activity.channelData.status.

param type description mandatory
activity Partial Activity yes
status status status to set yes

Example of use:

ChannelDataUtils.setStatusToMessage(activity, status): ;

5.4 - Conversational context utils

Conversational context utils

Conversational context utils is an utility found in Aura Bot common library in charge of managing BotFramework TurnContext

Introduction

Conversational context utils utility allows managing BotFramework TurnContext.

Find more information in the Github repository: https://github.com/Telefonica/aura-common-utilities/tree/master/packages/aura-bot-utilities/src/aura-bot-common/utils

It contains different methods, described in the following sections.

getAuraUser

It gets the AuraUser with the minimum BaseModel attributes and, optionally, more specific attributes of the authenticator.

param type description mandatory
context TurnContext Context where the channel data will be taken from yes

Minimum BaseModel attributes:

export interface AuraUserBaseModel<T> {
    auraId: string;
    auraIdGlobal: string;
    type: AuraUserType;
    userId: string;
    authData: T;
    channel: ChannelConfiguration;
    timestamp: number;
    deviceId?: string;
    accountNumber?: string;
    phoneNumber?: string;
    authorizationId?: string;
    redirectIntent?: string;
    originalAddress?: MessageUserInfo;
    sessionId?: string;
    idTokenHint?: string;
}

Example of use:

const auraUser = ContextUtils.getAuraUser(context);

getAuraPersistentData

It gets persistent data including information about: conversationData, userData and dialogData.

export interface AuraPersistentData {
    conversationData: any;
    userData: any;
    dialogData: any;
}
param type description mandatory
context TurnContext Context where the channel data will be taken from yes

Example of use:

const persistentData = await ContextUtils.getAuraPersistentData(stepContext.context);
if (persistentData.conversationData.orderPizza) {
    orderPizza = persistentData.conversationData.orderPizza;
}
...

getCorrelator

It gets the correlator (identifier to track the request).

param type description mandatory
context TurnContext Context where the channelData will be taken from yes
const corr: string = ContextUtils.getCorrelator(stepContext.context);
this.logger.info({ msg: 'App GenericFaq Closed', corr });

getRecognitionResult

It gets the result of the recognition process.

⚠️ In some cases, the recognition process has been altered to avoid the execution of other recognizers and the result might not be as expected.

param type description mandatory
context TurnContext Context where the channel data will be taken from yes
export interface RecognizerResult {
    /**
     * Utterance sent to recognizer
     */
    readonly text: string;
    /**
     * If original text is changed by things like spelling, the altered version.
     */
    readonly alteredText?: string;
    /**
     * Intents recognized for the utterance.
     *
     * @remarks
     * A map of intent names to an object with score is returned.
     */
    readonly intents: {
        [name: string]: {
            score: number;
        };
    };
    /**
     * (Optional) entities recognized.
     */
    readonly entities?: any;
    /**
     * (Optional) other properties
     */
    [propName: string]: any;
}

Example of use:

const recognitionResult: RecognizerResult = ContextUtils.getRecognitionResult(stepContext.context);
const entities = recognitionResult.entities;

getTopIntentResult

Among all the recognized intents, it gets the topIntent with the highest score and the utm information.

⚠️ In some cases, the recognition process has been altered to avoid the execution of other recognizers and the result might not be as expected.

param type description mandatory
context TurnContext Context where the channel data will be taken from yes
export interface AuraIntentResult extends RecognizerResult {
    topIntent: Intent;
    utm: Utm;
}

Example of use:

const auraIntentResult: AuraIntentResult = ContextUtils.getAuraIntentResult(stepContext.context);
const utmInfo: Utm = auraIntentResult.utm;

getTopIntent

Among all the recognized intents, it gets the topIntent with the highest score directly.

⚠️ In some cases, the recognition process has been altered to avoid the execution of other recognizers and the result might not be as expected.

param type description mandatory
context TurnContext Context where the channel data will be taken from yes
export interface Intent {
    intent: string;
    entities?: IEntity[];
    score?: number;
    type?: IntentType;
}

Example of use:

const auraIntentResult: Intent = ContextUtils.getTopIntent(stepContext.context);

getTopIntentValue

Among all the recognized intents, it gets the topIntent value in string format. For example: intent.balance.check.

⚠️ In some cases, the recognition process has been altered to avoid the execution of other recognizers and the result might not be as expected.

param type description mandatory
context TurnContext Context where the channel data will be taken from yes

Example of use:

const intent : string = ContextUtils.getTopIntentValue(stepContext.context);

getUserChannel

It gets the user’s channel.

param type description mandatory
context TurnContext Context where the channel data will be taken from yes
export interface ChannelConfigurationPartial {
    auraBotCacheTTL?: number;
    id: string;
    brand?: string;
    dialogLibraries?: DialogLibraryConfiguration[];
    name?: string;
    nlp?: NlpConfig;
    actions?: ChannelActions;
    prefix?: string;
    requestOptions?: RequestOptionsModel;
    responseOptions?: ResponseOptions;
    security?: Security;
    whatsapp?: WhatsAppModel;
    type?: BridgeType;
    metadata?: DocumentMetadata;
}
export interface ChannelConfiguration extends ChannelConfigurationPartial {
    brand: string;
    name: string;
    prefix: string;
    nlp: NlpConfig;
}

Example of use:

const userChannel: ChannelConfiguration = ContextUtils.getUserChannel(stepContext.context);

getPromptRecognizedResult

It gets the recognizerResult from turnState to retrieve the value in the validator function.

This function is currently used in getRetriesValidatorAndOverwriteRecognizerResult function, used for overwrite the default recognizerResult with the result got in the prompt recognizer.

param type description mandatory
context TurnContext Context where the channel data will be taken from yes

Example of use:

const userChannel: PromptRecognizerResult<any> = ContextUtils.getPromptRecognizedResult(context);

setPromptRecognizedResult

It saves the recognizerResult in the turnState to retrieve the value later in the validator function.

This function is currently used in the prompt recognizer where a custom recognizeChoices is performed (including number and ordinal recognition).

param type description mandatory
context TurnContext Context where the channel data will be taken from yes
promptRecognizedResult PromptRecognizerResult Result of prompt recognition yes

Example of use:

const result: PromptRecognizerResult<FoundChoice> = { succeeded: false };
if (matched.length > 0) {
	result.succeeded = true;
    result.value = matched[0].resolution;
}
// Save personalized recognizer result
ContextUtils.setPromptRecognizedResult(context, result);

existError

It checks if an error exist and returns a boolean. (Mainly, it is designed for middlewares)

param type description mandatory
context TurnContext Context where the channel data will be taken from yes

Example of use:

 if (!ContextUtils.existError(context)) {
 ...
 }

setError

It sets an error without warning the user at that time, allowing the execution of remaining middlewares. (Mainly designed for middlewares)

param type description mandatory
context TurnContext Context where the channel data will be taken from yes
error Error Error got from catch (for example) yes
localMessage string Specific error message for logger no
activityMessage string Specific error message for activity show to user no

Example of use:

try {
} catch (error) {
	await ContextUtils.setError(context, error);
}

setErrorAndSendActivity

It sets an error and immediately sends a message to the user. (Mainly designed for dialogs).

param type description mandatory
context TurnContext Context where the channel data will be taken from yes
error Error Error got from catch (for example) yes
localMessage string Specific error message for logger no
activityMessage string Specific error message for activity show to user no

Example of use:

try {
} catch (error) {
	await ContextUtils.setErrorAndSendActivity(context, error);
}

setHistoryConversation

It stores in Conversation Data the request and response messages. This method is deprecated.

param type description mandatory
context TurnContext Context where the channel data will be taken from yes
activity Partial Activity requested to the channel yes
maxHistorySize number Maximum number of messages in the history yes

Example of use:

await ContextUtils.setHistoryConversation(
     context,
     activity,
     ConfigurationManager.instance.environmentConfiguration.AURA_MAX_HISTORY_CHAT_ITERATIONS
);

addToHistoryConversation

It stores in Conversation Data the request and response messages.

⚠️ This method is deprecated.

param type description mandatory
context TurnContext Context where the channel data will be taken from yes
activity Partial Activity requested to the channel yes
maxHistorySize number Maximum number of messages in the history yes
isRequest boolean If is request no

Example of use:

this.addToHistoryConversation(context, activity, maxHistorySize, false);

getHistoryConversation

It returns the history conversation stored in Conversation Data.

param type description mandatory
context TurnContext Context where the channel data will be taken from yes
loadFromRemote boolean Force to load the history from remote storage yes
formatter (DialogChatHistory) => string Formatter function no

Example of use:

const history = await ContextUtils.getHistoryConversation(context, true,
        (item: DialogChatHistory) =>
            `(${getLocalFormattedIsoTime(item.date)})` +
            `[${(item.type === 'request') ? User : AURA}]:${item.message}`
    )

Result:

2021-3-15 15:55:02 User:  Que ponen en la cuatro
2021-3-15 15:55:04 AURA:  Ok, estarei aqui sempre que você precisar.
2021-3-15 15:55:08 User:  Hola?
2021-3-15 15:55:09 AURA:  Ok, estarei aqui sempre que você precisar.
2021-3-15 15:55:15 User:  Bye
2021-3-15 15:55:16 AURA:  Ok, estarei aqui sempre que você precisar.

setConversationState

It stores the conversation state in turnState.

param type description mandatory
context TurnContext Context where the channel data will be taken from yes
conversationState ConversationState Conversation state to store yes

Example of use:

ContextUtils.setConversationState(context, this.conversationState);

saveConversationState

It saves the cached state object if it has been changed. If the force flag is passed in the cached state, the object will be saved regardless of whether it has been changed or not. If no object has been cached, an empty object will be created and then saved.

param type description mandatory
context TurnContext Context for current turn of conversation with the user yes
force boolean If true, the state will always be written, out regardless of its change state. By default, false. no

Example of use:

await ContextUtils.saveConversationState(context, true);

loadConversationState

It reads and caches the backing state object for a turn. Subsequent readings will return the cached object, unless the force flag is passed, in which the state object to be re-read will be forced.

param type description mandatory
context TurnContext Context for current turn of conversation with the user yes
force boolean If true, the cache will be bypassed and the state will always be read directly from storage. By default, false. no

Example of use:

await ContextUtils.loadConversationState(context, loadFromRemote);

getInternalSuggestions

It gets Aura suggestions.

param type description mandatory
context TurnContext Context yes

Example of use:

const internalSuggestions: InternalSuggestions = ContextUtils.getInternalSuggestions(stepContext.context);

setInternalSuggestions

It sets Aura suggestions.

param type description mandatory
context TurnContext Context yes
internalSuggestions InternalSuggestions Suggestions to store yes

Example of use:

getUserAuthPersistentData

It gets the user’s authentication state for login/logout.

export interface IUserAuthState {
    refreshCache?: boolean; // Deprecated in Vortex release
    accountRemovalTimestamp?: number;
}
param type description mandatory
context TurnContext Context where the channel data will be taken from yes

Example of use:

const userAuthState = await ContextUtils.getUserAuthPersistentData(stepContext.context);

getCorrelatorFromChannelData

It gets the correlator from channelData, if exists there, or creates a new one.

param type description mandatory
context TurnContext Context where the channel data will be taken from yes

Example of use:

const correlator = ContextUtils.getCorrelatorFromChannelData(context);

setStatus

It sets status to the response channelData object.

param type description mandatory
context TurnContext Current Context yes
status AuraResponseStatus Aura Response object with the error status yes
errorInfo Error Extra info of error. Used when the error has been triggered by another component no
logAsError boolean Force to log the error info as logger.error. By default, false. It logs only in debug level mode no

Example of use:

ContextUtils.setStatus(context, new AuraResponseStatus(AURA_STATUS.ERROR.OTHER.GENERAL));

getError

It gets the error from context.

param type description mandatory
context TurnContext Context where the channel data will be taken from yes

Example of use:

const error = ContextUtils.getError(context);

getRecognizer

It gets the recognizer.

param type description mandatory
context TurnContext Context where the channel data will be taken from yes

Example of use:

const error = ContextUtils.getRecognizer(context);

setRecognizer

It sets the recognizer.

param type description mandatory
context TurnContext Context where the
channelData will set yes
recognizer string Recognizer yes

Example of use:

const error = ContextUtils.getSecognizer(context, recognizer);

5.5 - Ai service

AI Service

AI Service is an utility found in Aura Bot common library in charge of managing calls to external AI services.

Introduction

AI ​​Service allows you to manage calls to external AI services through generative APIs. The service is responsible for abstracting the details of the API calls and providing a simple interface for recognizing intents using different recognizers.

Creating an instance of the service

To create an instance of the service, you need to provide a AiRecognizerServiceConfiguration object with the following parameters:

Parameter Type Description Mandatory
AURA_GATEWAY_API_ENDPOINT string URL of the Aura Gateway API yes
AURA_AUTHORIZATION_HEADER string Authorization header yes
AURA_GATEWAY_API_ISSUER_URL string Issuer URL for token info yes

Example of use:

import { AuraBotCommon } from '@telefonica/aura-bot-utilities';

const aiService = new AuraBotCommon.AiRecognizerService({
    AURA_AUTHORIZATION_HEADER: process.env.AURA_AUTHORIZATION_HEADER!,
    AURA_GATEWAY_API_ENDPOINT: process.env.AURA_GATEWAY_API_ENDPOINT!,
    AURA_GATEWAY_API_ISSUER_URL: process.env.AURA_GATEWAY_API_ISSUER_URL!
});

Recognizing intents. The recognize method

The recognize method allows you to recognize intents from a TurnContext using a specific intent configuration. The method takes the following parameters:

Parameter Type Description Mandatory
context TurnContext Turn context yes
intentConfiguration AuraConfigurationApiClient.AtriaIntentConfiguration Intent configuration yes

Example of use:

const intentConfiguration = AiRecognizerService.getConfigurationByRecognizer(
    context, AiRecognizerService.TRIAGE_RECOGNIZER
);

const intent = await aiService.recognize(context, intentConfiguration);

This method uses the generative API to send the message and receive the response. It also manages the session ID by storing it in the TurnContext for future requests.

Recognizing intents using triage. The recognizeUsingTriage method

The recognizeUsingTriage method allows you to recognize intents from a TurnContext using the triage recognizer. The method takes the following parameter:

Parameter Type Description Mandatory
context TurnContext Turn context yes

Example of use:

const intent = await aiService.recognizeUsingTriage(context);

Getting configurations

The AI Service provides two static methods to retrieve intent configurations from the TurnContext:

  • getConfigurationByRecognizer: Retrieves the configuration for a specific recognizer by its name.
  • getConfigurationByDialog: Retrieves the configuration for a specific dialog by its intent name.