(Updated to v2 ask-cli)
https://github.com/javichur/alexa-skill-clean-code-template
Alexa Skill Template with clean code (eslint, sonar), testing (unit tests, e2e), multi-language, Alexa Presentation Language (APL), In-Skill Purchases support (ISP) and more.
Made with ❤️ by Javier Campos (https://javiercampos.es) Available on the [AWS Serverless Application Repository].
- 💾📂 Load and save info from/to session (LoadSessionIntent, SaveSessionIntent).
- 💾📂 Load and save data from/to Dynamodb (LoadDynamoDBIntent, SaveDynamoDBIntent).
- ☁️ Using external APIs (UseApiIntent).
- 🧘 Get user info like name, email or phone (CheckPermisionsIntent).
- 🧱 Using built-in slots (ColorIntent).
- 📺 APL touch support (ListadoItemSelected).
- 💰 In-Skill Purchases: Subscriptions and One-Time purchases (WhatCanIBuyIntent, TellMeMoreAboutProductIntent, BuyIntent, PurchaseHistoryIntent, RefundProductIntent; BuyResponseHandler and CancelProductResponseHandler).
- 🐛 FallbackIntent to respond gracefully to unexpected customer requests (AMAZON.FallbackIntent).
- ⛓️ Chaining intents sample (ChainingIntent).
- 💃 Dynamic entities / slots (UpdateJokeCategoriesIntent, ClearDynamicEntitiesIntent).
- 📍 Geolocation and Alexa Auto sample intents (AreYouACarIntent), to get speed, altitude, latitude, longitude, and check if automotive.
- 📽️ Play videos in Echo Show devices / display devices.
- And more...
-
Install ASK CLI (
npm install -g ask-cli) -
For Windows users, please fix Powershell problem once (more info https://github.com/alexa/ask-cli/blob/develop/docs/FAQ.md#q-for-windows-users-if-your-skill-return-empty-response-and-log-shows-module-not-found-genericerrormapper-or-cannot-find-module-dispatchererrormappergenericerrormapper-how-to-resolve):
Install-Module Microsoft.PowerShell.Archive -MinimumVersion 1.2.3.0 -Repository PSGallery -Force -Scope CurrentUser
Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser-
Install Visual Code (https://code.visualstudio.com/)
-
(Do not use this vscode extension with ask-cli v2)
Install Alexa Skill Kit (ASK) Toolkit for vscode (https://marketplace.visualstudio.com/items?itemName=ask-toolkit.alexa-skills-kit-toolkit) -
You must edit ~/.aws/credentials file to add a valid AWS profile (aws_access_key_id, aws_secret_access_key) with the following policy. You must create a IAM user with this policy (https://console.aws.amazon.com/iam/):
{
"Version": "2012-10-17",
"Statement": {
"Effect": "Allow",
"Action": [
"iam:CreateRole",
"iam:GetRole",
"iam:AttachRolePolicy",
"iam:PassRole",
"lambda:AddPermission",
"lambda:CreateFunction",
"lambda:GetFunction",
"lambda:UpdateFunctionCode",
"lambda:ListFunctions",
"lambda:UpdateFunctionConfiguration",
"logs:FilterLogEvents",
"logs:getLogEvents",
"logs:describeLogStreams"
],
"Resource": "*"
}
}More info:
- https://developer.amazon.com/es/docs/smapi/manage-credentials-with-ask-cli.html
- https://docs.aws.amazon.com/es_es/cli/latest/userguide/cli-chap-configure.html
- Configure ASK CLI with AWS profile (credentials):
ask configure(The old ask init command has been removed in ask-cli v2).
- Create a new skill from this template (https://github.com/javichur/alexa-skill-clean-code-template):
ask new --template-url https://github.com/javichur/alexa-skill-clean-code-template.git --template-branch master
? Choose a method to host your skill's backend resources: AWS Lambda
? Would you like to continue download the skill template? Yes
? Please type in your skill name: my-new-skill
? Please type in your folder name for the skill project (alphanumeric): my-new-skill
Project for skill "my-new-skill" is successfully created at \my-new-skill
Project initialized with deploy delegate "@ask-cli/lambda-deployer" successfully.(The old command ask new --url has been removed in ask-cli v2).
-
Select your AWS region and nodejs version in
ask-resources.jsonfile. -
Install dependencies:
cd my-new-skill/lambda/custom
npm install-
Develop your awesome Alexa Skill! Take advantage of this template!
-
Deploy the skill easily with cli:
cd my-new-skill
ask deploy- Test your skill:
ask dialog -l en-US
> Alexa, open <your invocation name>- Deploy the skill easily with cli:
ask deploy-
Multi-language. Add text strings for all languages in
stringsfolder. -
Handlers organized in the
/handlersfolder to quickly find the samples: API calls, chaining intents, APL touch events, dynamic entities, dynamoDB, session, in skill purchases (ISP), get user permissions, other global handlers... -
Control your Code Style using Airbnb eslint rules:
npm run eslint- Control the quality of your code using SonarQube (I assume Sonar running on localhost:9000):
npm run sonar
start http://localhost:9000/dashboard?id=my-new-skill- Use vscode and press
F5to start Unit Tests and debug with breakpoints in your code.
Or use npm run unit-test
- Run e2e tests. Use
npm run e2e-test. You must get a free access token for a virtual device in https://apps.bespoken.io/dashboard/virtualdevice and paste it intesting.jsonfile.
- Configure ASK CLI with AWS profile (credentials):
ask configureYou must edit ~/.aws/credentials file to add a valid AWS profile (aws_access_key_id, aws_secret_access_key, region). More info: https://docs.aws.amazon.com/es_es/cli/latest/userguide/cli-chap-configure.html
- Create a new skill from
Hello Worldtemplate (https://github.com/alexa/skill-sample-nodejs-hello-world):
ask new
? Please select the runtime Node.js V8
? List of templates you can choose Hello World
? Please type in your skill name: alexa-skill-clean-code-templateThe .ask/config file will be contain:
{
"deploy_settings": {
"default": {
"skill_id": "",
"was_cloned": false,
"merge": {}
}
}
}- Edit
skill.jsonto deploy Lambda function in Europe:
"apis": {
"custom": {
"endpoint": {
"sourceDir": "lambda/custom",
"uri": "ask-custom-clean-code-skill-template-default"
},
"regions": {
"EU": {
"endpoint": {
"sourceDir": "lambda/custom",
"uri": "ask-custom-clean-code-skill-template-default"
}
}
}
}
}- Deploy
ask deployOr deploy only Lambda function
ask deploy lambdaThe ask deploy command invokes hooks in order to install dependencies.
-
Test interaction model using
Utterance Profiler(https://developer.amazon.com/alexa/console/ask) -
Test your skill using interactive
ask dialog
ask dialog --locale "en-US"
User > Alexa, open hello world
Alexa > Welcome to the Alexa Skills Kit, you can say hello!
User > help
Alexa > You can say hello to me!
User > hello
Alexa > Hello World!-
Test your skill using simulator (https://developer.amazon.com/alexa/console/ask)
-
(Removed in ASK-CLI V2) Test JSON request/response using
ask simulate
(Removed) ask simulate --locale "en-US" --text "start hello world"- Automating Unit Tests using Bespoken Tools.
.vscode/launch.jsonedited.
npm install bespoken-tools --save-devAnd press F5 to start Unit Tests. Or use npm run unit-test
- Clean code. ESLINT (with airbnb rules) + Sonar added. See root package.json
npm run eslint
npm run sonar-eslint-
Locale. Add
addRequestInterceptors()interceptor. -
Add text strings for all languages in
stringsfolder. -
Add
es-ESlanguage inskill.json. -
Refactor handlers. See
/handlers/globalHandlers.js. -
IntentReflectorHandleradded. -
Add APL support in Skill Manifest (https://developer.amazon.com/es/docs/alexa-presentation-language/apl-select-the-viewport-profiles-your-skill-supports.html).
"interfaces": [
{
"type": "ALEXA_PRESENTATION_APL",
"supportedViewports": [
{
"mode": "HUB",
"shape": "ROUND",
"minWidth": 480,
"maxWidth": 480,
"minHeight": 480,
"maxHeight": 480
},
{
"mode": "HUB",
"shape": "RECTANGLE",
"minWidth": 1024,
"maxWidth": 1024,
"minHeight": 600,
"maxHeight": 600
},
{
"mode": "HUB",
"shape": "RECTANGLE",
"minWidth": 1280,
"maxWidth": 1280,
"minHeight": 800,
"maxHeight": 800
},
{
"mode": "TV",
"shape": "RECTANGLE",
"minWidth": 960,
"maxWidth": 960,
"minHeight": 540,
"maxHeight": 540
},
{
"mode": "HUB",
"shape": "RECTANGLE",
"minWidth": 960,
"maxWidth": 960,
"minHeight": 480,
"maxHeight": 480
}
]
}
],-
Add APL templates
/apl. -
Use APL with custom layoyts (
VerticalListItemindocumentListado.json). -
Use APL events (
headerNavigationActionandTouchWrapper.onPressindocumentListado.json). -
Access to DynamoDB using dynamola library.
npm install dynamola --saveUse it:
const Dynamola = require('dynamola');
let myDb = new Dynamola('dynamodb-table-name', 'dynamodb-primary-key-name', null);
myDb.getItem(userID).then((data) => {
if(!data){
// item doesn't exist
}
else {
// item returned OK
}
})
.catch((err) => {
// error reading dynamodb
});To access the DynamoDB database:
I. Configure the name of the table and the name of the primary key in the "settings.js" file.
II. Verify that you have created the database in dynamodb.
III. You can create a test table using the dynamodb-create-sample-table.js script. You will need access permissions to DynamoDB where you run that script.
IV. Verify that you have assigned the necessary permissions for the lambda function to get read/write access to the dynamodb table. Get more info here: https://github.com/javichur/dynamola
-
Work with session. See
/data/sessionState.js, and following intents:SaveSessionIntentandLoadSessionIntent. -
Access to external APIs. Check
/data/api.jsandUseApiRequestHandler(index.js). -
Mock info
/data/mocks. -
Tests e2e added. Use
npm run e2e-test. You must get a free access token for a virtual device in https://apps.bespoken.io/dashboard/virtualdevice and paste it intesting.jsonfile. -
Deploy using Alias and Lambda versions. // TODO
-
Use permissions to get info about the user (name, phone number or email). Add the following code in
skill.jsonand tryCheckPermisionsIntentsample.
"permissions": [
{
"name": "alexa::profile:given_name:read"
},
{
"name": "alexa::profile:email:read"
},
{
"name": "alexa::profile:mobile_number:read"
}
]-
In-Skill Purchases added. Check
\handlers\purchaseHandlers.js,index.jsand voice models. New intents have been included: WhatCanIBuyIntent, TellMeMoreAboutProductIntent, BuyIntent, PurchaseHistoryIntent, RefundProductIntent; BuyResponseHandler and CancelProductResponseHandler. -
Geolocation and automotive features. Use
AreYouACarIntentto get this info in Alexa Auto or Alexa app:
{
"locationServices": {
"status": "RUNNING",
"access": "ENABLED"
},
"timestamp": "2020-06-20T17:37:22Z",
"coordinate": {
"latitudeInDegrees": 0.0,
"longitudeInDegrees": 0.0,
"accuracyInMeters": 15.15
},
"altitude": {
"altitudeInMeters": 123,
"accuracyInMeters": 15.15
},
"heading": {
"directionInDegrees": 0
},
"speed": {
"speedInMetersPerSecond": 123
}
}- Play video feature. Use
PlayVideoIntentto play a video in your Alexa Echo Show devices. To allow playing videos, please activate the VideoApp interface in the developer console:Your alexa skill > Custom > Interfaces > Video App.
- Error invoking
ask deploy: "No se puede cargar el archivo\hooks\pre_deploy_hook.ps1porque la ejecución de scripts está deshabilitada en este sistema". Solution:
Set-ExecutionPolicy -Scope CurrentUser
$> unrestrictedIMPORTANT: If you create a new skill project from a skill template that contains hook scripts, ASK CLI will run them. You should only use skill templates from sources that you trust.
ASK CLI v1 to v2 Migration Guide: https://developer.amazon.com/es-ES/docs/alexa/smapi/ask-cli-v1-to-v2-migration-guide.html
Check ask-cli version:
ask -vAdd testers to a beta test for the given Alexa skill:
ask smapi add-testers-to-beta-test -s <skill-id> --testers-emails <testers-emails-separated-by-commas>Test your alexa skill:
ask dialog -l en-USFor Windows users, please fix the PowerShell problem once if your skill return empty response, and log shows "Module not found: GenericErrorMapper" or "Cannot find module './dispatcher/error/mapper/GenericErrorMapper'" (more info https://github.com/alexa/ask-cli/blob/develop/docs/FAQ.md#q-for-windows-users-if-your-skill-return-empty-response-and-log-shows-module-not-found-genericerrormapper-or-cannot-find-module-dispatchererrormappergenericerrormapper-how-to-resolve):
Install-Module Microsoft.PowerShell.Archive -MinimumVersion 1.2.3.0 -Repository PSGallery -Force -Scope CurrentUser