LoginSignup
1
0

More than 3 years have passed since last update.

【初心者向け】LambdaでAlexaカスタムスキルと連携する関数を作成

Last updated at Posted at 2020-03-02

Lambdaで関数を作成

AWS Lamdaで関数の作成手順

前の記事:Alexaでカスタムスキルを作成する

AWSのサービス一覧から「Lambda」を選択

1-1.png

Lambdaトップ画面より「関数の作成」を押下

1-2.png

関数の基本情報を設定

  • 「一から作成」を選択
  • 「関数名」を入力 →今回は"sampleFunction"としました
  • 「ランタイム」では「Python3.8」を選択
  • 「関数の作成」を押下 1-3.png

作成成功メッセージ

作成が成功すると上部にメッセージが表示され、コード入力画面が表示されます
1-4.png

関数を作成

関数コードに動作が確認可能なサンプルコードを入力します

lambda_function.py
import json
import base64

def lambda_handler(event, context):

    if event['request']['type'] == "IntentRequest":
        # トークンを取得してピリオドで分割
        token = event['session']['user']['accessToken'].split('.')
        # トークンをデコードしてjson形式へ
        payload =json.loads(base64.urlsafe_b64decode(token[1] + '=' * (-len(token[1]) % 4)).decode(encoding='utf-8'))
        session_attributes = {}
        card_title = "こんにちは。あなたのIDは" + payload['username'] + "です"
        speech_output = "こんにちは。あなたのIDは" + payload['username'] + "です"
        reprompt_text = "こんにちは。あなたのIDは" + payload['username'] + "です"

        should_end_session = True

        return build_response(session_attributes, build_speechlet_response(
            card_title, speech_output, reprompt_text, should_end_session))

    else:
        session_attributes = {}
        card_title = "サンプルスキルを開きました"
        speech_output = "サンプルスキルを開きました"
        reprompt_text = "サンプルスキルを開きました"

        should_end_session = False

        return build_response(session_attributes, build_speechlet_response(
            card_title, speech_output, reprompt_text, should_end_session))

def build_response(session_attributes, speechlet_response):
    return {
        'version': '1.0',
        'sessionAttributes': session_attributes,
        'response': speechlet_response
    }

def build_speechlet_response(title, output, reprompt_text, should_end_session):
    return {
        'outputSpeech': {
            'type': 'PlainText',
            'text': output
        },
        'card': {
            'type': 'Simple',
            'title': "SessionSpeechlet - " + title,
            'content': "SessionSpeechlet - " + output
        },
        'reprompt': {
            'outputSpeech': {
                'type': 'PlainText',
                'text': reprompt_text
            }
        },
        'shouldEndSession': should_end_session
    }

1-5.png

次の記事

関連記事

1
0
1

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
1
0