簡體   English   中英

Alexa提出問題並從外部API獲得響應

[英]Alexa ask a question and get response from external API

我設置了一個簡單的意圖

 { "interactionModel": { "languageModel": { "invocationName": "viva bank", "intents": [ ...builtin intents...{ "name": "ask", "slots": [{ "name": "question", "type": "AMAZON.SearchQuery" }], "samples": [ "when {question}", "how to {question}", "what {question}" ] } ], "types": [] } } } 

但是,當我問一個問題時,它給出了一個像這樣的通用錯誤響應:

我:alexa詢問viva銀行是否收取滯納金

Alexa:對不起,我不知道。

這是我的lambda代碼,但我認為它沒有那么遠。

 'use strict'; const Alexa = require('ask-sdk-core'); var https = require('https'); var querystring = require('querystring'); const APP_ID = 'amzn1.ask.skill.1234'; const AskIntentHandler = { canHandle(handlerInput) { return !!handlerInput.requestEnvelope.request.intent.slots['question'].value; }, handle(handlerInput) { var question = handlerInput.requestEnvelope.request.intent.slots['question'].value; console.log('mydata:', question); var responseString = ''; const subscription_key = 'XXXX'; var data = { simplequery: question, channel: 'Alexa' }; var get_options = { headers: { 'Subscription-Key': subscription_key } }; https.get('https://fakeapi.com/' + querystring.stringify(data), get_options, (res) => { console.log('statusCode:', res.statusCode); console.log('headers:', res.headers); res.on('data', (d) => { responseString += d; }); res.on('end', function(res) { var json_hash = JSON.parse(responseString); // grab the first answer returned as text and have Alexa read it const speechOutput = json_hash['results'][0]['content']['text']; console.log('==> Answering: ', speechOutput); // speak the output return handlerInput.responseBuilder.speak(speechOutput).getResponse(); }); }).on('error', (e) => { console.error(e); return handlerInput.responseBuilder.speak("I'm sorry I ran into an error").getResponse(); }); } }; exports.handler = (event, context) => { const alexa = Alexa.handler(event, context); alexa.APP_ID = APP_ID; alexa.registerHandlers(AskIntentHandler); alexa.execute(); }; 

我真的只是想創建一個非常簡單的傳遞,其中向Alexa詢問一個問題,然后我將其傳遞給外部API並讓Alexa讀取響應。

如果對於intent是必需的,您可以根據需要設置問題槽值,並且您需要包含意圖名稱。 您可以使用async / await來處理API。

const Alexa = require('ask-sdk-core');
const https = require('https');
const querystring = require('querystring');
const { getSlotValue } = Alexa;

const APP_ID = 'amzn1.ask.skill.1234';

const AskIntentHandler = {
  canHandle(handlerInput) {
    return (
      handlerInput.requestEnvelope.request.type === "IntentRequest" &&
      handlerInput.requestEnvelope.request.intent.name === "AskIntent"
    );
  },
  async handle(handlerInput) {
    const question = getSlotValue(handlerInput.requestEnvelope, "question");
    console.log("question ", question);
    const data = await getAnswer(question);
    const speechText = data;
    return handlerInput.responseBuilder
      .speak(speechText)
      .reprompt(speechText)
      .getResponse();
  }
};

const getAnswer = question => {
  const subscription_key = "XXXX";
  let data = {
    simplequery: question,
    channel: "Alexa"
  };
  let get_options = {
    headers: {
      "Subscription-Key": subscription_key
    }
  };
  return new Promise((resolve, reject) => {
    https
      .get(
        "https://fakeapi.com/" + querystring.stringify(data),
        get_options,
        res => {
          console.log("statusCode:", res.statusCode);
          console.log("headers:", res.headers);
          res.on("data", d => {
            responseString += d;
          });

          res.on("end", function(res) {
            var json_hash = JSON.parse(responseString);
            // grab the first answer returned as text and have Alexa read it
            const speechOutput = json_hash["results"][0]["content"]["text"];
            console.log("==> Answering: ", speechOutput);
            resolve(speechOutput);
          });
        }
      )
      .on("error", e => {
        console.error(e);
        resolve("I'm sorry I ran into an error");
      });
  });
};

在AskIntentHandler中,除了檢查問題槽之外,您應該將“canHandle”設置為意圖的名稱。

const AskIntentHandler = {
  canHandle (handlerInput) {
  return handlerInput.requestEnvelope.request.type === 'IntentRequest' &&
      handlerInput.requestEnvelope.request.intent.name === 'AskIntent' &&
      !!handlerInput.requestEnvelope.request.intent.slots['question'].value
  },
  handle (handlerInput) {
     // API Request Here
  }
}

此外,如果始終需要“問題”來運行意圖,您可以設置一個對話框,這樣Alexa會詢問用戶“問題”,如果她不識別。

https://developer.amazon.com/docs/custom-skills/delegate-dialog-to-alexa.html

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM