{{announcement.body}}
{{announcement.title}}

Externalize your i18n in your Alexa Skill

DZone 's Guide to

Externalize your i18n in your Alexa Skill

In this article, we discuss how externalize the i18n to enhance your Alexa Skill development and mantenance.

· AI Zone ·
Free Resource

In computing, internationalization is the process of designing software so that it can be adapted to different languages and regions without the need of re-engineering or making changes in code.

In the case of software, it means to translate into several languages, using different currencies or using different date formats.

In terms of Alexa Skills, it is a good practice having the translations separated from the AWS Lambda source code. There are many tools that can help us in this process. We will guide you in this process using POEditor.

Prerequisites

Here you have the technologies used in this project.

  1. Amazon Developer Account - How to get it
  2. AWS Account - Sign up here for free
  3. ASK CLI - Install and configure ASK CLI
  4. AWS CLI - Install and configure AWS CLI
  5. POEditor Account - Register here
  6. Node.js v10.x
  7. Java Runtime Environment (JRE) version 6.x or newer
  8. Visual Studio Code
  9. npm Package Manager

The Alexa Skills Kit Command Line Interface (ASK CLI) is a tool for you to manage your Alexa skills and related resources, such as AWS Lambda functions. With ASK CLI, you have access to the Skill Management API, which allows you to manage Alexa skills programmatically from the command line. If you want how to create your Skill with the ASK CLI in Node.js using DynamoDB on local machine, please follow the steps explained in my repository here sample. Let's start!

POEditor

POEditor is an online localization platform and translation management system, designed for teams to collaborate easily, but also suited for individuals. You can use POEditor to translate apps, websites, themes, plugins, games or other software products, and to automate the localization workflow. Supported most of the l18n file formats. They also have a really nice and easy-to-use RESTFul API.

What POEditor offer to us?

  1. Simple REST API Bring POEditor to home base by connecting it to your software via our simple API. Let the API automate your localization workflow and forget about manually managing your localization projects.
  2. GitHub, Bitbucket, GitLab and Azure DevOps integration Connect your repos to your POEditor account to quickly communicate data between our localization platform and GitHub/Bitbucket/GitLab/Azure Devops. Use the WordPress translation plugin to manage the localization of your language files directly in WordPress, via the POEditor API.
  3. Slack and Microsoft Teams integration Connect your POEditor account to Slack or Microsoft Teams and never miss any important events during the localization process. Add your localization team members to dedicated channels, and you'll always be on the same page, in real time.
  4. Crowdsourced translation projects Set your software localization project to "Public" to crowdsource the translation of your strings. You will get a link that you can share in order to invite people to enroll as contributors.
  5. Rich statistics The stats page offers real-time information about your translators' activity, the amount of terms, translations, words and characters belonging to a localization project, as well as charts and the percentage of completion for each language
  6. Smart Translation Memory Don't like to translate strings multiple times? Then you will enjoy using the Translation Memory feature. The TM searches through all your previous translations so you can reuse them.
  7. Realtime translation updates If collaborative software localization sounds like a mess, relax. POEditor lets you know of your fellow translators' whereabouts when you're sharing the same language page, and automatically saves any changes you make to the translation.
  8. Human translation services Purchase professional human translations for your localization project directly from your POEditor account. We've neatly aggregated the translation providers we are partners with, for you to easily compare and integrate into your continuous localization workflow.
  9. Automatic Translation Automatic Translation offers the possibility to work with the machine translation engines from Google, Microsoft and DeepL, in order to automatically fill in missing translations.

Setting up POEditor

Once we have signed up on POEditor, now it is time to create a new project for our Alexa Skill. It is a good practice to have one POEditor project per Skill.

We have created one called test-skill that contains 15 strings and it is available in Spanish and English:

Test skill

As you can see above, we have a quick look at the status of our projects. We can see we have the 57% of our project translated.

If we click on our project, we will see the status of that project:

Project status

In this view we can see we have 15 strings in 2 languages with 7 terms to translate and only 8 available translations. Below this it is available the information per language, we have all the Spanish translations but in English, we only have the 14%, it means that in English we only have one translation done.

In this page you can make a bulk import, add terms to translate, add new languages, show the stats of the translations and setting up some configuration of this project like permissions, contributors, code hosting service integration, make it open source, etc.

And finally if we click in a language, e.g. Spanish, we will see the translations:

Language translations

Here you can make a bulk import as well, export the current language translations and execute the translation memory tool. If you do not have all the translation of this language you can activate the automatic translation (It will use Google, Microsoft or DeepL to make that).

Downloading Translations in the Alexa Skill

So, now we have the project properly configured. To download the translations, we will use the POEditor API to download the terms and all translations of one specific language:

Methods and terms

This is an example of the request:

Shell
 




x


1
 curl -X POST https://api.poeditor.com/v2/terms/list \
2
      -d api_token="3af6ba0fa02f86fcf38bbe1b533461f1" \
3
      -d id="7717" \
4
      -d language="es"


This is an example of the response:

JSON
 




x
116


1
  {
2
    "response": {
3
      "status": "success",
4
      "code": "200",
5
      "message": "OK"
6
    },
7
    "result": {
8
      "terms": [
9
        {
10
          "term": "WELCOME_MSG",
11
          "context": "",
12
          "plural": "",
13
          "created": "2020-05-16T16:53:24+0000",
14
          "updated": "2020-05-24T11:45:59+0000",
15
          "translation": {
16
            "content": "Beienvenido en que te puedo ayudar?",
17
            "fuzzy": 0,
18
            "updated": "2020-05-24T12:12:21+0000"
19
          },
20
          "reference": "",
21
          "tags": [],
22
          "comment": ""
23
        },
24
        {
25
          "term": "HELLO_MSG",
26
          "context": "",
27
          "plural": "",
28
          "created": "2020-05-24T11:31:07+0000",
29
          "updated": "",
30
          "translation": {
31
            "content": "Hola Mundo!",
32
            "fuzzy": 0,
33
            "updated": "2020-05-24T11:32:13+0000"
34
          },
35
          "reference": "",
36
          "tags": [],
37
          "comment": ""
38
        },
39
        {
40
          "term": "HELP_MSG",
41
          "context": "",
42
          "plural": "",
43
          "created": "2020-05-24T11:31:20+0000",
44
          "updated": "",
45
          "translation": {
46
            "content": "Puedes decirme hola. Cómo te puedo ayudar?",
47
            "fuzzy": 0,
48
            "updated": "2020-05-24T11:32:19+0000"
49
          },
50
          "reference": "",
51
          "tags": [],
52
          "comment": ""
53
        },
54
        {
55
          "term": "GOODBYE_MSG",
56
          "context": "",
57
          "plural": "",
58
          "created": "2020-05-24T11:31:25+0000",
59
          "updated": "",
60
          "translation": {
61
            "content": "Hasta luego!",
62
            "fuzzy": 0,
63
            "updated": "2020-05-24T11:32:23+0000"
64
          },
65
          "reference": "",
66
          "tags": [],
67
          "comment": ""
68
        },
69
        {
70
          "term": "REFLECTOR_MSG",
71
          "context": "",
72
          "plural": "",
73
          "created": "2020-05-24T11:31:29+0000",
74
          "updated": "",
75
          "translation": {
76
            "content": "Acabas de activar %(intentName)s",
77
            "fuzzy": 0,
78
            "updated": "2020-05-24T12:12:26+0000"
79
          },
80
          "reference": "",
81
          "tags": [],
82
          "comment": ""
83
        },
84
        {
85
          "term": "FALLBACK_MSG",
86
          "context": "",
87
          "plural": "",
88
          "created": "2020-05-24T11:31:34+0000",
89
          "updated": "",
90
          "translation": {
91
            "content": "Lo siento, no se nada sobre eso. Por favor inténtalo otra vez.",
92
            "fuzzy": 0,
93
            "updated": "2020-05-24T11:32:34+0000"
94
          },
95
          "reference": "",
96
          "tags": [],
97
          "comment": ""
98
        },
99
        {
100
          "term": "ERROR_MSG",
101
          "context": "",
102
          "plural": "",
103
          "created": "2020-05-24T11:31:38+0000",
104
          "updated": "",
105
          "translation": {
106
            "content": "Lo siento, ha habido un error. Por favor inténtalo otra vez.",
107
            "fuzzy": 0,
108
            "updated": "2020-05-24T11:32:38+0000"
109
          },
110
          "reference": "",
111
          "tags": [],
112
          "comment": ""
113
        }
114
      ]
115
    }
116
  }


Understanding how the API works, it is time to integrate it into our Alexa Skill.

We will use the following flow to download the translations:

Flow

The following code located in utilities/i18nUtils.js will execute the same as we explained in the flow diagram:

JavaScript
 




x
64


 
1
 async function downloadTranslations(locale, handlerInput) {
2
 
          
3
        const ISOlocale = locale.split('-')[0];
4
        const { attributesManager } = handlerInput;
5
        var sessionAtrributes = attributesManager.getSessionAttributes();
6
        var download = false;
7
        //New session stablished
8
        if(!('translations' in sessionAtrributes)){
9
            console.log('NO TRANSLATIONS IN SESSION');
10
            persitentAttributes = await attributesManager.getPersistentAttributes();
11
            if(!('translations' in persitentAttributes)){
12
                console.log('NO TRANSLATIONS IN DYNAMODB');
13
                download = true;
14
            
15
            }else{
16
                //we have translataions
17
                if((ISOlocale in persitentAttributes.translations)){
18
                        const lastDowloaded = moment(persitentAttributes.translations[ISOlocale].timestamp);
19
                        const today = moment();
20
 
          
21
                        var diffDays = today.diff(lastDowloaded, 'days');
22
                        if(diffDays >= 7){
23
                            console.log('THERE ARE TRANSLATIONS IN DYNAMODB FOR CURRENT LOCALE BUT TO OLD');
24
                            download = true;
25
                        }else{
26
                            console.log('THERE ARE TRANSLATIONS IN DYNAMODB FOR CURRENT LOCALE');
27
                            download = false;
28
                            translations = persitentAttributes.translations[ISOlocale].strings;
29
                        }
30
                        
31
                }else{
32
                    console.log('THERE ARE TRANSLATIONS IN DYNAMODB BUT NOT FOR CURRENT LOCALE');
33
                    download = true
34
                }
35
            }
36
        }
37
 
          
38
        if(download){
39
            console.log('DOWNLOADING TRANSLATIONS...');
40
            translations = await rp.post(poEditorEndpoint, {
41
                form: {
42
                    api_token: poEditorToken,
43
                    id: poEditorProjectId,
44
                    language: ISOlocale
45
                }
46
            }).then(function (body) {
47
                // Request succeeded but might as well be a 404
48
                // Usually combined with resolveWithFullResponse = true to check response.statusCode
49
                return JSON.parse(body).result;
50
                
51
            })
52
            .catch(function (err) {
53
                // Request failed due to technical reasons...
54
            });
55
        }
56
 
          
57
        
58
        sessionAtrributes['translations'] = translations;
59
        sessionAtrributes['translations'].downloaded = download;
60
        console.log('TRANSLATIONS: ' + JSON.stringify(translations));
61
 
          
62
        attributesManager.setSessionAttributes(sessionAtrributes);
63
 
          
64
    }


In order to make in an easy way a x-www-form-urlencoded POST request in Node.js, we will use the npm package request-promise.

This code will be called from the localisationRequestInterceptor:

JavaScript
 




x
15


1
const Alexa = require('ask-sdk-core');
2
 
          
3
const i18nUtils = require('../utilities/i18nUtils');
4
 
          
5
// This request interceptor will bind a translation function 't' to the handlerInput
6
module.exports = {
7
    LocalisationRequestInterceptor: {
8
        async process(handlerInput) {
9
 
          
10
            const locale = Alexa.getLocale(handlerInput.requestEnvelope);
11
            await i18nUtils.downloadTranslations(locale, handlerInput);
12
 
          
13
        }
14
    }
15
}


Using Translations in the Alexa Skill

Now we have the translations downloaded in our Alexa Skill, it is time to use it there!

I have removed the i18next npm package because we will not use it anymore. Now we will have our own translation function.

This function will be search a term in the translations downloaded before. It is located in i18nUtils.js as well:

JavaScript
 




xxxxxxxxxx
1
14


 
1
  function getTranslation(key, handlerInput, replaceObjects) {
2
 
          
3
        const { attributesManager } = handlerInput;
4
        const sessionAtributes = attributesManager.getSessionAttributes();
5
        const terms = sessionAtributes['translations'].terms;
6
 
          
7
        for(var i = 0; i < terms.length; i++){
8
            t = terms[i];
9
            if(t.term === key){
10
                return sprintfJs.sprintf(t.translation.content, replaceObjects);
11
            }
12
        }
13
 
          
14
    }


Now we can call this function wherever we want in our Alexa Skill:

JavaScript
 




x
18


1
  const Alexa = require('ask-sdk-core');
2
  const i18nUtils = require('../utilities/i18nUtils');
3
 
          
4
  module.exports = {
5
      LaunchRequestHandler: {
6
          canHandle(handlerInput) {
7
              return Alexa.getRequestType(handlerInput.requestEnvelope) === 'LaunchRequest';
8
          },
9
          handle(handlerInput) {
10
              const speakOutput = i18nUtils.getTranslation('WELCOME_MSG', handlerInput);
11
              
12
              return handlerInput.responseBuilder
13
                  .speak(speakOutput)
14
                  .reprompt(speakOutput)
15
                  .getResponse();
16
          }
17
      }
18
  };


This function supports string replacement like the i18next package. In this case, I am using the npm package sprintf-js:

JavaScript
 




x


1
  const Alexa = require('ask-sdk-core');
2
  const i18nUtils = require('../utilities/i18nUtils');
3
 
          
4
  /* *
5
  * The intent reflector is used for interaction model testing and debugging.
6
  * It will simply repeat the intent the user said. You can create custom handlers for your intents 
7
  * by defining them above, then also adding them to the request handler chain below 
8
  * */
9
  module.exports = {
10
      IntentReflectorHandler: {
11
          canHandle(handlerInput) {
12
              return Alexa.getRequestType(handlerInput.requestEnvelope) === 'IntentRequest';
13
          },
14
          handle(handlerInput) {
15
            
16
              const intentName = Alexa.getIntentName(handlerInput.requestEnvelope);
17
            
18
              const speakOutput = i18nUtils.getTranslation('REFLECTOR_MSG', handlerInput, {intentName: intentName});
19
 
          
20
              return handlerInput.responseBuilder
21
                  .speak(speakOutput)
22
                  .getResponse();
23
          }
24
      }
25
  };


Saving Translations in the Alexa Skill

In order to not to download the translations every time we run the Skill, we will persist them to DynamoDB following this flow:

Translation persistence

This flow is implemented on the saveAttributesResponseInterceptor intercetpor:

JavaScript
 




x
51


 
1
 const Alexa = require('ask-sdk-core');
2
  var moment = require('moment');
3
 
          
4
  // This request interceptor will bind a translation function 't' to the handlerInput
5
  module.exports = {
6
    SaveAttributesResponseInterceptor: {
7
      async process(handlerInput, response) {
8
        
9
        if (!response) return; // avoid intercepting calls that have no outgoing response due to errors
10
        const { attributesManager, requestEnvelope } = handlerInput;
11
        const sessionAtributes = attributesManager.getSessionAttributes();
12
        const translations = sessionAtributes['translations'];
13
        const downloaded = sessionAtributes['translations'].downloaded;
14
 
          
15
          if (downloaded) {
16
 
          
17
            persitentAttributes = await attributesManager.getPersistentAttributes();
18
 
          
19
            
20
            const locale = Alexa.getLocale(requestEnvelope);
21
            const ISOlocale = locale.split('-')[0];
22
            const timestamp = moment().toISOString();
23
 
          
24
            if (!('translations' in persitentAttributes)
25
                || (('translations' in persitentAttributes) && !(ISOlocale in persitentAttributes.translations))) {
26
 
          
27
              var saveObject = {};
28
              
29
              saveObject[ISOlocale] = {
30
                timestamp: timestamp,
31
                strings: translations,
32
              };
33
              persitentAttributes['translations'] = saveObject;
34
 
          
35
            } else {
36
                //Set values
37
                persitentAttributes.translations[ISOlocale].timestamp = timestamp;
38
                persitentAttributes.translations[ISOlocale].strings = translations;
39
            }
40
            
41
            console.log(
42
              'Saving to persistent storage:' + JSON.stringify(persitentAttributes)
43
            );
44
            //Persist values
45
            attributesManager.setPersistentAttributes(persitentAttributes);
46
 
          
47
            await attributesManager.savePersistentAttributes();
48
          }
49
      },
50
    },
51
  };


Running the Skill and DynamoDB Locally with Visual Studio Code

The launch.json file in .vscode folder has the configuration for Visual Studio Code which allow us to run our lambda locally:

JSON
 




x
26


1
{
2
  "version": "0.2.0",
3
  "configurations": [
4
    {
5
      "type": "node",
6
      "request": "launch",
7
      "name": "Launch Skill",
8
      "env": {
9
        "DYNAMODB_LOCAL": "true"
10
      },
11
      // Specify path to the downloaded local adapter(for nodejs) file
12
      "program": "${workspaceRoot}/lambda/custom/local-debugger.js",
13
      "args": [
14
        // port number on your local host where the alexa requests will be routed to
15
        "--portNumber",
16
        "3001",
17
        // name of your nodejs main skill file
18
        "--skillEntryFile",
19
        "${workspaceRoot}/lambda/custom/index.js",
20
        // name of your lambda handler
21
        "--lambdaHandler",
22
        "handler"
23
      ]
24
    }
25
  ]
26
}


This configuration file will execute the following command:

JavaScript
 




x


1
  node --inspect-brk=28448 lambda\custom\local-debugger.js --portNumber 3001 --skillEntryFile lambda/custom/index.js --lambdaHandler handler
2
 
          


This configuration uses the local-debugger.js file which runs a TCP server listening on http://localhost:3001

For a new incoming skill request a new socket connection is established. From the data received on the socket the request body is extracted, parsed into JSON and passed to the skill invoker's lambda handler. The response from the lambda handler is parsed as a HTTP 200 message format as specified here The response is written onto the socket connection and returned.

After configuring our launch.json file and understanding how the local debugger works, it is time to click on the play button:

Execution

After executing it, you can send Alexa POST requests to http://localhost:3001.

NOTE: If you want to start the local DynamoDB you have to set to true the environment variable DYNAMODB_LOCAL in this file.

Debugging and Testing the Skill with Visual Studio Code

Following the steps before, now you can set up breakpoints wherever you want inside all JS files in order to debug your skill.

In my post talking about Node.js Skill you can see how to test your Skill either directly with Alexa Developer Console or locally with Postman.

Checking the Local DynamoDB

When we are running the DynamoDB locally, this local instance we will set up a shell in http://localhosta:8000/shell

Local DynamoDB

In that shell we can execute queries in order to check the content of our local database. These are some example of queries you can do:

  1. Get all the content of our table:
JavaScript
 




x


 
1
//GET ALL VALUES FROM TABLE
2
 
          
3
var params = {
4
  TableName: "exampleTable",
5
 
          
6
  Select: "ALL_ATTRIBUTES", // optional (ALL_ATTRIBUTES | ALL_PROJECTED_ATTRIBUTES |
7
  //           SPECIFIC_ATTRIBUTES | COUNT)
8
  ConsistentRead: false, // optional (true | false)
9
  ReturnConsumedCapacity: "NONE", // optional (NONE | TOTAL | INDEXES)
10
};
11
 
          
12
AWS.config.update({
13
  region: "local",
14
  endpoint: "http://localhost:8000",
15
  accessKeyId: "fake",
16
  secretAccessKey: "fake",
17
});
18
 
          
19
var dynamodb = new AWS.DynamoDB();
20
 
          
21
dynamodb.scan(params, function (err, data) {
22
  if (err) ppJson(err);
23
  // an error occurred
24
  else ppJson(data); // successful response
25
});


Then we can show the data of the table:

Table data

  1. Get the information of our table:
JavaScript
 




x


1
//GET TABLE INFORMATION
2
var params = {
3
  TableName: "exampleTable",
4
};
5
 
          
6
AWS.config.update({
7
  region: "local",
8
  endpoint: "http://localhost:8000",
9
  accessKeyId: "fake",
10
  secretAccessKey: "fake",
11
});
12
 
          
13
var dynamodb = new AWS.DynamoDB();
14
 
          
15
dynamodb.describeTable(params, function (err, data) {
16
  if (err) ppJson(err);
17
  // an error occurred
18
  else ppJson(data); // successful response
19
});


Now we can show the information of our table:

Table information

These queries are using the AWS SDK for JavaScript.

This local DynamoDB is accessible by the AWS CLI as well. Before using the CLI, we need to create a fake profile that will use the region, accessKeyId and secretAccessKey used by our local database and client. So in our ~/.aws/credentials we have to create the fake profile:

Properties files
 




x


 
1
  [fake]
2
  aws_access_key_id=fake
3
  aws_secret_access_key=fake


And in our ~/.aws/config we set the local region for our fake profile:

Properties files
 




x


 
1
  [fake]
2
  region = local


After creating it, now we can execute queries using the AWS CLI using our fake profile:

Shell
 




x


1
  aws dynamodb list-tables --endpoint-url http://localhost:8000 --region local --profile fake
2
 
          


This command will return a list of tables in our local database:

JSON
 




x


 
1
{
2
  "TableNames": ["exampleTable"]
3
}


You can find more information about how to make queries with the AWS CLI here

Conclusion

Internationalization takes place as a fundamental step in the design and development process, rather than as a subsequent addition, which can often involve a difficult and expensive process of reengineering. We have to take the correct decision in terms of i18n in the beginning of our development process.

POEditor is freemium and you can start for free with 1,000 strings. POEditor is not so expensive, with very affordable prices. You can check it here.

I hope this example project is useful to you.

You can find the code in my GitHub.

That's all folks!

Happy coding!

Topics:
alexa, alexa app development, alexa skill, alexa skill development, alexa skills, alexa skills developer, alexa skills development, i18n, javascript, node

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}