Changing locale in a Node.js bot

Back in March we implemented a new feature in the BotBuilder SDK for Node.js which allows developers to provide simple localization switching in their bots. This means your bot will be able to prompt your users for different language options.

Using the Node SDK’s LocalizedRegExpRecognizer

To add this feature, we included a new recognizer to the core library – LocalizedRegExpRecognizer. This recognizer extends the IntentRecognizer and uses language specific regular expressions specified by the developer on the client side to match intents. As a Node.js bot developer, you might factor your localization settings like the following example:

Our language-specific patterns are defined for english (“en”) and spanish(“es”) in JSON format in index.json separated by different folders for locale.

Below is a sample from the index.json we’re using for English (“en”) localization:

// index.json in "en" locale
    "localized_greetingRegExp": "^Hello$|^Good morning$|^Good afternoon$",
    "locale_updated": "Locale Updated!",
    "greeting": ["Hi there!", "Welcome.", "Hello!", "Greetings."],
    "good_bye": ["Good-bye!", "Farewell!", "Bye!", "See you later!"]

Here is a sample from the index.json configuration for Spanish (“es”) localization:

// index.json in "es" locale
    "localized_greetingRegExp": "^Hola$|^Buenas dias$|^Buenas tardes$",
    "locale_updated": "Locale Updated!",
    "greeting": ["¡Hola!"],
    "good_bye": ["Adiós!", "¡Hasta luego!"]

Back in the bot, we can define our LocalizedRegExpRecognizer:

var localeRecog = new builder.LocalizedRegExpRecognizer('Greetings', 

The first input "Greetings" is the intent and the second input "localized_greetingRegExp"provisions the key to the regular expression pattern in our index.json files.

As a best practice, bots should initially prompt the user to select their language/locale. After the user sets their locale, their next utterance will trigger the LocalizedRegExpRecognizer to look for a RegExpRecognizer mapped to the current locale. If one doesn’t exist, it will create a RegExpRecognizer.

For example if the preferred locale is "es", our LocalizedRegExpRecognizer looks for localeRecog.recognizers["es"]. If it doesn’t exist, LocalizedRegExpRecognizer will create one using the first two parameters passed to it during its construction.

Included below are screenshots that show an example of an interaction using the LocalizedRegExpRecognizer.

Type something to the chatbot to begin, then select a language:

Choosing Spanish which corresponds to the locale “es”:

Triggering the next dialog which responds with a greeting and farewell:

Selecting English this time:

Starting the next dialog by uttering “hello”:

And that’s it! We’ve included a simple way to allow prompt users to specify different localizations.

Happy Making!

Steven Gum from the Bot Framework Team