Alexa ASK CLI を v2 へバージョンアップしてスキルを新規作成



# はじめに

`ASK CLI`が`v2`になったのでインストールしてみた。
本当は、あるAPIの一部がv2にしか対応していなくて仕方なくv2にしたんだけど、すんなりいかなかったのでメモ・・・

新規作成ではなく、`v1` で既にスキルを作っている場合は、 [スキルプロジェクトを v2 用にマイグレーション](https://qiita.com/takara1121/items/a90a5576807d73d8e752)、今はASK CLIを使ってないけど、 `v2` からASK CLIを使用する場合は、[スキルプロジェクトをセットアップする](https://qiita.com/takara1121/items/d0c593c0a37668e6a953)を参照。


# 前提

- ASK CLI v1 がインストールされている

# ASK CLI をv2にバージョンアップ

バージョンアップは簡単。下記コマンドで。

```
npm install -g ask-cli@2
```

2022年5月6日時点でのv2バージョンは2.27.0
2022年1月8日時点でのv2バージョンは2.25.0
2021年1月26日時点でのv2バージョンは2.22.4
2020年4月21日時点でのv2バージョンは2.1.1

```
>ask --version
2.1.1
```

#ask new してみる

何も考えずに`ask new` `ENTER`でよさそう。

```
>ask new
Usage: ask new [options]

create a new skill project from Alexa skill templates

Options:
  --template-url <template-url>  [OPTIONAL] Url for the template to be used with
  -p, --profile <profile>        [OPTIONAL] Provides the ASK CLI profile to use. When you don't include this option,
                                 ASK CLI uses the default profile.
  --debug                        [OPTIONAL] Enables the ASK CLI  to show debug messages in the output of the command.
  -h, --help                     output usage information

C:\work\AlexaSkills\a\test-skill>
```


```:ask&nbsp;new
>ask new

<ENTER>


Please follow the wizard to start your Alexa skill project ->
? Choose the programming language you will use to code your skill:  (Use arrow keys)
> NodeJS
  Python
  Java

<ENTER>


Please follow the wizard to start your Alexa skill project ->
? Choose the programming language you will use to code your skill:  NodeJS
? Choose a method to host your skill's backend resources:
  Alexa-hosted skills
  Host your skill code by Alexa (free).
  AWS with CloudFormation
  Host your skill code with AWS services and provision with AWS CloudFormation (requires AWS account)
> AWS Lambda
  Host your skill code on AWS Lambda (requires AWS account).
  ──────────────
  self-hosted and manage your own hosting  

<ENTER>


? Choose a method to host your skill's backend resources:  AWS Lambda
  Host your skill code on AWS Lambda (requires AWS account).
? Choose a template to start with:  (Use arrow keys)
> Hello world               Alexa's hello world skill to send the greetings to the world!
  Fact skill                Quick sample skill to manage a collection of voice data.                                                                                                                           

<ENTER>


? Choose a template to start with:  Hello world             Alexa's hello world skill to send the greetings to the world!
? Please type in your skill name:  (skill-sample-nodejs-hello-world)
 
<スキル名>を入力後 <ENTER>


? Please type in your skill name:  test-skill
? Please type in your folder name for the skill project (alphanumeric):  (Helloworld)

<スキルプロジェクト名>を入力後 <ENTER>


Project for skill "test-skill" is successfully created at C:\test-skill

Project initialized with deploy delegate "@ask-cli/lambda-deployer" successfully.

>
```

ディレクトリ構成はこんな感じ。
`en-US`なので、`ja-JP`に書き換える。変更はv1の時と同じ。
`HelloWorld`は`v1`の時ように多言語対応版ではなかった。

```:スキルディレクトリ構造（test-skill）
C:test-skill.
│  .gitignore
│  ask-resources.json
│  LICENSE.txt
│
├─.ask
│      ask-states.json
│
├─.github
│      PULL_REQUEST_TEMPLATE.md
│
├─infrastructure
│  └─lambda-deployer
├─lambda
│      index.js
│      package.json
│      util.js
│
└─skill-package
    │  skill.json
    │
    ├─assets
    │      en-US_largeIcon.png
    │      en-US_smallIcon.png
    │
    └─interactionModels
        └─custom
                en-US.json
```

ディレクトリ構造の主な変更点。[詳しくはココ](https://developer.amazon.com/en-US/docs/alexa/smapi/ask-cli-v1-to-v2-migration-guide.html?fbclid=IwAR2w96yfReFrNI8ojqTIY4o0ftxGWDAParBxFe5UC3b2PcqMD6H0VPtal6M)。

|Project component|v1.x|v2.x|
|:--|:--|:--|
|Project configuration|.ask/config|ask-resources.json|
|Skill package|skill.json|skill-package/skill.json|
|   |models/xx-YY.json|skill-package/interactionModels/xx-YY.json|
|   |isps/|skill-package/isps/|
|   |…|…|
|Skill code|lambda/|lambda/|
|Skill hosting infrastructure|N/A|infrastructure/|



# ask deploy してみる

`--target`が無くなっている。

※いつからか忘れたが、復活していた。
--target ： skill-metadata（スキル更新）　または　skill-infrastructure（Lambda更新）　で指定できる。

```
Usage: ask deploy [options]

deploy the skill project

Options:
  -p, --profile <profile>  [OPTIONAL] Provides the ASK CLI profile to use. When you don't include this option, ASK CLI
                           uses the default profile.
  --debug                  [OPTIONAL] Enables the ASK CLI  to show debug messages in the output of the command.
  -h, --help               output usage information
```

```:ask&nbsp;deploy
PS test-skill> ask deploy
==================== Deploy Skill Metadata ====================
/ Uploading the entire skill package (it may take few minutes to build the skill metadata)...
Skill package deployed successfully.
Skill ID: amzn1.ask.skill.1576d476-806c-4316-a4f5-5125f5a46497

==================== Build Skill Code ====================
npm WARN hello-world@1.1.0 No repository field.

Skill code built successfully.
Code for region default built to C:\work\AlexaSkills\a\test-skill\.ask\lambda\build.zip successfully with build flow nodejs-npm.

==================== Deploy Skill Infrastructure ====================
  √ Deploy Alexa skill infrastructure for region "default"
  The api endpoints of skill.json have been updated from the skill infrastructure deploy results.
Skill infrastructures deployed successfully through @ask-cli/lambda-deployer.

==================== Enable Skill ====================
Skill is enabled successfully.
PS test-skill> 
```


# Module not found: GenericErrorMapper エラー 回避

デプロイが成功しているのに、スキルを起動すると、Alexaに「<font color="OrangeRed">スキルがリクエストに正しく応答できませんでした。</font>」と言われ、CloudWatchログに`Cannot find module`エラーが出力されてたら下記を試してみる。

```
2020-04-20T06:17:37.886Z	undefined	ERROR	Uncaught Exception 	
{
    "errorType": "Runtime.ImportModuleError",
    "errorMessage": "Error: Cannot find module './dispatcher/error/mapper/GenericErrorMapper'\nRequire stack:\n- /var/task/node_modules/ask-sdk-runtime/dist/index.js\n- /var/task/node_modules/ask-sdk-core/dist/attributes/AttributesManagerFactory.js\n- /var/task/node_modules/ask-sdk-core/dist/index.js\n- /var/task/index.js\n- /var/runtime/UserFunction.js\n- /var/runtime/index.js",
    "stack": [
        "Runtime.ImportModuleError: Error: Cannot find module './dispatcher/error/mapper/GenericErrorMapper'",
        "Require stack:",
        "- /var/task/node_modules/ask-sdk-runtime/dist/index.js",
        "- /var/task/node_modules/ask-sdk-core/dist/attributes/AttributesManagerFactory.js",
        "- /var/task/node_modules/ask-sdk-core/dist/index.js",
        "- /var/task/index.js",
        "- /var/runtime/UserFunction.js",
        "- /var/runtime/index.js",
        "    at _loadUserApp (/var/runtime/UserFunction.js:100:13)",
        "    at Object.module.exports.load (/var/runtime/UserFunction.js:140:17)",
        "    at Object.<anonymous> (/var/runtime/index.js:43:30)",
        "    at Module._compile (internal/modules/cjs/loader.js:1158:30)",
        "    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1178:10)",
        "    at Module.load (internal/modules/cjs/loader.js:1002:32)",
        "    at Function.Module._load (internal/modules/cjs/loader.js:901:14)",
        "    at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:74:12)",
        "    at internal/main/run_main_module.js:18:47"
    ]
}
```

そのうち修正されると思うが、現時点での回避策はコレみたい。

[Q: For Windows users, if your skill return empty response, and log shows "Module not found: GenericErrorMapper" or "Cannot find module './dispatcher/error/mapper/GenericErrorMapper'", how to resolve?](https://github.com/alexa/ask-cli/blob/develop/docs/FAQ.md?fbclid=IwAR3sUyRt_9jECb7Y-A7dFdjCHkB7IrcafaKvzV3N8kHgItVOms8II_MPVEg#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
```

# おわりに

こんな感じで`test-skill`完成。

![テストスキル](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/426739/fa5e497b-c881-6f91-0e08-4398b2d614e0.png)


# 参考

- [ASK CLI v1 to v2 Migration Guide（※Amazon公式サイト）](https://developer.amazon.com/en-US/docs/alexa/smapi/ask-cli-v1-to-v2-migration-guide.html?fbclid=IwAR2w96yfReFrNI8ojqTIY4o0ftxGWDAParBxFe5UC3b2PcqMD6H0VPtal6M)

#関連

- [Alexa ASK CLI を v2 にして、スキルプロジェクトを v2 用にマイグレーション](https://qiita.com/takara1121/items/a90a5576807d73d8e752)
- [Alexa ASK CLI v2用のスキルプロジェクトをセットアップする](https://qiita.com/takara1121/items/d0c593c0a37668e6a953)