LoginSignup
34
36

More than 3 years have passed since last update.

AlexaスキルをPython/Lambdaで実装する

Posted at

AlexaスキルをPython/Lambdaで実装する

はじめに

Mac環境の記事ですが、Windows環境も同じ手順になります。環境依存の部分は読み替えてお試しください。

目的

この記事を最後まで読むと、次のことができるようになります。

  • Alexaスキルを作成する
  • AWS Lambdaを構築する

Alexaシミュレータ

スクリーンショット 2019-09-09 21.08.01.png

関連する記事

実行環境

環境 Ver.
macOS Mojave 10.14.6
Python 3.7.3
ask-sdk 1.11.0

ソースコード

実際に実装内容やソースコードを追いながら読むとより理解が深まるかと思います。是非ご活用ください。

GitHub

事前準備

Amazon Developerアカウントの作成

Amazon AlexaログインからAmazon Developerアカウントを作成する

AWSアカウントの作成

AWSコンソールにサインインからAWSアカウントを作成する

skill.zipの作成

tree.sh
pj_folder
└── fortune_telling.py
fortune_telling.py
import random

from ask_sdk_core.handler_input import HandlerInput
from ask_sdk_core.skill_builder import SkillBuilder
from ask_sdk_core.utils import get_slot_value, is_intent_name, is_request_type
from ask_sdk_model import Response
from ask_sdk_model.ui import SimpleCard

sb = SkillBuilder()


@sb.request_handler(can_handle_func=is_request_type("LaunchRequest"))
def launch_request_handler(handler_input):
    # type: (HandlerInput) -> Response
    speech_text = "今日の運勢を占いますか? (はい/いいえ)"

    handler_input.response_builder.speak(speech_text).set_card(
        SimpleCard("Fortune Telling", speech_text)).set_should_end_session(
        False)
    return handler_input.response_builder.response


@sb.request_handler(can_handle_func=is_intent_name("FortuneTellingIntent"))
def fortune_telling_intent_handler(handler_input):
    # type: (HandlerInput) -> Response
    yes_no = get_slot_value(handler_input=handler_input, slot_name="continue")
    if yes_no == 'はい':
        num = random.randint(0, 9)
        if num >= 0 and num <= 2:
            speech_text = "大吉ですねっ!ホッとした。"
        elif num >= 3 and num <= 6:
            speech_text = "小吉かぁ。微妙な1日。"
        else:
            speech_text = "大凶ですよ。はい残念!"
        speech_text = '{} 続けますか? (はい/いいえ)'.format(speech_text)
        end_session = False
    elif yes_no == 'いいえ':
        speech_text = "ほな、さいならー"
        end_session = True
    else:
        speech_text = "えっなんて?"
        end_session = False

    handler_input.response_builder.speak(speech_text).set_card(
        SimpleCard("Fortune Telling", speech_text)).set_should_end_session(end_session)
    return handler_input.response_builder.response


@sb.request_handler(can_handle_func=is_intent_name("AMAZON.HelpIntent"))
def help_intent_handler(handler_input):
    # type: (HandlerInput) -> Response
    speech_text = "こんにちは。と言ってみてください。"

    handler_input.response_builder.speak(speech_text).ask(speech_text).set_card(
        SimpleCard("Fortune Telling", speech_text))
    return handler_input.response_builder.response


@sb.request_handler(
    can_handle_func=lambda handler_input:
        is_intent_name("AMAZON.CancelIntent")(handler_input) or
        is_intent_name("AMAZON.StopIntent")(handler_input))
def cancel_and_stop_intent_handler(handler_input):
    # type: (HandlerInput) -> Response
    speech_text = "さようなら"

    handler_input.response_builder.speak(speech_text).set_card(
        SimpleCard("Fortune Telling", speech_text))
    return handler_input.response_builder.response


@sb.request_handler(can_handle_func=is_request_type("SessionEndedRequest"))
def session_ended_request_handler(handler_input):
    # type: (HandlerInput) -> Response

    return handler_input.response_builder.response


@sb.exception_handler(can_handle_func=lambda i, e: True)
def all_exception_handler(handler_input, exception):
    # type: (HandlerInput, Exception) -> Response
    print(exception)

    speech = "すみません、わかりませんでした。もう一度言ってください。"
    handler_input.response_builder.speak(speech).ask(speech)
    return handler_input.response_builder.response


handler = sb.lambda_handler()
skill.sh
cd pj_folder
mkdir skill
cd skill
cp fortune_telling.py skill/
pip install ask-sdk-core -t .
zip ../skill.zip -r .
tree.sh
pj_folder
├── fortune_telling.py
├── skill
└── skill.zip

Alexaスキルの作成

  1. 占いスキル(FortuneTelling)を作成する

    Alexa Developer Consoleを開く > スキルの作成をクリック

    スクリーンショット 2019-09-09 19.50.25.png

    以下を入力/選択してスキルの作成をクリック

    • スキル名にFortuneTellingを入力
    • スキルに追加するモデルを選択でカスタムを選択
    • スキルのバックエンドリソースをホスティングする方法を選択でユーザー定義のプロビジョニングを選択

    スクリーンショット 2019-09-09 19.51.07.png

  2. 呼び出し名を設定する

    呼び出し名に占いくんを入力

    スクリーンショット 2019-09-09 20.02.32.png

  3. スロットタイプを作成する

    スロットタイプをクリック > スロットタイプにcontinueTypeを入力 > カスタムスロットタイプを作成をクリック

    スロット値にはいいいえを追加

    スクリーンショット 2019-09-09 20.08.41.png

  4. インテントを作成する

    インテントを追加をクリック > FortuneTellingIntentを入力 > カスタムインテントを作成をクリック

    インテントスロットにcontinueを追加 > スロットタイプにcontinueTypeを入力

    スクリーンショット 2019-09-09 20.16.09.png

    サンプル発話に{continue}を追加

    スクリーンショット 2019-09-09 20.19.11.png

  5. JSONエディターで設定内容を確認する

    json_editor.json
    {
        "interactionModel": {
            "languageModel": {
                "invocationName": "占いくん",
                "intents": [
                    {
                        "name": "AMAZON.CancelIntent",
                        "samples": []
                    },
                    {
                        "name": "AMAZON.HelpIntent",
                        "samples": []
                    },
                    {
                        "name": "AMAZON.StopIntent",
                        "samples": []
                    },
                    {
                        "name": "AMAZON.NavigateHomeIntent",
                        "samples": []
                    },
                    {
                        "name": "FortuneTellingIntent",
                        "slots": [
                            {
                                "name": "continue",
                                "type": "continueType"
                            }
                        ],
                        "samples": [
                            "{continue}"
                        ]
                    }
                ],
                "types": [
                    {
                        "name": "continueType",
                        "values": [
                            {
                                "name": {
                                    "value": "いいえ"
                                }
                            },
                            {
                                "name": {
                                    "value": "はい"
                                }
                            }
                        ]
                    }
                ]
            }
        }
    }
    

AWS Lambdaの構築

  1. 関数を作成する

    AWS マネジメントコンソールを開く > サービスをクリック > Lambdaをクリック > 関数の作成をクリック

    オプションで一から作成を選択 > 関数名にFortuneTellingを入力 > ランタイムでPython 3.7を選択 > 関数の作成をクリック

    スクリーンショット 2019-09-09 20.28.55.png

  2. トリガーを設定する

    作成したスキルのエンドポイントを開く > AWS LambdaのARNをクリック > スキルIDをコピー

    スクリーンショット 2019-09-09 20.31.39.png

    作成した関数のトリガーを追加をクリック > トリガーを選択でAlexa Skills Kitを選択 > スキルID検証で有効を選択 > スキルIDに先ほどコピーしたスキルIDを入力 > 追加をクリック

    スクリーンショット 2019-09-09 20.37.15.png

  3. 関数コードを設定する

    ブラウザを更新 > コード エントリ タイプで.zip ファイルをアップロードを選択 > アップロードをクリック > 事前に準備したskill.zipを選択 > ハンドラにfortune_telling.handlerを入力 > 保存をクリック

    スクリーンショット 2019-09-09 20.54.31.png

  4. エンドポイントを設定する

    作成した関数のARNをコピー

    スクリーンショット 2019-09-09 20.58.09.png

    作成したスキルのエンドポイントを開く > AWS LambdaのARNをクリック > デフォルトの地域に先ほどコピーしたARNを入力 > エンドポイントを保存をクリック

    スクリーンショット 2019-09-09 21.02.24.png

  5. モデルをビルドする

    モデルを保存をクリック > モデルをビルドをクリック

    スクリーンショット 2019-09-09 21.04.34.png

Alexaスキルのテスト

テストをクリック > 開発中をクリック > 占いくんを入力 > はい or いいえを入力

スクリーンショット 2019-09-09 21.08.01.png

34
36
0

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
34
36