Пример #1
0
        public override SpeechletResponse OnIntent(IntentRequest request, Session session)
        {
            Console.WriteLine("OnIntent requestId={0}, sessionId={1}", request.RequestId, session.SessionId);

            // Get intent from the request object.
            Intent intent     = request.Intent;
            string intentName = intent?.Name;

            // Note: If the session is started with an intent, no welcome message will be rendered;
            // rather, the intent specific response will be returned.
            if ("StatusIntent".Equals(intentName))
            {
                return(ShareStatus(intent, session));
            }
            else if ("SpecificStatusQueryIntent".Equals(intentName))
            {
                return(CheckRequestedStatus(intent, session));
            }
            else
            {
                throw new SpeechletException("Invalid Intent");
            }
        }
Пример #2
0
        private Task <SkillResponse> HandleIntentAsync(IntentRequest request, ILambdaLogger logger)
        {
            switch (request.Intent.Name)
            {
            case "NextLaunchIntent": return(_nextLaunchIntentHandler.HandleAsync(request, logger));

            case "AMAZON.HelpIntent": return(HandleHelpIntentAsync(request, logger));

            case "AMAZON.StopIntent": return(HandleStopIntentAsync(request, logger));

            case "AMAZON.CancelIntent": return(HandleStopIntentAsync(request, logger));

            default:
                logger.LogLine($"Unknown intent request name '{request.Intent.Name}'");

                var response = ResponseBuilder.Tell(new PlainTextOutputSpeech
                {
                    Text = "I'm sorry, I'm not sure what you mean."
                });

                return(Task.FromResult(response));
            }
        }
        public override SpeechletResponse OnIntent(IntentRequest request, Session session)
        {
            Console.WriteLine("OnIntent requestId={0}, sessionId={1}", request.RequestId, session.SessionId);

            // Get intent from the request object.
            Intent intent     = request.Intent;
            string intentName = (intent != null) ? intent.Name : null;

            // Note: If the session is started with an intent, no welcome message will be rendered;
            // rather, the intent specific response will be returned.
            if ("MyNameIsIntent".Equals(intentName))
            {
                return(SetNameInSessionAndSayHello(intent, session));
            }
            else if ("WhatsMyNameIntent".Equals(intentName))
            {
                return(GetNameFromSessionAndSayHello(intent, session));
            }
            else
            {
                throw new SpeechletException("Invalid Intent");
            }
        }
Пример #4
0
        static SkillResponse HandleAskForAnotherDeployIntent(IntentRequest request, Session session, ILogger log)
        {
            SkillResponse response;

            session.Attributes.Clear();

            if (request.Intent.Name == Intents.YesIntent)
            {
                var reprompt = new Reprompt {
                    OutputSpeech = new PlainTextOutputSpeech {
                        Text = "Hai deciso che risorsa vuoi creare?"
                    }
                };

                response = ResponseBuilder.Ask("Perfetto! Che tipo di risorsa vuoi creare ora?", reprompt, session);
            }
            else
            {
                response = ResponseBuilder.Tell("OK, ci vediamo al prossimo deploy!");
            }

            return(response);
        }
Пример #5
0
        public override async Task <SpeechletResponse> OnIntentAsync(IntentRequest request, Session session)
        {
            // Get intent from the request object.
            Intent intent     = request.Intent;
            string intentName = (intent != null) ? intent.Name : null;

            Logger.Info($"OnIntent intentName={intentName} requestId={request.RequestId}, sessionId={session.SessionId}");


            // Note: If the session is started with an intent, no welcome message will be rendered;
            // rather, the intent specific response will be returned.
            switch (intentName)
            {
            case "AskJennIntent":
                return(await BuildAskJennResponseAsync(intent, session));

            case "FlightStatusIntent":
                return(BuildFlightStatusAsync(intent, session));

            default:
                throw new SpeechletException("Invalid Intent");
            }
        }
Пример #6
0
        PlayGrooveMusic(Session session, HttpClient httpClient, IntentRequest intentRequest)
        {
            AlexaUtils.SimpleIntentResponse simpleIntentResponse = new AlexaUtils.SimpleIntentResponse();

            AlexaSkillsKit.Slu.Slot objectByArtistName;
            AlexaSkillsKit.Slu.Slot objectName;
            AlexaSkillsKit.Slu.Slot objectType;

            intentRequest.Intent.Slots.TryGetValue("object.byArtist.name", out objectByArtistName);
            intentRequest.Intent.Slots.TryGetValue("object.name", out objectName);
            intentRequest.Intent.Slots.TryGetValue("object.type", out objectType);

            if (objectType.Value.ToString() == "song")
            {
                simpleIntentResponse = await SearchGrooveSong(objectName.Value, objectByArtistName.Value, session, httpClient);
            }
            else if (objectType.Value.ToString() == "album")
            {
                simpleIntentResponse = await SearchGrooveAlbum(objectName.Value, objectByArtistName.Value, session, httpClient);
            }

            return(AlexaUtils.BuildSpeechletResponse(simpleIntentResponse, true));
        }
Пример #7
0
        public SkillResponse FunctionHandler(SkillRequest input, ILambdaContext context)
        {
            context.Logger.LogLine("Request Type: " + input.GetRequestType().Name);

            if (input.GetRequestType() == typeof(LaunchRequest))
            {
                SkillResponse response = ResponseBuilder.AudioPlayerPlay(Alexa.NET.Response.Directive.PlayBehavior.ReplaceAll, "https://s3-eu-west-1.amazonaws.com/rtg-dispatcher/streaming-test/Dispatcher_Ready_Question.wav", "token");
                response.Response.OutputSpeech = new PlainTextOutputSpeech()
                {
                    Text = "Playing"
                };
                response.Response.ShouldEndSession = false;

                return(response);
            }
            else if (input.GetRequestType() == typeof(IntentRequest))
            {
                IntentRequest request = input.Request as IntentRequest;
                return(request.Intent.Name == "AMAZON.YesIntent" ? ResponseBuilder.AudioPlayerPlay(Alexa.NET.Response.Directive.PlayBehavior.ReplaceAll, "https://s3-eu-west-1.amazonaws.com/rtg-dispatcher/streaming-test/Caller_Birth.wav", "token") : ResponseBuilder.Empty());
            }

            return(ResponseBuilder.Empty());
        }
Пример #8
0
        public SkillResponse GetResponse(IntentRequest request)
        {
            SkillResponse skillResponse;

            switch (request.Intent.Name)
            {
            case "fact":
                //get fact
                var fact = GetFacts().First();
                skillResponse = MakeSkillResponse(fact, false, "Chuck Norris, waits for no man!");

                break;

            case "multifact":
                var count = int.Parse(request.Intent.Slots["count"].Value);

                //get facts
                var facts = GetFacts(count);

                var strBuilder = new StringBuilder();

                for (var i = 0; i < count; i++)
                {
                    strBuilder.AppendLine($"Fact {i + 1}: " + facts[i]);
                }

                skillResponse = MakeSkillResponse(strBuilder.ToString(), false, "Chuck Norris, waits for no man!");

                break;

            default:
                skillResponse = MakeSkillResponse("Check Norris doesn't know what you want, so he left", true, "Chuck Norris, waits for no man!");
                break;
            }

            return(skillResponse);
        }
        public SkillResponse Handle(SkillRequest skillRequest, TokenUser tokenUser)
        {
            if (!base.skillRequestValidator.IsValid(skillRequest))
            {
                throw new ArgumentNullException("skillRequest");
            }

            if (tokenUser == null)
            {
                throw new ArgumentNullException("tokenUser");
            }

            logger.LogTrace("BEGIN GetPointsAverage. RequestId: {0}.", skillRequest.Request.RequestId);

            IntentRequest intentRequest = skillRequest.Request as IntentRequest;

            double[] allPoints = tokenUser.Players.Select(x => (double)x.Points).ToArray();

            SkillResponse response;

            if (allPoints == null || allPoints.Length <= 0)
            {
                response = string.Format("Hmm, you don't see anyone in your list of tokens.").Tell(true);
            }
            else
            {
                double averagePoints          = allPoints.Average();
                string averagePointsFormatted = string.Format("{0:0.0}", averagePoints);

                string pointsWord = Math.Abs(averagePoints) != 1 ? "points" : "point";
                response = string.Format("The average score for all tokens is {0} {1}.", averagePointsFormatted, pointsWord).Tell(true);
            }

            logger.LogTrace("END GetPointsAverage. RequestId: {0}.", skillRequest.Request.RequestId);

            return(response);
        }
Пример #10
0
        internal static InteractionInternalModel FromAlexaRequest(
            SkillRequest skillRequest
            )
        {
            InteractionInternalModel interactionModel = new InteractionInternalModel
            {
                Id = skillRequest.Request.RequestId
            };

            Type requestType = skillRequest.GetRequestType();

            interactionModel.Request.Channel = "alexa";

            if (requestType == typeof(IntentRequest))
            {
                IntentRequest intentRequest = skillRequest.Request as IntentRequest;
                interactionModel.Request.Intent             = intentRequest.Intent.Name;
                interactionModel.Request.State              = intentRequest.DialogState;
                interactionModel.Request.ConfirmationStatus = intentRequest.Intent.ConfirmationStatus;

                if (intentRequest.Intent.Slots != null)
                {
                    interactionModel.Request.Parameters = intentRequest.Intent.Slots.ToList()
                                                          .ConvertAll(s => new KeyValuePair <string, string>(s.Value.Name, s.Value.Value));
                }
            }
            else if (requestType == typeof(LaunchRequest))
            {
                interactionModel.Request.Intent = "DefaultWelcomeIntent";
            }
            else if (requestType == typeof(SessionEndedRequest))
            {
                return(null);
            }

            return(interactionModel);
        }
Пример #11
0
        private SkillResponse GetMedicineDose(IntentRequest intentRequest, SkillRequest input, SkillResponse response)
        {
            switch (intentRequest.DialogState)
            {
            case DialogState.Started:
                // Pre-fill slots: update the intent object with slot values for which
                // you have defaults, then return Dialog.Delegate with this updated intent
                // in the updatedIntent property.
                Log($"GetMedicineDose: Started");
                response = ResponseBuilder.DialogDelegate(input.Session, intentRequest.Intent);
                break;

            case DialogState.InProgress:
                // return a Dialog.Delegate directive with no updatedIntent property.
                Log($"GetMedicineDose: InProgress");
                response = ResponseBuilder.DialogDelegate(input.Session);
                break;

            case DialogState.Completed:
                // Dialog is now complete and all required slots should be filled,
                // so call your normal intent handler.
                Log($"GetMedicineDose: Completed");
                response = CalcDosage(intentRequest, response);
                break;

            default:
                // return a Dialog.Delegate directive with no updatedIntent property.
                //response = ResponseBuilder.DialogElicitSlot(GetInnerResponse("What medicine will you be administering?"), "medicineName", input.Session, intentRequest.Intent);
                Log($"GetMedicineDose: Default.");
                Log($"Input: {JsonConvert.SerializeObject(input)}");
                Log($"Intent Request: {JsonConvert.SerializeObject(intentRequest)}");
                response = ResponseBuilder.DialogDelegate(input.Session);
                Log($"Response: {JsonConvert.SerializeObject(response)}");
                break;
            }
            return(response);
        }
Пример #12
0
        public override async Task <SpeechletResponse> OnIntentAsync(IntentRequest request, Session session)
        {
            // Get intent from the request object.
            Intent intent     = request.Intent;
            string intentName = (intent != null) ? intent.Name : null;

            Logger.Info($"OnIntent intentName={intentName} requestId={request.RequestId}, sessionId={session.SessionId}");
            var tasks = new List <Task>();

            tasks.Add(AskTeenageQueue.AddAsync(JsonConvert.SerializeObject(request)));
            tasks.Add(AskTeenageQueue.AddAsync(JsonConvert.SerializeObject(session)));


            // Note: If the session is started with an intent, no welcome message will be rendered;
            // but, the intent specific response will be returned and the session terminated.

            switch (intentName)
            {
            case "AMAZON.CancelIntent":
                return(await BuildAskTeenagerExitResponseAsync(intent, session));

            case "AMAZON.StopIntent":
                return(await BuildAskTeenagerExitResponseAsync(intent, session));

            case "AMAZON.HelpIntent":
                return(await BuildAskTeenagerHelpResponseAsync(intent, session));

            case "AskTeenagerOpinion":
                return(await BuildAskTeenagerOpinionResponseAsync(intent, session));

            case "AskTeenagerStatus":
                return(await BuildAskTeenagerStatusResponseAsync(intent, session));

            default:
                throw new SpeechletException("Invalid Intent");
            }
        }
Пример #13
0
        private SkillResponse CalcDosage(IntentRequest intentRequest, SkillResponse response)
        {
            // At this point, we should have all of our parameters, and can perform the calculation.

            string weight            = null;
            string medicineName      = null;
            string unitOfMeasurement = null;

            //if (intentRequest != null && intentRequest.Intent != null && intentRequest.Intent.Slots != null)
            //{
            //if (intentRequest?.Intent?.Slots.ContainsKey("weight"))
            //{
            weight = intentRequest?.Intent?.Slots["weight"].Value;
            //}
            //if (intentRequest.Intent.Slots.ContainsKey("medicineName"))
            //{
            medicineName = intentRequest?.Intent?.Slots["medicineName"].Value;
            //}
            //if (intentRequest.Intent.Slots.ContainsKey("unitOfMeasurement"))
            //{
            unitOfMeasurement = intentRequest?.Intent?.Slots["unitOfMeasurement"].Value;
            //}
            //}

            if (string.IsNullOrEmpty(weight) || string.IsNullOrEmpty(medicineName) || string.IsNullOrEmpty(unitOfMeasurement))
            {
                response = MakeSkillResponse("Something's wrong. I have a hole where something else should be...", false);
            }
            else
            {
                response = MakeSkillResponse($"I don't have all the data yet to calculate the dosage of {medicineName} for a {weight} {unitOfMeasurement} animal.", false);
                //if (unitOfMeasurement == "Kilograms")
                //{
                //}
            }
            return(response);
        }
Пример #14
0
        async public override Task <SkillResponse> HandleIntentRequest(IntentRequest request)
        {
            var log = curContext.Logger;

            slots = request.Intent.Slots;

            Slot lightStateSlot = null;

            if (slots.ContainsKey(LIGHTCONTROl))
            {
                lightStateSlot = slots[LIGHTCONTROl];
            }

            // Need to seperate it out.
            Wash_Lights washLtsMsg = new Wash_Lights
            {
                DeviceType = "200",
                Instance   = 1,
                LightState = lightStateSlot.Value
            };

            LightsAlexaMsg msg = new LightsAlexaMsg
            {
                ID         = 2000,
                IntentName = request.Intent.Name,
                Slot       = washLtsMsg
            };
            await DynamoDB.PutAlexaMsg(msg);

            outSpeech = new PlainTextOutputSpeech();
            //(outSpeech as PlainTextOutputSpeech).Text = "Alright!. I have sent a message to venue system to push " + monVidSrcSlot.Value + " on " + monLocSlot.Value + " Monitor.";
            (outSpeech as PlainTextOutputSpeech).Text = "Cabin system accepted your request. Enjoy your flight!. ";
            skillResponse.Response.OutputSpeech       = outSpeech;
            skillResponse.Response.ShouldEndSession   = true;

            return(skillResponse);
        }
Пример #15
0
        private static IRequestHandler GetRequestHandlerFromIntentRequest(IntentRequest intentRequest)
        {
            switch (intentRequest.Intent.Name)
            {
            case LastMeetupIntentName:
                return(new LastMeetupRequestHandler(intentRequest));

            case NextMeetupIntentName:
            case FallbackIntentName:
                return(new NextMeetupRequestHandler(intentRequest));

            case CancelIntentName:
                return(new CancelRequestHandler(intentRequest));

            case HelpIntentName:
                return(new HelpRequestHandler(intentRequest));

            case StopIntentName:
                return(new StopRequestHandler(intentRequest));

            default:
                throw new ArgumentException("Could not find a matching handler for the IntentRequest Intent");
            }
        }
        public SkillResponse Handle(SkillRequest skillRequest, TokenUser tokenUser)
        {
            if (!base.skillRequestValidator.IsValid(skillRequest))
            {
                throw new ArgumentNullException("skillRequest");
            }

            if (tokenUser == null)
            {
                throw new ArgumentNullException("tokenUser");
            }

            logger.LogTrace("BEGIN GetPlayerPoints. RequestId: {0}.", skillRequest.Request.RequestId);

            IntentRequest intentRequest = skillRequest.Request as IntentRequest;

            string playerName = Configuration.TEXT_INFO.ToTitleCase(intentRequest.Intent.Slots["player"].Value);

            Player existingPlayer = tokenUser.Players.FirstOrDefault(x => x.Name == playerName);

            SkillResponse response;

            if (existingPlayer != null)
            {
                string pointsWord = Math.Abs(existingPlayer.Points) != 1 ? "points" : "point";
                response = string.Format("{0} has {1} {2}.", existingPlayer.Name, existingPlayer.Points, pointsWord).Tell(true);
            }
            else
            {
                response = string.Format("Hmm, I don't see {0} in your list of tokens.", playerName).Tell(true);
            }

            logger.LogTrace("END GetPlayerPoints. RequestId: {0}.", skillRequest.Request.RequestId);

            return(response);
        }
        public SpeechletResponse OnIntent(IntentRequest request, Session session, Context context)
        {
            Log.Info("OnIntent requestId={0}, sessionId={1}", request.RequestId, session.SessionId);

            Intent intent     = request.Intent;
            string intentName = (intent != null) ? intent.Name : null;

            if ("GetDocumentIntent".Equals(intentName))
            {
                return(SetNameInSessionAndSayHello(intent, session));
            }
            else if ("ReadDocumentIntent".Equals(intentName))
            {
                return(GetNameFromSessionAndSayHello(intent, session));
            }
            else if ("AMAZON.CancelIntent".Equals(intentName))
            {
                return(CloseSession(intent, session));
            }
            else
            {
                throw new SpeechletException("Invalid Intent");
            }
        }
        public override async Task <SkillResponse> GetSkillResponse(SkillRequest skillRequest, TokenUser tokenUser)
        {
            if (!base.SkillRequestValidator.IsValid(skillRequest))
            {
                throw new ArgumentNullException("skillRequest");
            }

            if (tokenUser == null)
            {
                throw new ArgumentNullException("tokenUser");
            }

            base.Logger.LogTrace("BEGIN GetSkillResponse. RequestId: {0}.", skillRequest.Request.RequestId);

            IntentRequest intentRequest = skillRequest.Request as IntentRequest;

            if (intentRequest.Intent.ConfirmationStatus == "DENIED")
            {
                return(string.Format("Okay").Tell(true));
            }

            // Get the right handler for the IntentRequest based on the name of the intent
            IIntentRequestHandler requestHandler = base.RequestHandlers.Where(x => x.HandlerName == intentRequest.Intent.Name).FirstOrDefault() as IIntentRequestHandler;

            if (requestHandler == null)
            {
                throw new NotSupportedException(string.Format("Cannot successfully route IntentRequest '{0}'.", intentRequest.Intent.Name));
            }

            // Handle the request
            SkillResponse skillResponse = await Task.Run(() => requestHandler.Handle(skillRequest, tokenUser));

            base.Logger.LogTrace("END GetSkillResponse. RequestId: {0}.", skillRequest.Request.RequestId);

            return(skillResponse);
        }
Пример #19
0
        public async Task <SpeechletResponse> OnIntentAsync(IntentRequest intentRequest, Session session)
        {
            await logHelper.Log($"User {session.User.Id} in session {session.SessionId}");

            return((await HandleIntentAsync(intentRequest.Intent, intentRequest.DialogState, session)).Build());
        }
Пример #20
0
        public SkillResponse HandleResponse(SkillRequest alexaRequestInput)
        {
            AlexaRequestValidationService    validator        = new AlexaRequestValidationService();
            SpeechletRequestValidationResult validationResult = validator.ValidateAlexaRequest(alexaRequestInput);

            if (validationResult != SpeechletRequestValidationResult.OK)
            {
                logger.Debug("validation error: " + validationResult.ToString());
                new Exception("Invalid Request");
            }
            SkillResponse response = new SkillResponse();

            response.Version = "1.0";
            logger.Debug("Request:" + JsonConvert.SerializeObject(alexaRequestInput.Request));
            CaseInfo caseInfo = Helpers.GetCaseInfo(alexaRequestInput.Context.System.User.UserId);

            if (caseInfo.profile == null)
            {
                caseInfo.profile = Helpers.GetUserProfile(alexaRequestInput);
            }
            switch (alexaRequestInput.Request.Type)
            {
            case "LaunchRequest":

                logger.Debug("Launch request in");

                response.Response      = new ResponseBody();
                response.Response.Card = new SimpleCard()
                {
                    Content = "Hello " + caseInfo.profile.name + ". Welcome to your Benefind dashboard. Say: \"Check case summary\", \"Check my pending documents\" or \"Schedule an appointment\"",

                    Title = "Benifind Dashboard"
                };
                response.Response.OutputSpeech = new PlainTextOutputSpeech()
                {
                    Text = "Hello " + caseInfo.profile.name + ". Welcome to your Beni-find dashboard. You don't have any new notifications. You can now say, Check case summary, or  Check my pending documents, Or say Schedule an appointment  \""
                };
                //response.Response.OutputSpeech = new PlainTextOutputSpeech() { Text = "Hello!! say, \"I am ready!\"" };

                response.Response.ShouldEndSession = false;

                logger.Debug("Launch request out");
                break;

            case "SessionEndedRequest":
                response.Response      = new ResponseBody();
                response.Response.Card = new SimpleCard()
                {
                    Content = "Goodbye, have a good day!",

                    Title = "Welcome!!"
                };
                response.Response.OutputSpeech = new PlainTextOutputSpeech()
                {
                    Text = "Goodbye, have a good day!"
                };
                response.Response.ShouldEndSession = true;
                return(response);

            case "IntentRequest":
                try
                {
                    IntentRequest intentRequest = (IntentRequest)(alexaRequestInput.Request);
                    if (intentRequest.Intent.Name == "casesummary")
                    {
                        string text = "Hello <Name>, I see your SNAP case is active and ongoing. The SNAP case will be up for renewal for March 31st 2019. Your child care case is pending for an RFI. Please say \"Check my RFI\" to know more.";
                        response.Response = Helpers.GetPlainTextResponseBody(text.Replace("<Name>", caseInfo.profile.name), true, "Case Summary");
                        response.Response.ShouldEndSession = false;;
                    }
                    if (intentRequest.Intent.Name == "rfi")
                    {
                        string text = "Hello <Name>, you have a household composition RFI, due by January 31st 2019. You can upload documents on our self service portal or return documents to our offices. P.A.F.S 76 is a supported document for this RFI.";
                        response.Response = Helpers.GetPlainTextResponseBody(text.Replace("<Name>", caseInfo.profile.name), true, "RFI Details");
                        response.Response.ShouldEndSession = false;;
                    }
                    if (intentRequest.Intent.Name == "schedule")
                    {
                        string text = "";
                        if (intentRequest.Intent.ConfirmationStatus == "CONFIRMED")
                        {
                            var date = intentRequest.Intent.Slots["date"].Value;
                            var time = intentRequest.Intent.Slots["time"].Value;


                            text = "All set, your appointment is scheduled for the selected time. I have also sent you this information on your email.";
                            Helpers.SendEmailAsync(caseInfo.profile.email, caseInfo.profile.name, date, time);
                        }
                        else
                        {
                            text = "Ok, Roger that!! Request cancelled!";
                        }
                        response.Response = Helpers.GetPlainTextResponseBody(text.Replace("<Name>", caseInfo.profile.name), true, "Appointments");
                        response.Response.ShouldEndSession = true;;
                    }

                    if (intentRequest.Intent.Name == "AMAZON.StopIntent")
                    {
                        var stophandler   = new AMAZON_StopIntent();
                        var skillresponse = stophandler.HandleIntent(null, null, null, null, logger);
                        skillresponse.Version = "1.0";
                        return(skillresponse);
                    }
                    if (intentRequest.Intent.Name == "AMAZON.FallbackIntent")
                    {
                        var fallbackhandler  = new AMAZON_FallbackIntent();
                        var fallbackresponse = fallbackhandler.HandleIntent(null, null, null, null, logger);
                        fallbackresponse.Version = "1.0";
                        return(fallbackresponse);
                    }
                    if (intentRequest.Intent.Name == "AMAZON.CancelIntent")
                    {
                        var cancelhandler   = new AMAZON_CancelIntent();
                        var cancellresponse = cancelhandler.HandleIntent(null, null, null, null, logger);
                        cancellresponse.Version = "1.0";
                        return(cancellresponse);
                    }
                    //if (intentRequest.Intent.Name == "AMAZON.HelpIntent")
                    //{
                    //    var helphandler = new AMAZON_HelpIntent();
                    //    var helplresponse = helphandler.HandleIntent(null, null, null, null, logger);
                    //    helplresponse.Version = "1.0";
                    //    helplresponse.Response.ShouldEndSession = false;
                    //    return helplresponse;
                    //}
                    break;
                }
                catch (Exception e)
                {
                    response.Response = Helpers.GetPlainTextResponseBody("Aaargh, the application encountered an error. Please try again later. Sorry for the inconvenience", true, "Error", e.Message);
                    response.Response.ShouldEndSession = true;
                    logger.Debug(e.StackTrace);
                }
                break;
            }
            logger.Debug("Response:" + JsonConvert.SerializeObject(response.Response));

            return(response);
        }
Пример #21
0
 public static string TryGetSlotValue(this IntentRequest intentRequest, string slotName)
 {
     return(intentRequest.Intent.Slots[slotName].Value?.ToLower());
 }
Пример #22
0
        public override async Task <SpeechletResponse> OnIntentAsync(IntentRequest intentRequest, Session session)
        {
            var handler = _intentHandlerFactory.CreateIntentHandler(intentRequest.Intent);

            return(await handler.HandleAsync().ConfigureAwait(false));
        }
Пример #23
0
 public abstract SpeechletResponse OnIntent(IntentRequest intentRequest, Session session, Context context);
Пример #24
0
        private SkillResponse HandleIntent(IntentRequest intentRequest, Session session, ILambdaLogger logger)
        {
            try
            {
                var intent = intentRequest.Intent;

                IIntentProcessor processor;

                switch (intentRequest.Intent.Name)
                {
                case "NewTimeSectionIntent":
                {
                    processor = new NewTimeSectionIntentProcessor(intent, session, logger);
                    break;
                }

                case "CurrentPlayerIntent":
                {
                    processor = new CurrentPlayerIntentProcessor(intent, session, logger);
                    break;
                }

                case "ResultIntent":
                {
                    processor = new ResultIntentProcessor(intent, session, logger);
                    break;
                }

                case "PauseIntent":
                {
                    processor = new PauseIntentProcessor(intent, session, logger);
                    break;
                }

                case "ResetIntent":
                {
                    processor = new ResetIntentProcessor(intent, session, logger);
                    break;
                }

                case "AMAZON.HelpIntent":
                {
                    processor = new HelpIntentProcessor(intent, session, logger);
                    break;
                }

                case "AMAZON.CancelIntent":
                {
                    processor = new StopIntentProcessor(intent, session, logger);
                    break;
                }

                case "AMAZON.StopIntent":
                {
                    processor = new StopIntentProcessor(intent, session, logger);
                    break;
                }

                case "AMAZON.NavigateHomeIntent":
                {
                    processor = new HomeIntentProcessor(intent, session, logger);
                    break;
                }

                default:
                {
                    processor = new FallbackIntentProcessor(intent, session, logger);
                    break;
                }
                }

                return(processor.Run());
            }
            catch (Exception e)
            {
                return(ResponseBuilder.Tell($"I\'m broke :( Can you report it - <{e.Message}>, to developer, please?"));
            }
        }
Пример #25
0
        public override async Task <SkillResponse> HandleIntent(SkillRequest skillRequest, IntentRequest intentRequest,
                                                                ILambdaContext context)
        {
            var profile = await SpotifyClient.GetPrivateProfileAsync();

            if (profile.HasError())
            {
                return(TellWithoutEnding("There was an error getting your profile"));
            }

            var playlists = await SpotifyClient.GetUserPlaylistsAsync(profile.Id);

            if (playlists.HasError())
            {
                return(TellWithoutEnding("There was an error getting your playlists"));
            }

            var playlistName = intentRequest.GetSlotValue("PlaylistName");
            var list         = (from playlist in playlists.Items
                                let score = new SmithWatermanGotoh().GetSimilarity(playlist.Name.ToLower(), playlistName.ToLower())
                                            select new MostMatchingPlaylist(playlist, score)).ToList();

            var mostMatching = list.MaxBy(x => x.Score).FirstOrDefault();

            if (mostMatching == null)
            {
                return(TellWithoutEnding("Sorry. Couldn't find the requested playlist"));
            }

            var speech = $"Found {mostMatching.Playlist.Name}, is this the correct one?";

            skillRequest.Session.SetSessionValue("PlaylistUri", mostMatching.Playlist.Uri);
            return(ResponseBuilder.Ask(speech, new Reprompt(speech), skillRequest.Session));
        }
 public static string GetSlotValue(this IntentRequest intentRequest, string slotName)
 {
     return(!intentRequest.Intent.Slots.TryGetValue(slotName, out Slot slot) ? null : slot.Value);
 }
        public override async Task <SpeechletResponse> OnIntentAsync(IntentRequest intentRequest, Session session)
        //        public override Task<SpeechletResponse> OnIntentAsync(IntentRequest intentRequest, Session session)
        {
            Trace.TraceInformation("AlexaSpeechletAsync called");

            // if the inbound request doesn't include your Alexa Skills AppId or you haven't updated your
            // code to include the correct AppId, return a visual and vocal error and do no more
            // Update the AppId variable in AlexaConstants.cs to resolve this issue

            if (AlexaUtils.IsRequestInvalid(session))
            {
                Trace.TraceInformation("AlexaSpeechletAsync InvalidApplication");
                return(await Task.FromResult <SpeechletResponse>(InvalidApplicationId(session)));
            }

            // this function is invoked when Amazon matches what the user said to
            // one of your defined intents.  now you will need to handle
            // the request

            // intentRequest.Intent.Name contains the name of the intent
            // intentRequest.Intent.Slots.* contains slot values if you're using them
            // session.User.AccessToken contains the Oauth 2.0 access token if the user has linked to your auth system

            // Get intent from the request object.
            Intent intent     = intentRequest.Intent;
            string intentName = (intent != null) ? intent.Name : null;

            // If there's no match between the intent passed and what we support, (i.e. you forgot to implement
            // a handler for the intent), default the user to the standard OnLaunch request

            // you'll probably be calling a web service to handle your intent
            // this is a good place to create an httpClient that can be recycled across REST API requests
            // don't be evil and create a ton of them unnecessarily, as httpClient doesn't clean up after itself

            var httpClient = new HttpClient();

            Trace.TraceInformation("AlexaSpeechletAsync called with intentName " + intentName);
            switch (intentName)
            {
            case "CatchAllIntent":
                try
                {
                    string resp = SendToBotFramework(session.SessionId, intentRequest.Intent.Slots["Search"].Value);

                    return(await Task.FromResult <SpeechletResponse>(AlexaUtils.BuildSpeechletResponse(
                                                                         new AlexaUtils.SimpleIntentResponse()
                    {
                        cardText = resp
                    }, true)));
                } catch (Exception ex)
                {
                    return(await Task.FromResult <SpeechletResponse>(AlexaUtils.BuildSpeechletResponse(
                                                                         new AlexaUtils.SimpleIntentResponse()
                    {
                        cardText = ex.ToString()
                    }, true)));
                }

            case "AMAZON.FallbackIntent":
                return(await Task.FromResult <SpeechletResponse>(AlexaUtils.BuildSpeechletResponse(
                                                                     new AlexaUtils.SimpleIntentResponse()
                {
                    cardText = "Decider received the Fallback Intent"
                }, true)));


            // add your own intent handler

            // case ("YourCustomIntent"):
            //   return await YourCustomIntentClass(session, whateverYouNeedToPass);
            //   invalid pattern with change // return Task.FromResult<SpeechletResponse>(YourCustomIntentClass(session, whateverYouNeedToPass));

            // did you forget to implement an intent?
            // just send the user to the intent-less utterance

            default:
                return(await Task.FromResult <SpeechletResponse>(GetOnLaunchAsyncResult(session)));
            }
        }
Пример #28
0
        //This function will extract slot value when all slots were filled
        public static void GetSlotValues(IntentRequest request, TraceWriter log, Intent updatedIntent)
        {
            var filledSlots = request.Intent.Slots;
            var intentName  = request.Intent.Name;

            //Check these values for both life expectancy and drawdown intent
            //Value in the slot is valid
            if (filledSlots["gender"].Resolution.Authorities[0].Status.Code == "ER_SUCCESS_MATCH")
            {
                Globals.userGender = filledSlots["gender"].Resolution.Authorities[0].Values[0].Value.Name;
                log.Info("gender = " + Globals.userGender);
            }
            if (filledSlots["health"].Resolution.Authorities[0].Status.Code == "ER_SUCCESS_MATCH")
            {
                Globals.userHealth = filledSlots["health"].Resolution.Authorities[0].Values[0].Value.Name;
                log.Info("health = " + Globals.userHealth);
            }
            if (filledSlots["age"].Value != "?")
            {
                Globals.userAge = Double.Parse(filledSlots["age"].Value);
                log.Info("age = " + Globals.userAge);
            }

            //Value in the slot is invalid
            if (filledSlots["gender"].Resolution.Authorities[0].Status.Code == "ER_SUCCESS_NO_MATCH")
            {
                Globals.userGender = null;
                log.Info("gender = " + Globals.userGender);
            }

            if (filledSlots["health"].Resolution.Authorities[0].Status.Code == "ER_SUCCESS_NO_MATCH")
            {
                Globals.userHealth = null;
                log.Info("health = " + Globals.userHealth);
            }

            if (filledSlots["age"].Value == "?")
            {
                Globals.userAge = -1;
                log.Info("age = " + Globals.userAge);
            }


            //Check addition values for drawdown api
            if (intentName == "DrawDown")
            {
                //Value in the slot is valid
                if (filledSlots["potSize"].Value != "?")
                {
                    Globals.userPotSize = Double.Parse(filledSlots["potSize"].Value);
                    log.Info("potSize = " + Globals.userPotSize);
                }
                if (filledSlots["potEquity"].Value != "?")
                {
                    Globals.userPotEquity = Double.Parse(filledSlots["potEquity"].Value) / 100;
                    log.Info("potEquity = " + Globals.userPotEquity);
                }
                if (filledSlots["withdrawalAmount"].Value != "?")
                {
                    Globals.userWithdrawalAmount = Double.Parse(filledSlots["withdrawalAmount"].Value);
                    log.Info("withdrawalAmount = " + Globals.userWithdrawalAmount);
                }
                if (filledSlots["potIncreaseRate"].Value != "?")
                {
                    Globals.userPotIncreaseRate = Double.Parse(filledSlots["potIncreaseRate"].Value) / 100;
                    log.Info("potIncreaseRate = " + Globals.userPotIncreaseRate);
                }

                //Caculate userPotCash by 1 - userPotEquity
                Globals.userPotCash = 1 - Globals.userPotEquity;
                log.Info("potCash = " + Globals.userPotCash);

                //Value in the slot is invalid
                if (filledSlots["potSize"].Value == "?")
                {
                    Globals.userPotSize = -1;
                    log.Info("potSize = " + Globals.userPotSize);
                }
                if (filledSlots["potEquity"].Value == "?")
                {
                    Globals.userPotEquity = -1;
                    log.Info("potEquity = " + Globals.userPotEquity);
                }
                if (filledSlots["withdrawalAmount"].Value == "?")
                {
                    Globals.userWithdrawalAmount = -1;
                    log.Info("withdrawalAmount = " + Globals.userWithdrawalAmount);
                }
                if (filledSlots["potIncreaseRate"].Value == "?")
                {
                    Globals.userPotIncreaseRate = -1;
                    log.Info("potIncreaseRate = " + Globals.userPotIncreaseRate);
                }
            }
        }
 protected abstract SkillResponse Handle(IntentRequest intentRequest, Session session, Context context);
Пример #30
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="json"></param>
        /// <returns></returns>
        public static SpeechletRequestEnvelope FromJson(JObject json)
        {
            if (json["version"] != null && json.Value <string>("version") != Sdk.VERSION)
            {
                throw new SpeechletException("Request must conform to 1.0 schema.");
            }

            SpeechletRequest request;
            JObject          requestJson = json.Value <JObject>("request");
            string           requestType = requestJson.Value <string>("type");
            string           requestId   = requestJson.Value <string>("requestId");
            DateTime         timestamp   = requestJson.Value <DateTime>("timestamp");

            switch (requestType)
            {
            case "LaunchRequest":
                request = new LaunchRequest(requestId, timestamp);
                break;

            case "IntentRequest":
                string intentName = "";
                intentName = requestJson.Value <JObject>("intent").Value <string>("name");
                if (intentName == "AMAZON.NextIntent")
                {
                    request = new AudioIntentRequest(requestId, timestamp,
                                                     Intent.FromJson(requestJson.Value <JObject>("intent")));
                    return(new SpeechletRequestEnvelope
                    {
                        Request = request,
                        Version = json.Value <string>("version"),
                        Context = Context.FromJson(json.Value <JObject>("context"))
                    });
                }
                request = new IntentRequest(requestId, timestamp,
                                            Intent.FromJson(requestJson.Value <JObject>("intent")));
                break;

            case "SessionStartedRequest":
                request = new SessionStartedRequest(requestId, timestamp);
                break;

            case "SessionEndedRequest":
                SessionEndedRequest.ReasonEnum reason;
                Enum.TryParse <SessionEndedRequest.ReasonEnum>(requestJson.Value <string>("reason"), out reason);
                request = new SessionEndedRequest(requestId, timestamp, reason);
                break;

            case "AudioPlayer.PlaybackNearlyFinished":
                request = new AudioPlayerRequest(requestId, timestamp);
                break;

            default:
                System.Diagnostics.Debug.WriteLine("Unhandled requestType" + requestType);
                throw new ArgumentException("json");
            }

            if (requestType == "AudioPlayer.PlaybackNearlyFinished")
            {
                return(new SpeechletRequestEnvelope
                {
                    Request = request,
                    Version = json.Value <string>("version"),
                    Context = Context.FromJson(json.Value <JObject>("context"))
                });
            }

            return(new SpeechletRequestEnvelope {
                Request = request,
                Session = Session.FromJson(json.Value <JObject>("session")),
                Version = json.Value <string>("version")
            });
        }