Advertisement
uopspop

Untitled

Apr 20th, 2020
1,375
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. const AWS = require('aws-sdk')
  2.  
  3. var questions = [
  4.     {
  5.         "Reindeer have very thick coats, how many hairs per square inch do they have?": [
  6.             "13,000",
  7.             "1,200",
  8.             "5,000",
  9.             "700",
  10.             "1,000",
  11.             "120,000"
  12.         ]
  13.     },
  14.     {
  15.         "The 1964 classic Rudolph The Red Nosed Reindeer was filmed in:": [
  16.             "Japan",
  17.             "United States",
  18.             "Finland",
  19.             "Germany"
  20.         ]
  21.     },
  22.     {
  23.         "Santas reindeer are cared for by one of the Christmas elves, what is his name?": [
  24.             "Wunorse Openslae",
  25.             "Alabaster Snowball",
  26.             "Bushy Evergreen",
  27.             "Pepper Minstix"
  28.         ]
  29.     },
  30.     {
  31.         "If all of Santas reindeer had antlers while pulling his Christmas sleigh, they would all be:": [
  32.             "Girls",
  33.             "Boys",
  34.             "Girls and boys",
  35.             "No way to tell"
  36.         ]
  37.     },
  38.     {
  39.         "What do Reindeer eat?": [
  40.             "Lichen",
  41.             "Grasses",
  42.             "Leaves",
  43.             "Berries"
  44.         ]
  45.     },
  46.     {
  47.         "What of the following is not true?": [
  48.             "Caribou live on all continents",
  49.             "Both reindeer and Caribou are the same species",
  50.             "Caribou are bigger than reindeer",
  51.             "Reindeer live in Scandinavia and Russia"
  52.         ]
  53.     },
  54.     {
  55.         "In what year did Rudolph make his television debut?": [
  56.             "1964",
  57.             "1979",
  58.             "2000",
  59.             "1956"
  60.         ]
  61.     },
  62.     {
  63.         "Who was the voice of Rudolph in the 1964 classic?": [
  64.             "Billie Mae Richards",
  65.             "Burl Ives",
  66.             "Paul Soles",
  67.             "Lady Gaga"
  68.         ]
  69.     },
  70.     {
  71.         "In 1939 what retailer used the story of Rudolph the Red Nose Reindeer?": [
  72.             "Montgomery Ward",
  73.             "Sears",
  74.             "Macys",
  75.             "Kmart"
  76.         ]
  77.     },
  78.     {
  79.         "Santa's reindeer named Donner was originally named what?": [
  80.             "Dunder",
  81.             "Donny",
  82.             "Dweedle",
  83.             "Dreamy"
  84.         ]
  85.     },
  86.     {
  87.         "Who invented the story of Rudolph?": [
  88.             "Robert May",
  89.             "Johnny Marks",
  90.             "Santa",
  91.             "J.K. Rowling"
  92.         ]
  93.     },
  94.     {
  95.         "In what location will you not find reindeer?": [
  96.             "North Pole",
  97.             "Lapland",
  98.             "Korvatunturi mountain",
  99.             "Finland"
  100.         ]
  101.     },
  102.     {
  103.         "What Makes Santa's Reindeer Fly?": [
  104.             "Magical Reindeer Dust",
  105.             "Fusion",
  106.             "Amanita muscaria",
  107.             "Elves"
  108.         ]
  109.     },
  110.     {
  111.         "Including Rudolph, how many reindeer hooves are there?": [
  112.             "36",
  113.             "24",
  114.             "16",
  115.             "8"
  116.         ]
  117.     },
  118.     {
  119.         "Santa only has one female reindeer. Which one is it?": [
  120.             "Vixen",
  121.             "Clarice",
  122.             "Cupid",
  123.             "Cupid"
  124.         ]
  125.     },
  126.     {
  127.         "In the 1964 classic Rudolph The Red Nosed Reindeer, what was the snowman narrators name?": [
  128.             "Sam",
  129.             "Frosty",
  130.             "Burl",
  131.             "Snowy"
  132.         ]
  133.     },
  134.     {
  135.         "What was Rudolph's father's name?": [
  136.             "Donner",
  137.             "Dasher",
  138.             "Blixen",
  139.             "Comet"
  140.         ]
  141.     },
  142.     {
  143.         "In the 1964 movie, What was the name of the coach of the Reindeer Games?": [
  144.             "Comet",
  145.             "Blixen",
  146.             "Donner",
  147.             "Dasher"
  148.         ]
  149.     },
  150.     {
  151.         "In the 1964 movie, what is the name of the deer that Rudolph befriends at the reindeer games?": [
  152.             "Fireball",
  153.             "Clarice",
  154.             "Jumper",
  155.             "Vixen"
  156.         ]
  157.     },
  158.     {
  159.         "In the 1964 movie, How did Donner, Rudolph's father, try to hide Rudolph's nose?": [
  160.             "Black mud",
  161.             "Bag",
  162.             "Pillow case",
  163.             "Sock"
  164.         ]
  165.     },
  166.     {
  167.         "In the 1964 movie, what does the Misfit Elf want to be instead of a Santa Elf?": [
  168.             "Dentist",
  169.             "Reindeer",
  170.             "Toy maker",
  171.             "Candlestick maker"
  172.         ]
  173.     },
  174.     {
  175.         "In the 1964 movie,what was the Bumble's one weakness?": [
  176.             "Could not swim",
  177.             "Always hungry",
  178.             "Candy canes",
  179.             "Cross eyed"
  180.         ]
  181.     },
  182.     {
  183.         "In the 1964 movie, what is Yukon Cornelius really in search of?": [
  184.             "Peppermint",
  185.             "Gold",
  186.             "India",
  187.             "Polar Bears"
  188.         ]
  189.     },
  190.     {
  191.         "In the 1964 movie, why is the train on the Island of Misfit Toys?": [
  192.             "Square wheels",
  193.             "No Engine",
  194.             "Paint does not match",
  195.             "It does not toot"
  196.         ]
  197.     },
  198.     {
  199.         "In the 1964 movie, what is the name of the Jack in the Box?": [
  200.             "Charlie",
  201.             "Sam",
  202.             "Billy",
  203.             "Jack"
  204.         ]
  205.     },
  206.     {
  207.         "In the 1964 movie, why did Santa Claus almost cancel Christmas?": [
  208.             "Storm",
  209.             "No snow",
  210.             "No toys",
  211.             "The Reindeer were sick"
  212.         ]
  213.     },
  214.     {
  215.         "In the 1964 movie, what animal noise did the elf make to distract the Bumble?": [
  216.             "Oink",
  217.             "Growl",
  218.             "Bark",
  219.             "Meow"
  220.         ]
  221.     },
  222.     {
  223.         "In the 1964 movie, what is the name of the prospector?": [
  224.             "Yukon Cornelius",
  225.             "Slider Sam",
  226.             "Bumble",
  227.             "Jack"
  228.         ]
  229.     },
  230.     {
  231.         "How far do reindeer travel when they migrate?": [
  232.             "3000 miles",
  233.             "700 miles",
  234.             "500 miles",
  235.             "0 miles"
  236.         ]
  237.     },
  238.     {
  239.         "How fast can a reindeer run?": [
  240.             "48 miles per hour",
  241.             "17 miles per hour",
  242.             "19 miles per hour",
  243.             "14 miles per hour"
  244.         ]
  245.     }
  246. ];
  247.  
  248.  
  249. // Route the incoming request based on type (LaunchRequest, IntentRequest,
  250. // etc.) The JSON body of the request is provided in the event parameter.
  251.  
  252. exports.handler = function (event, context) {
  253.  
  254.     try {
  255.  
  256.         // console.log("event.session.application.applicationId=" + event.session.application.applicationId);
  257.  
  258.         /**
  259.         *Uncomment this if statement and populate with your skill's application ID to
  260.         *prevent someone else from configuring a skill that sends requests to this function.
  261.         */
  262.  
  263.         // if (event.session.application.applicationId !== "amzn1.echo-sdk-ams.app.05aecccb3-1461-48fb-a008-822ddrt6b516") {
  264.         // context.fail("Invalid Application ID");
  265.         // }
  266.  
  267.         // if (event.session.new) {
  268.         //     onSessionStarted({ requestId: event.request.requestId }, event.session);
  269.         // }
  270.        
  271.         console.log("event.request: " , event.request);
  272.  
  273.         if (event.request.type === "LaunchRequest") {
  274.             onLaunch(event.request,
  275.                 event.session,
  276.                 function callback(sessionAttributes, speechletResponse) {
  277.                     context.succeed(buildResponse(sessionAttributes, speechletResponse));
  278.                 });
  279.         } else if (event.request.type === "IntentRequest") {
  280.             onIntent(event.request,
  281.                 event.session,
  282.                 function callback(sessionAttributes, speechletResponse) {
  283.                     context.succeed(buildResponse(sessionAttributes, speechletResponse));
  284.                 });
  285.         } else if (event.request.type === "SessionEndedRequest") {
  286.             onSessionEnded(event.request, event.session);
  287.             context.succeed();
  288.         } else if (event.request.type === "Messaging.MessageReceived") {
  289.             console.log("event.request.message: " , event.request.message);
  290.             handleAnnounceReuqest(function callback(sessionAttributes, speechletResponse) {
  291.                     context.succeed(buildResponse(sessionAttributes, speechletResponse));
  292.                 });
  293.         }
  294.     } catch (e) {
  295.         context.fail("Exception: " + e);
  296.     }
  297. };
  298.  
  299. /**
  300.  * Called when the session starts.
  301.  */
  302. function onSessionStarted(sessionStartedRequest, session) {
  303.     console.log("onSessionStarted requestId=" + sessionStartedRequest.requestId
  304.         + ", sessionId=" + session.sessionId);
  305.  
  306.     // add any session init logic here
  307. }
  308.  
  309. /**
  310.  * Called when the user invokes the skill without specifying what they want.
  311.  */
  312. function onLaunch(launchRequest, session, callback) {
  313.     console.log("onLaunch requestId=" + launchRequest.requestId
  314.         + ", sessionId=" + session.sessionId);
  315.  
  316.     getWelcomeResponse002(callback);
  317. }
  318.  
  319. /**
  320.  * Called when the user specifies an intent for this skill.
  321.  */
  322. function onIntent(intentRequest, session, callback) {
  323.     console.log("onIntent requestId=" + intentRequest.requestId
  324.         + ", sessionId=" + session.sessionId);
  325.  
  326.     var intent = intentRequest.intent,
  327.         intentName = intentRequest.intent.name;
  328.     console.log("intentName: " + intentName);
  329.  
  330.     // handle yes/no intent after the user has been prompted
  331.     if (session.attributes && session.attributes.userPromptedToContinue) {
  332.         delete session.attributes.userPromptedToContinue;
  333.         if ("AMAZON.NoIntent" === intentName) {
  334.             handleFinishSessionRequest(intent, session, callback);
  335.         } else if ("AMAZON.YesIntent" === intentName) {
  336.             handleRepeatRequest(intent, session, callback);
  337.         }
  338.     }
  339.  
  340.     // dispatch custom intents to handlers here
  341.     if ("AnswerIntent" === intentName) {
  342.         handleAnswerRequest(intent, session, callback);
  343.     } else if ("AnswerOnlyIntent" === intentName) {
  344.         handleAnswerRequest(intent, session, callback);
  345.     } else if ("DontKnowIntent" === intentName) {
  346.         handleAnswerRequest(intent, session, callback);
  347.     } else if ("AMAZON.YesIntent" === intentName) {
  348.         handleAnswerRequest(intent, session, callback);
  349.     } else if ("AMAZON.NoIntent" === intentName) {
  350.         handleAnswerRequest(intent, session, callback);
  351.     } else if ("AMAZON.StartOverIntent" === intentName) {
  352.         getWelcomeResponse002(callback);
  353.     } else if ("AMAZON.RepeatIntent" === intentName) {
  354.         handleRepeatRequest(intent, session, callback);
  355.     } else if ("AMAZON.HelpIntent" === intentName) {
  356.         handleGetHelpRequest(intent, session, callback);
  357.     } else if ("AMAZON.StopIntent" === intentName) {
  358.         handleFinishSessionRequest(intent, session, callback);
  359.     } else if ("AMAZON.CancelIntent" === intentName) {
  360.         handleFinishSessionRequest(intent, session, callback);
  361.     } else if ("AnswerNoMeaning" === intentName) {
  362.         handleAnswerRequest(intent, session, callback);
  363.     } else if ("AnnounceIntent" === intentName) {
  364.         // getWelcomeResponse002(callback);
  365.         handleAnnounceReuqest(callback);
  366.     } else {
  367.         throw "Invalid intent";
  368.     }
  369. }
  370.  
  371. /**
  372.  * Called when the user ends the session.
  373.  * Is not called when the skill returns shouldEndSession=true.
  374.  */
  375. function onSessionEnded(sessionEndedRequest, session) {
  376.     console.log("onSessionEnded requestId=" + sessionEndedRequest.requestId
  377.         + ", sessionId=" + session.sessionId);
  378.  
  379.     // Add any cleanup logic here
  380. }
  381.  
  382. // ------- Skill specific business logic -------
  383.  
  384. var ANSWER_COUNT = 4;
  385.  
  386. var GAME_LENGTH = 5;
  387.  
  388. var CARD_TITLE = "Trivia"; // Be sure to change this for your skill.
  389.  
  390. function getWelcomeResponse002(callback) {
  391.  
  392.     var sessionAttributes = {};
  393.     var repromptText = "";
  394.     var speechOutput = "what announcements do you want to make";
  395.     var shouldEndSession = false;
  396.     callback(sessionAttributes,
  397.         buildSpeechletResponse(CARD_TITLE, speechOutput, repromptText, shouldEndSession));
  398. }
  399.  
  400. function getWelcomeResponse(callback) {
  401.  
  402.     var sessionAttributes = {},
  403.  
  404.         speechOutput = "I will ask you " + GAME_LENGTH.toString()
  405.  
  406.             + " questions, try to get as many right as you can. Just say the number of the answer. Let's begin. ",
  407.  
  408.         shouldEndSession = false,
  409.  
  410.         gameQuestions = populateGameQuestions(),
  411.         correctAnswerIndex = Math.floor(Math.random() * (ANSWER_COUNT)), // Generate a random index for the correct answer, from 0 to 3
  412.         roundAnswers = populateRoundAnswers(gameQuestions, 0, correctAnswerIndex),
  413.  
  414.         currentQuestionIndex = 0,
  415.         spokenQuestion = Object.keys(questions[gameQuestions[currentQuestionIndex]])[0],
  416.         repromptText = "Question 1. " + spokenQuestion + " ",
  417.  
  418.         i, j;
  419.  
  420.     for (i = 0; i < ANSWER_COUNT; i++) {
  421.         repromptText += (i + 1).toString() + ". " + roundAnswers[i] + ". "
  422.     }
  423.     speechOutput += repromptText;
  424.     sessionAttributes = {
  425.         "speechOutput": repromptText,
  426.         "repromptText": repromptText,
  427.         "currentQuestionIndex": currentQuestionIndex,
  428.         "correctAnswerIndex": correctAnswerIndex + 1,
  429.         "questions": gameQuestions,
  430.         "score": 0,
  431.         "correctAnswerText":
  432.             questions[gameQuestions[currentQuestionIndex]][Object.keys(questions[gameQuestions[currentQuestionIndex]])[0]][0]
  433.     };
  434.     callback(sessionAttributes,
  435.         buildSpeechletResponse(CARD_TITLE, speechOutput, repromptText, shouldEndSession));
  436. }
  437.  
  438. function populateGameQuestions() {
  439.     var gameQuestions = [];
  440.     var indexList = [];
  441.     var index = questions.length;
  442.  
  443.     if (GAME_LENGTH > index) {
  444.         throw "Invalid Game Length.";
  445.     }
  446.  
  447.     for (var i = 0; i < questions.length; i++) {
  448.         indexList.push(i);
  449.     }
  450.  
  451.     // Pick GAME_LENGTH random questions from the list to ask the user, make sure there are no repeats.
  452.     for (var j = 0; j < GAME_LENGTH; j++) {
  453.         var rand = Math.floor(Math.random() * index);
  454.         index -= 1;
  455.  
  456.         var temp = indexList[index];
  457.         indexList[index] = indexList[rand];
  458.         indexList[rand] = temp;
  459.         gameQuestions.push(indexList[index]);
  460.     }
  461.  
  462.     return gameQuestions;
  463. }
  464.  
  465. function populateRoundAnswers(gameQuestionIndexes, correctAnswerIndex, correctAnswerTargetLocation) {
  466.     // Get the answers for a given question, and place the correct answer at the spot marked by the
  467.     // correctAnswerTargetLocation variable. Note that you can have as many answers as you want but
  468.     // only ANSWER_COUNT will be selected.
  469.     var answers = [],
  470.         answersCopy = questions[gameQuestionIndexes[correctAnswerIndex]][Object.keys(questions[gameQuestionIndexes[correctAnswerIndex]])[0]],
  471.         temp, i;
  472.  
  473.     var index = answersCopy.length;
  474.  
  475.     if (index < ANSWER_COUNT) {
  476.         throw "Not enough answers for question.";
  477.     }
  478.  
  479.     // Shuffle the answers, excluding the first element.
  480.     for (var j = 1; j < answersCopy.length; j++) {
  481.         var rand = Math.floor(Math.random() * (index - 1)) + 1;
  482.         index -= 1;
  483.  
  484.         var temp = answersCopy[index];
  485.         answersCopy[index] = answersCopy[rand];
  486.         answersCopy[rand] = temp;
  487.     }
  488.  
  489.     // Swap the correct answer into the target location
  490.     for (i = 0; i < ANSWER_COUNT; i++) {
  491.         answers[i] = answersCopy[i];
  492.     }
  493.     temp = answers[0];
  494.     answers[0] = answers[correctAnswerTargetLocation];
  495.     answers[correctAnswerTargetLocation] = temp;
  496.     return answers;
  497. }
  498.  
  499. function handleAnswerRequest(intent, session, callback) {
  500.     var speechOutput = "";
  501.     var sessionAttributes = {};
  502.     var gameInProgress = session.attributes && session.attributes.questions;
  503.     var answerSlotValid = isAnswerSlotValid(intent);
  504.     var userGaveUp = intent.name === "DontKnowIntent";
  505.  
  506.     if (!gameInProgress) {
  507.         // If the user responded with an answer but there is no game in progress, ask the user
  508.         // if they want to start a new game. Set a flag to track that we've prompted the user.
  509.         sessionAttributes.userPromptedToContinue = true;
  510.         speechOutput = "There is no game in progress. Do you want to start a new game? ";
  511.         callback(sessionAttributes,
  512.             buildSpeechletResponse(CARD_TITLE, speechOutput, speechOutput, false));
  513.     } else if (intent.name === "AnswerNoMeaning") {
  514.         // This is my try for this function
  515.         var reprompt = session.attributes.speechOutput;
  516.         var speechOutput = "Please give it a try";
  517.         callback(session.attributes,
  518.             buildSpeechletResponse(CARD_TITLE, speechOutput, reprompt, false));
  519.     } else if (!answerSlotValid && !userGaveUp) {
  520.         // If the user provided answer isn't a number > 0 and < ANSWER_COUNT,
  521.         // return an error message to the user. Remember to guide the user into providing correct values.
  522.         var reprompt = session.attributes.speechOutput;
  523.         var speechOutput = "Your answer must be a number between 1 and " + ANSWER_COUNT + ". " + reprompt;
  524.         callback(session.attributes,
  525.             buildSpeechletResponse(CARD_TITLE, speechOutput, reprompt, false));
  526.     } else {
  527.         var gameQuestions = session.attributes.questions,
  528.             correctAnswerIndex = parseInt(session.attributes.correctAnswerIndex),
  529.             currentScore = parseInt(session.attributes.score),
  530.             currentQuestionIndex = parseInt(session.attributes.currentQuestionIndex),
  531.             correctAnswerText = session.attributes.correctAnswerText;
  532.  
  533.         var speechOutputAnalysis = "";
  534.  
  535.         if (answerSlotValid && parseInt(intent.slots.Answer.value) == correctAnswerIndex) {
  536.             currentScore++;
  537.             speechOutputAnalysis = "correct. ";
  538.         } else {
  539.             if (!userGaveUp) {
  540.                 speechOutputAnalysis = "wrong. "
  541.             }
  542.             speechOutputAnalysis += "The correct answer is " + correctAnswerIndex + ": " + correctAnswerText + ". ";
  543.         }
  544.         // if currentQuestionIndex is 4, we've reached 5 questions (zero-indexed) and can exit the game session
  545.         if (currentQuestionIndex == GAME_LENGTH - 1) {
  546.             speechOutput = userGaveUp ? "" : "That answer is ";
  547.             speechOutput += speechOutputAnalysis + "You got " + currentScore.toString() + " out of "
  548.                 + GAME_LENGTH.toString() + " questions correct. Thank you for playing!";
  549.             callback(session.attributes,
  550.                 buildSpeechletResponse(CARD_TITLE, speechOutput, "", true));
  551.         } else {
  552.             currentQuestionIndex += 1;
  553.             var spokenQuestion = Object.keys(questions[gameQuestions[currentQuestionIndex]])[0];
  554.             // Generate a random index for the correct answer, from 0 to 3
  555.             correctAnswerIndex = Math.floor(Math.random() * (ANSWER_COUNT));
  556.             var roundAnswers = populateRoundAnswers(gameQuestions, currentQuestionIndex, correctAnswerIndex),
  557.  
  558.                 questionIndexForSpeech = currentQuestionIndex + 1,
  559.                 repromptText = "Question " + questionIndexForSpeech.toString() + ". " + spokenQuestion + " ";
  560.             for (var i = 0; i < ANSWER_COUNT; i++) {
  561.                 repromptText += (i + 1).toString() + ". " + roundAnswers[i] + ". "
  562.             }
  563.             speechOutput += userGaveUp ? "" : "That answer is ";
  564.             speechOutput += speechOutputAnalysis + "Your score is " + currentScore.toString() + ". " + repromptText;
  565.  
  566.             sessionAttributes = {
  567.                 "speechOutput": repromptText,
  568.                 "repromptText": repromptText,
  569.                 "currentQuestionIndex": currentQuestionIndex,
  570.                 "correctAnswerIndex": correctAnswerIndex + 1,
  571.                 "questions": gameQuestions,
  572.                 "score": currentScore,
  573.                 "correctAnswerText":
  574.                     questions[gameQuestions[currentQuestionIndex]][Object.keys(questions[gameQuestions[currentQuestionIndex]])[0]][0]
  575.             };
  576.             callback(sessionAttributes,
  577.                 buildSpeechletResponse(CARD_TITLE, speechOutput, repromptText, false));
  578.         }
  579.     }
  580. }
  581.  
  582. function uuidv4() {
  583.   return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
  584.     var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);
  585.     return v.toString(16);
  586.   });
  587. }
  588.  
  589. function handleAnnounceReuqest(callback) {
  590.     console.log('handleAnnounceReuqest() starts.')
  591.     var uuid = uuidv4();
  592.     var params = {
  593.       ClientRequestToken: uuid, /* required */
  594.       Content: { /* required */
  595.         TextList: [
  596.           {
  597.             Locale: 'en-US', /* required */
  598.             Value: 'this is an announcement made from Lambda' /* required */
  599.           }
  600.         ]
  601.       },
  602.       RoomFilters: [ /* required */
  603.         {
  604.           Key: 'RoomArn', /* required */
  605.           Values: [ /* required */
  606.             'arn:aws:a4b:us-east-1:602307824922:room/39a4ac8b07b41622dfdc2fd3dadf2fc8/52b8bb40b219bf8737126a807919ac93'
  607.           ]
  608.         },
  609.         /* more items */
  610.       ],
  611.       TimeToLiveInSeconds: '300'
  612.     };    
  613.        
  614.    
  615.     var alexaforbusiness = new AWS.AlexaForBusiness();
  616.     alexaforbusiness.sendAnnouncement(params, function (err, data) {
  617.       if (err) {
  618.           console.log("error response - data: " , err, err.stack); // an error occurred
  619.           console.log('handleAnnounceReuqest() ends 001.')
  620.       } else {
  621.             console.log("successful response - data: " , data);           // successful response
  622.             var sessionAttributes = {};
  623.             var repromptText = "";
  624.             var speechOutput = "announcement is sent";
  625.             var shouldEndSession = false;
  626.             callback(sessionAttributes,
  627.                 buildSpeechletResponse(CARD_TITLE, speechOutput, repromptText, shouldEndSession));
  628.             console.log('handleAnnounceReuqest() ends 002.')
  629.       }
  630.     });
  631.  
  632.     console.log('handleAnnounceReuqest() ends 000.')
  633. }
  634.  
  635. function handleRepeatRequest(intent, session, callback) {
  636.     // Repeat the previous speechOutput and repromptText from the session attributes if available
  637.     // else start a new game session
  638.     if (!session.attributes || !session.attributes.speechOutput) {
  639.         getWelcomeResponse002(callback);
  640.     } else {
  641.         callback(session.attributes,
  642.             buildSpeechletResponseWithoutCard(session.attributes.speechOutput, session.attributes.repromptText, false));
  643.     }
  644. }
  645.  
  646. function handleGetHelpRequest(intent, session, callback) {
  647.     // Provide a help prompt for the user, explaining how the game is played. Then, continue the game
  648.     // if there is one in progress, or provide the option to start another one.
  649.  
  650.     // Set a flag to track that we're in the Help state.
  651.     session.attributes.userPromptedToContinue = true;
  652.  
  653.     // Do not edit the help dialogue. This has been created by the Alexa team to demonstrate best practices.
  654.  
  655.     var speechOutput = "I will ask you " + GAME_LENGTH + " multiple choice questions. Respond with the number of the answer. "
  656.         + "For example, say one, two, three, or four. To start a new game at any time, say, start game. "
  657.         + "To repeat the last question, say, repeat. "
  658.         + "Would you like to keep playing?",
  659.         repromptText = "To give an answer to a question, respond with the number of the answer . "
  660.             + "Would you like to keep playing?";
  661.     var shouldEndSession = false;
  662.     callback(session.attributes,
  663.         buildSpeechletResponseWithoutCard(speechOutput, repromptText, shouldEndSession));
  664. }
  665.  
  666. function handleFinishSessionRequest(intent, session, callback) {
  667.     // End the session with a "Good bye!" if the user wants to quit the game
  668.     callback(session.attributes,
  669.         buildSpeechletResponseWithoutCard("Good bye!", "", true));
  670. }
  671.  
  672. function isAnswerSlotValid(intent) {
  673.     var answerSlotFilled = intent.slots && intent.slots.Answer && intent.slots.Answer.value;
  674.     var answerSlotIsInt = answerSlotFilled && !isNaN(parseInt(intent.slots.Answer.value));
  675.     return answerSlotIsInt && parseInt(intent.slots.Answer.value) < (ANSWER_COUNT + 1) && parseInt(intent.slots.Answer.value) > 0;
  676. }
  677.  
  678. // ------- Helper functions to build responses -------
  679.  
  680. function buildSpeechletResponse(title, output, repromptText, shouldEndSession) {
  681.  
  682.     return {
  683.         outputSpeech: {
  684.             type: "PlainText",
  685.             text: output
  686.         },
  687.         card: {
  688.             type: "Simple",
  689.             title: title,
  690.             content: output
  691.         },
  692.         reprompt: {
  693.             outputSpeech: {
  694.                 type: "PlainText",
  695.                 text: repromptText
  696.             }
  697.         },
  698.         shouldEndSession: shouldEndSession
  699.     };
  700.  
  701. }
  702.  
  703. function buildSpeechletResponseWithoutCard(output, repromptText, shouldEndSession) {
  704.  
  705.     return {
  706.         outputSpeech: {
  707.             type: "PlainText",
  708.             text: output
  709.         },
  710.         reprompt: {
  711.             outputSpeech: {
  712.                 type: "PlainText",
  713.                 text: repromptText
  714.             }
  715.         },
  716.         shouldEndSession: shouldEndSession
  717.     };
  718.  
  719. }
  720.  
  721. function buildResponse(sessionAttributes, speechletResponse) {
  722.  
  723.     return {
  724.         version: "1.0",
  725.         sessionAttributes: sessionAttributes,
  726.         response: speechletResponse
  727.     };
  728. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement