LoginSignup
6
2

More than 5 years have passed since last update.

Alexaのカスタムスキルを作る(その2)

Last updated at Posted at 2017-12-15

前回の
https://qiita.com/miutex/items/ff09b2f171be1588ce7b

この記事でやること

  • zaif APIをコールし価格取得
  • 実機テスト

zaif APIをコールし価格取得

ここはちゃっちゃとやっちゃいます。
価格取得するだけであればAPI Key不要でgetで簡単に取れるのが嬉しいですね。

index.js
const handlers = {
    'btcIntent': function () {
        let http = require('https');
        var URL = 'https://api.zaif.jp/api/1/last_price/'+this.event.request.intent.slots["crypt"]["value"]+'_jpy';
        console.log(URL);

        http.get(URL, (res) => {
            res.setEncoding('utf8');

            res.on('data', (chunk) => {
                var parsedValue = JSON.parse(chunk);
                var key1 = "last_price";
                console.log(parsedValue);
                console.log(parsedValue[key1]);
                this.emit(':tell', String(parsedValue['last_price']) + 'えんです');
            });

        }).on('error', (e) => {
            console.log(e.message); //エラー時
            this.emit(':tell', 'エラーです'+e.message);
        });
    },
    'Unhandled': function () {
        this.attributes.speechOutput = this.t('HELP_MESSAGE');
        this.attributes.repromptSpeech = this.t('HELP_REPROMPT');
        this.emit(':ask', this.attributes.speechOutput, this.attributes.repromptSpeech);
    },
};

※全ソースを載せていないので、見たい方はその1を参考にしてください。

レスポンス

response
{
  "version": "1.0",
  "response": {
    "outputSpeech": {
      "ssml": "<speak> 1936110えんです </speak>",
      "type": "SSML"
    },
    "speechletResponse": {
      "outputSpeech": {
        "ssml": "<speak> 1936110えんです </speak>"
      },
      "shouldEndSession": true
    }
  },
  "sessionAttributes": {}
}

キタ━━━━(゚∀゚)━━━━!!

実機テスト

20171210_01.jpg

ウチの高級目覚まし時計Echo Dot。言うほど高級でもないか。2000円引きだったし。

IMG_7163.PNG

スキルもスマホを開いたら既に設定されていて、特別何もしなくても大丈夫でした。
jpのアカウントでログインしているので、カスタムスキルをusのアカウントで作るなどしていると、この辺りが上手くいかないはず。

Synonymsが期待通りに動作しない?(勘違い)

早速実機でテスト
「アレクサ、びっとこいんそうばでびっとこいんはいくら?」
「undefinedえんです」
???

ログを確認。ログはLambda側に仕込んでCloudWatchから見ています。

crypt:
{
  name: 'crypt',
  value: 'びっとこいん',
  resolutions: 
  { 
    resolutionsPerAuthority: 
    [ { 
      authority: 'amzn1.er-authority.echo-sdk.amzn1.ask.skill.*****.CRYPT_LIST',
      status: 
      { 
        code: 'ER_SUCCESS_MATCH' 
      },
      values: [ { 
        value: { name: 'btc', id: '****************' }
      } ] 
    } ] 
  },
  confirmationStatus: 'NONE' 
}

マニュアルちゃんと読んでから作らない自分が悪いのですが、Slot解決がされる場合、格納場所が異なるようです。
ソースを改修します。

index.js
const handlers = {
    'btcIntent': function () {
        var unit = this.event.request.intent.slots["crypt"]["value"]; //default
        if('resolutions' in this.event.request.intent.slots["crypt"]) {
            if(this.event.request.intent.slots["crypt"]["resolutions"]["resolutionsPerAuthority"][0]["status"]["code"] == 'ER_SUCCESS_MATCH') {
                unit = this.event.request.intent.slots["crypt"]["resolutions"]["resolutionsPerAuthority"][0]["values"][0]["value"]["name"];
            }
        }

        let http = require('https');
        var URL = 'https://api.zaif.jp/api/1/last_price/'+unit+'_jpy';

        http.get(URL, (res) => {
            res.setEncoding('utf8');

            res.on('data', (chunk) => {
                var parsedValue = JSON.parse(chunk);
                var key1 = "last_price";
                console.log(parsedValue);
                console.log(parsedValue[key1]);
                this.emit(':tell', String(parsedValue['last_price']) + 'えんです');
            });

        }).on('error', (e) => {
            console.log(e.message); //エラー時
            this.emit(':tell', 'エラーです'+e.message);
        });
    },
    'Unhandled': function () {
        this.attributes.speechOutput = this.t('HELP_MESSAGE');
        this.attributes.repromptSpeech = this.t('HELP_REPROMPT');
        this.emit(':ask', this.attributes.speechOutput, this.attributes.repromptSpeech);
    },
};

SimulatorでSlot解決がされない場合にも動作するよう、デフォルト値にはvalueを入れてあります。

期待通りに動くようになりました。めでたしめでたし。

おまけ:echoism.ioについて

Alexaには管理画面の文字ベースでのSimulatorの他に
実際に声をかけて返してくれるものがあります。
https://echosim.io/

スクリーンショット 2017-12-15 12.07.29.png

こちらで試すとSlot解決も対応しているので、デバッグするのに助かりますね。

以上です

6
2
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
2