private SkillResponse ErrorResponse(Exception exc = null)
        {
            if (exc != null)
            {
                LogMessage(exc.Message, SeverityLevel.Error, new Dictionary <string, string>()
                {
                    { "Stack Trace", exc.StackTrace }
                });
            }

            var util = new Utils();
            // build the speech response
            var speech = new Alexa.NET.Response.SsmlOutputSpeech();

            speech.Ssml = $"<speak>{util.GetRandomMessage(Globals.IDidntUnderstand, false)}. Try saying 'What are today's threats' to list today's threats.</speak>";

            // create the speech reprompt
            var repromptMessage = new Alexa.NET.Response.PlainTextOutputSpeech();

            repromptMessage.Text = "Try saying 'What are today's threats' to list today's threats.";

            // create the reprompt
            var reprompt = new Alexa.NET.Response.Reprompt();

            reprompt.OutputSpeech = repromptMessage;

            // create the response using the ResponseBuilder
            var finalResponse = ResponseBuilder.Ask(speech, reprompt);

            return(finalResponse);
        }
Ejemplo n.º 2
0
        public SsmlOutputSpeech HandleNearbyAircraftIntent(IntentRequest intentRequest)
        {
            // build the speech response
            var speech = new Alexa.NET.Response.SsmlOutputSpeech();

            Slot distanceSlot      = null;
            Slot distanceUnitsSlot = null;

            intentRequest.Intent.Slots?.TryGetValue("distance", out distanceSlot);
            intentRequest.Intent.Slots?.TryGetValue("distanceUnits", out distanceUnitsSlot);

            double distanceValue = distanceSlot != null?Convert.ToDouble(distanceSlot.Value) : 20;

            string distanceUnitsValue = distanceUnitsSlot != null ? distanceUnitsSlot.Value : "kilometres";

            var distance = Distance.FromKilometres(distanceValue);

            var location = new GeoLocation(52.041808, 1.208131);
            var north    = GeoLocation.FindPointAtDistanceFrom(location, Angle.FromDegrees(0), distance);
            var south    = GeoLocation.FindPointAtDistanceFrom(location, Angle.FromDegrees(180), distance);
            var east     = GeoLocation.FindPointAtDistanceFrom(location, Angle.FromDegrees(90), distance);
            var west     = GeoLocation.FindPointAtDistanceFrom(location, Angle.FromDegrees(270), distance);
            var flights  = FlightRadar24.GetFlights(north.Latitude, south.Latitude, east.Longitude, west.Longitude);

            if (flights == null)
            {
                speech.Ssml = "I'm unable to contact Flight Radar.";
                return(speech);
            }

            var withinRangeOrderedByClosest = (from sighting in flights.Sightings
                                               let d = GeoLocation.DistanceBetween(sighting.Location, location)
                                                       where d.Kilometres < distance.Kilometres
                                                       orderby d.Kilometres descending
                                                       select new { sighting, d }).ToArray();



            if (withinRangeOrderedByClosest.Length == 0)
            {
                speech.Ssml = "There are no flights within {distanceValue} {distanceUnitsValue}.";
                return(speech);
            }

            var closest = withinRangeOrderedByClosest.First();
            var bearing = GeoLocation.RhumbBearing(location, closest.sighting.Location).Degrees;

            var id = AddIndefiniteArticle(closest.sighting.AircraftType) + (closest.sighting.FlightNumber != null
                ? $", flight {closest.sighting.FlightNumber}"
                : "");
            var destination = closest.sighting.Arrving != null ? $"to {closest.sighting.Arrving}" : "";
            var callsign    = closest.sighting.CallSign != null? $"{closest.sighting.CallSign}":"";

            speech.Ssml = $"<speak>There {GetIsOrAre(withinRangeOrderedByClosest.Length)} {withinRangeOrderedByClosest.Length} aircraft within {distanceValue:N0} {distanceUnitsValue}. The closest is {callsign} {destination}, range {closest.d.Kilometres:N0} kilometres, bearing {bearing:N0}, travelling at {closest.sighting.GroundSpeedKts} knots and altitude {Distance.FromFeet(closest.sighting.AltitudeFt).Metres:N0} metres.</speak>";
            return(speech);
        }
Ejemplo n.º 3
0
        private SkillResponse CreateResponse(string message)
        {
            var speech = new Alexa.NET.Response.SsmlOutputSpeech();

            speech.Ssml = $"<speak>{ message }</speak>";

            var finalResponse = ResponseBuilder.TellWithCard(speech, "Roxanne", message);

            return(finalResponse);
        }
Ejemplo n.º 4
0
        private SkillResponse VoiceResponse(string text)
        {
            var speech = new Alexa.NET.Response.SsmlOutputSpeech
            {
                Ssml = string.Format("<speak>{0}</speak>", text)
            };

            var finalResponse = Alexa.NET.ResponseBuilder.Tell(speech);

            return(finalResponse);
        }
Ejemplo n.º 5
0
        private SkillResponse HandleLaunchRequest(SkillRequest input, ILambdaContext context)
        {
            // build the speech response
            var speech = new Alexa.NET.Response.SsmlOutputSpeech
            {
                Ssml = "<speak>This is Air Traffic. Go ahead with your request, or ask for help</speak>"
            };
            // create the response using the ResponseBuilder
            var finalResponse = ResponseBuilder.Tell(speech);

            finalResponse.Response.ShouldEndSession = false;
            return(finalResponse);
        }
        private SkillResponse Exit()
        {
            var util = new Utils();
            // build the speech response
            var speech = new Alexa.NET.Response.SsmlOutputSpeech();

            speech.Ssml = $"<speak>{util.GetRandomMessage(Globals.GoodBye, false)}</speak>";

            // create the response using the ResponseBuilder
            var finalResponse = ResponseBuilder.Tell(speech);

            return(finalResponse);
        }
Ejemplo n.º 7
0
        //private SkillResponse HandleAudioPlayerRequest(SkillRequest input, ILambdaContext context)
        //{
        //    // do some audio response stuff
        //    var audioRequest = input.Request as AudioPlayerRequest;

        //    // these are events sent when the audio state has changed on the device
        //    // determine what exactly happened
        //    if (audioRequest.AudioRequestType == AudioRequestType.PlaybackNearlyFinished)
        //    {
        //        // queue up another audio file
        //    }
        //}

        private SkillResponse HandleIntentRequest(SkillRequest input, ILambdaContext context)
        {
            // do some intent-based stuff
            var intentRequest = input.Request as IntentRequest;
            // build the speech response
            var speech = new Alexa.NET.Response.SsmlOutputSpeech();

            // check the name to determine what you should do
            if (intentRequest.Intent.Name.Equals("AMAZON.HelpIntent"))
            {
                // build the speech response

                speech.Ssml = "<speak>I can tell you about aircraft flying near your position or over a specific place. You can ask questions like what is nearby? how many flights are within 20 miles? and, what is south of me? You can also set your specific location for more accurate results.</speak>";
            }

            if (intentRequest.Intent.Name.Equals("AIRTRAFFICnearbyAircraft"))
            {
                speech = HandleNearbyAircraftIntent(intentRequest);
            }



            //with card response
            //var finalResponse = ResponseBuilder.TellWithCard(speech, "Your Card Title", "Your card content text goes here, no HTML formatting honored");

            // create the response using the ResponseBuilder
            var finalResponse = ResponseBuilder.Tell(speech);

            return(finalResponse);

            //Build a simple response with a reprompt
            //// create the speech response
            //var speech = new Alexa.NET.Response.SsmlOutputSpeech();
            //speech.Ssml = "<speak>Today is <say-as interpret-as=\"date\">????0922</say-as>.</speak>";

            //// create the speech reprompt
            //var repromptMessage = new Alexa.NET.Response.PlainTextOutputSpeech();
            //repromptMessage.Text = "Would you like to know what tomorrow is?";

            //// create the reprompt
            //var repromptBody = new Alexa.NET.Response.Reprompt();
            //repromptBody.OutputSpeech = repromptMessage;

            //// create the response
            //var finalResponse = ResponseBuilder.Ask(speech, repromptBody);
            //return finalResponse;
        }
Ejemplo n.º 8
0
        public SkillResponse FunctionHandler(SkillRequest input, ILambdaContext context)
        {
            var logger      = context.Logger;
            var requestType = input.GetRequestType();

            if (requestType == typeof(Alexa.NET.Request.Type.LaunchRequest))
            {
                logger.Log("Launch Request");
            }

            var speech = new Alexa.NET.Response.SsmlOutputSpeech();

            speech.Ssml = "<speak>Hello, Code Camp!</speak>";

            var finalResponse = ResponseBuilder.Tell(speech);

            return(finalResponse);
        }
Ejemplo n.º 9
0
        private SkillResponse ResponseReprompt(string text, string reprompt)
        {
            var speech = new Alexa.NET.Response.SsmlOutputSpeech();

            speech.Ssml = "<speak> " + text + " </speak>";

            var repromptMessage = new Alexa.NET.Response.PlainTextOutputSpeech();

            repromptMessage.Text = "<speak> " + reprompt + " </speak>";

            // create the reprompt
            var repromptBody = new Alexa.NET.Response.Reprompt();

            repromptBody.OutputSpeech = repromptMessage;
            var finalResponse = ResponseBuilder.Ask(speech, repromptBody);

            return(finalResponse);
        }
Ejemplo n.º 10
0
        private SkillResponse safetyIntent(ApplicationUser user, Fulfillment fulfillment, AlexaSession session)
        {
            sendsafetyAlert(user);
            //Update skill-specific fulfillment info
            fulfillment.Note     = "Alert sent to Emergency Contact";
            fulfillment.Type     = FulfillmentType.High;
            fulfillment.Category = FulfillmentCategory.Safety;
            fulfillment.Status   = FulfillmentStatus.Fulfilled;

            user.AlexaSessions.Add(session);
            user.Fulfillments.Add(fulfillment);
            _context.SaveChanges();

            //Generate Alexa request
            var safetyResponse = new Alexa.NET.Response.SsmlOutputSpeech();

            safetyResponse.Ssml = "<speak>I have sent an alert to your emergency contact.</speak>";
            return(ResponseBuilder.Tell(safetyResponse));
        }
        private SkillResponse BuildResponse(string cardTitle, string plainTextContent, string ssml = "")
        {
            var speech = new Alexa.NET.Response.SsmlOutputSpeech();

            speech.Ssml = (ssml.Length > 0 ? ssml : $"<speak>{plainTextContent}</speak>");

            //add this back in when we support multiple dates
            //// create the speech reprompt
            //var repromptMessage = new Alexa.NET.Response.PlainTextOutputSpeech();
            //repromptMessage.Text = "Can I help you with anything else?";
            //// create the reprompt
            //var repromptBody = new Alexa.NET.Response.Reprompt();
            //repromptBody.OutputSpeech = repromptMessage;
            //var finalResponse = ResponseBuilder.AskWithCard(speech, cardTitle, plainTextContent, repromptBody);


            var finalResponse = ResponseBuilder.TellWithCard(speech, cardTitle, plainTextContent);

            return(finalResponse);
        }
Ejemplo n.º 12
0
        private SkillResponse requestRideIntent(Dictionary <string, Alexa.NET.Request.Slot> slots, ApplicationUser user, Fulfillment fulfillment, AlexaSession session)
        {
            Slot daySlot  = slots["day"];
            Slot timeSlot = slots["time"];

            fulfillment.Note     = "Ride requested. " + daySlot.Value + " " + timeSlot.Value;
            fulfillment.Type     = FulfillmentType.Medium;
            fulfillment.Category = FulfillmentCategory.Community;
            fulfillment.Status   = FulfillmentStatus.Unfulfilled;

            user.AlexaSessions.Add(session);
            user.Fulfillments.Add(fulfillment);
            _context.SaveChanges();

            //Generate Alexa request
            var safetyResponse = new Alexa.NET.Response.SsmlOutputSpeech();

            safetyResponse.Ssml = "<speak>I have entered a fulfillment request for a ride. You should receive a confirmation in the next 24 hours for your ride"
                                  + " on " + daySlot.Value + " " + timeSlot.Value + "</speak>";
            return(ResponseBuilder.Tell(safetyResponse));
        }
        private SkillResponse Help()
        {
            // create the speech response - cards still need a voice response
            var speech = new Alexa.NET.Response.SsmlOutputSpeech();

            speech.Ssml = $"<speak>Do you worry about space-based threats to earth such as asteroids and other near earth objects? {Globals.FriendlyAppTitle} will let you know what's out there zooming towards us.</speak>";

            // create the speech reprompt
            var repromptMessage = new Alexa.NET.Response.PlainTextOutputSpeech();

            repromptMessage.Text = "Try saying 'What are today's threats?'";

            // create the reprompt
            var repromptBody = new Alexa.NET.Response.Reprompt();

            repromptBody.OutputSpeech = repromptMessage;

            var finalResponse = ResponseBuilder.Ask(speech, repromptBody);

            return(finalResponse);
        }
        private SkillResponse FallbackHelp()
        {
            // create the speech response - cards still need a voice response
            var speech = new Alexa.NET.Response.SsmlOutputSpeech();

            speech.Ssml = $"<speak>{_util.GetRandomMessage(Globals.IDidntUnderstand)}. You might try 'What are today's threats?'</speak>";

            // create the speech reprompt
            var repromptMessage = new Alexa.NET.Response.PlainTextOutputSpeech();

            repromptMessage.Text = "Try saying 'What are today's threats?'";

            // create the reprompt
            var repromptBody = new Alexa.NET.Response.Reprompt();

            repromptBody.OutputSpeech = repromptMessage;

            var finalResponse = ResponseBuilder.Ask(speech, repromptBody);

            return(finalResponse);
        }
Ejemplo n.º 15
0
        //public void FunctionHandler(DynamoDBEvent dynamoEvent, ILambdaContext context)
        //{
        //    context.Logger.LogLine($"Beginning to process {dynamoEvent.Records.Count} records...");

        //    foreach (var record in dynamoEvent.Records)
        //    {
        //        context.Logger.LogLine($"Event ID: {record.EventID}");
        //        context.Logger.LogLine($"Event Name: {record.EventName}");

        //        string streamRecordJson = SerializeStreamRecord(record.Dynamodb);
        //        context.Logger.LogLine($"DynamoDB Record:");
        //        context.Logger.LogLine(streamRecordJson );
        //    }

        //    context.Logger.LogLine("Stream processing complete.");
        //}

        //private string SerializeStreamRecord(StreamRecord streamRecord)
        //{
        //    using (var writer = new StringWriter())
        //    {
        //        _jsonSerializer.Serialize(writer, streamRecord);
        //        return writer.ToString();
        //    }
        //}


        // Details here: https://github.com/timheuer/alexa-skills-dotnet


        public SkillResponse FunctionHandler(SkillRequest input, ILambdaContext context)
        {
            var requestType = input.GetRequestType();
            var speech      = new Alexa.NET.Response.SsmlOutputSpeech();

            speech.Ssml = "<speak>No mataches have been found.</speak>";


            if (requestType == typeof(IntentRequest))
            {
                // do some intent-based stuff
                var intentRequest = input.Request as IntentRequest;
                speech.Ssml = "<speak>Intent recognised.</speak>";
                // check the name to determine what you should do
                if (intentRequest.Intent.Name.Equals("TestIntent"))
                {
                    // get the slots
                    var firstValue = intentRequest.Intent.Slots["date"].Value;
                    speech.Ssml = "<speak>Slot recognised: " + firstValue + ".</speak>";
                }
            }
            else if (requestType == typeof(Alexa.NET.Request.Type.LaunchRequest))
            {
                // default launch path executed
                speech.Ssml = "<speak>Skill launched.</speak>";
            }
            else if (requestType == typeof(AudioPlayerRequest))
            {
                // do some audio response stuff
                speech.Ssml = "<speak>Audio.</speak>";
            }

            // build the speech response
            var dt = DateTime.Now;

            // create the response using the ResponseBuilder
            var finalResponse = ResponseBuilder.Tell(speech);

            return(finalResponse);
        }
        private SkillResponse Usage()
        {
            var commonUsage = "You can say 'What are today's threats?' to list today's space-based threats to earth, or say Help to get more information.";

            // create the speech response - cards still need a voice response
            var speech = new Alexa.NET.Response.SsmlOutputSpeech();

            speech.Ssml = $"<speak>Welcome to {Globals.FriendlyAppTitle}. {commonUsage}</speak>";

            // create the speech reprompt
            var repromptMessage = new Alexa.NET.Response.PlainTextOutputSpeech();

            repromptMessage.Text = commonUsage;

            // create the reprompt
            var repromptBody = new Alexa.NET.Response.Reprompt();

            repromptBody.OutputSpeech = repromptMessage;

            var finalResponse = ResponseBuilder.Ask(speech, repromptBody);

            return(finalResponse);
        }
Ejemplo n.º 17
0
        /// <summary>
        /// A simple function that takes a string and does a ToUpper
        /// </summary>
        /// <param name="input"></param>
        /// <param name="context"></param>
        /// <returns></returns>
        //public string FunctionHandler(string input, ILambdaContext context)
        //{
        //	return input?.ToUpper();
        //}
        public SkillResponse FunctionHandler(SkillRequest input, ILambdaContext context)
        {
            var intentRequest = input.Request as IntentRequest;
            var name          = intentRequest.Intent.Slots["Name"].Value;
            var action        = intentRequest.Intent.Slots["Action"].Value;

            var speak = new AlexaSpeak();

            foreach (var item in intentRequest.Intent.Slots)
            {
                speak.Normal($"{item.Value.Name}");
                speak.Break(AlexaSpeak.BreakStrength.x_strong);
                speak.Normal(item.Value.Value);
                speak.Break(AlexaSpeak.BreakStrength.x_strong);
            }

            speak
            .Break(AlexaSpeak.BreakStrength.x_strong)
            .Normal($"Hallo {name}")
            .Normal($"Du musst jetzt also {action}")
            //				.Volume("Guten morgen", AlexaSpeak.ProsodyVolume.soft)
            .Break(AlexaSpeak.BreakStrength.medium)
            .Pitch("Was machen wir denn jetzt?", AlexaSpeak.ProsodyPitch.low)
            .Break(AlexaSpeak.BreakStrength.medium)
            .Volume(speak.GetWhisper("Wollen wir uns verstecken?"), AlexaSpeak.ProsodyVolume.x_loud)
            ;

            var speech = new Alexa.NET.Response.SsmlOutputSpeech();

            //speech.Ssml = "<speak>Today is <say-as interpret-as=\"date\">????0922</say-as>.<break strength=\"x-strong\"/>I hope you have a good day.</speak>";
            speech.Ssml = speak.ToString();

            // create the response using the ResponseBuilder
            var finalResponse = ResponseBuilder.Tell(speech);

            return(finalResponse);
        }
Ejemplo n.º 18
0
        private SkillResponse medicalDataIntent(ApplicationUser user, Fulfillment fulfillment, AlexaSession session)
        {
            //Update skill-specific fulfillment info
            fulfillment.Note     = "User requested Medical Data Update";
            fulfillment.Category = FulfillmentCategory.Safety;
            fulfillment.Status   = FulfillmentStatus.Fulfilled;

            user.AlexaSessions.Add(session);
            user.Fulfillments.Add(fulfillment);
            _context.SaveChanges();

            var medicalResponse            = new Alexa.NET.Response.SsmlOutputSpeech();
            MedicalSensorData medicalData  = user.MedicalSensorData.Last();
            string            healthString = "";

            if (medicalData != null)
            {
                if (medicalData.health == true)
                {
                    healthString         = "You are healthy!";
                    medicalResponse.Ssml = "<speak>" + healthString + "</speak>";
                }
                else
                {
                    healthString         = "You aren't healthy.";
                    medicalResponse.Ssml = "<speak>" + healthString + "</speak>";
                }

                return(ResponseBuilder.Tell(medicalResponse));
            }
            else
            {
                medicalResponse.Ssml = "<speak>" + "An error occured, please try again." + "</speak>";
            }
            return(ResponseBuilder.Tell(medicalResponse));
        }
        public async Task <dynamic> Post([FromBody] SkillRequest input)
        {
            var speech        = new Alexa.NET.Response.SsmlOutputSpeech();
            var finalResponse = new SkillResponse();

            finalResponse.Version = "1.0";
            // check what type of a request it is like an IntentRequest or a LaunchRequest
            var requestType = input.GetRequestType();

            if (requestType == typeof(IntentRequest))
            {
                // do some intent-based stuff
                var intentRequest = input.Request as IntentRequest;

                // check the name to determine what you should do
                if (intentRequest.Intent.Name.Equals("GetPoints"))
                {
                    try
                    {
                        long?points = 0;
                        var  client = new CustomApiClient();
                        var  result = await client.QueryPointsAsync("API", "EXTERNAL", 1, "921722255", ParamType.Msisdn, 1, null, "WALLET_DEFAULT", null, null, false, null, null, null);

                        if (result != null)
                        {
                            foreach (var wallet in result.Wallets)
                            {
                                points = points + wallet.Points;
                            }
                        }
                        //// create the speech response - cards still need a voice response
                        //speech.Ssml = $"<speak>You currently have {points} loyalty points available in your account.</speak>";
                        //// create the card response
                        //finalResponse = ResponseBuilder.TellWithCard(speech, "GetPoints", $"You currently have {points} loyalty points available in your account.");

                        //_cache.sa
                        // create the speech response - cards still need a voice response
                        speech.Ssml = $"<speak>You currently have {points} loyalty points available in your account.</speak>";

                        // create the speech reprompt
                        var repromptMessage = new PlainTextOutputSpeech();
                        repromptMessage.Text = "Anything else you might want to do?";

                        // create the reprompt
                        var repromptBody = new Alexa.NET.Response.Reprompt();
                        repromptBody.OutputSpeech = repromptMessage;

                        // create the response
                        finalResponse = ResponseBuilder.AskWithCard(speech, "GetPoints", $"You currently have {points} loyalty points available in your account.", repromptBody);
                    }
                    catch (Exception e)
                    {
                        // create the speech response - cards still need a voice response
                        speech.Ssml = $"<speak>Oh boy, something went very wrong. {e.Message}</speak>";
                        // create the card response
                        finalResponse = ResponseBuilder.TellWithCard(speech, "GetPoints Exception", $"Oh boy, something went very wrong. {e.Message}.");
                    }
                }
                // check the name to determine what you should do
                if (intentRequest.Intent.Name.Equals("GetItems"))
                {
                    try
                    {
                        string      items       = string.Empty;
                        SessionData sessionData = null;
                        var         client      = new CustomApiClient();
                        var         result      = await client.QueryAvailableItemsAsync("API", "EXTERNAL", 1, "921722255", ParamType.Msisdn, 1, null, null, null, null, null);

                        if (result != null)
                        {
                            //items = string.Join(", ", result.Items.Select(z => z.Name));
                            redeemableItems.AddRange(result.Items);
                            items = string.Join(", ", redeemableItems.Select(z => z.Name));
                            var value = await _cache.GetStringAsync(input.Session.SessionId);

                            if (value != null)
                            {
                                sessionData = JsonConvert.DeserializeObject <SessionData>(value);
                            }
                            if (sessionData != null)
                            {
                                sessionData.RedeemableItems = redeemableItems;
                            }
                            else
                            {
                                sessionData = new SessionData {
                                    SessionId = input.Session.SessionId, PurchaseItems = purchaseItems, RedeemableItems = redeemableItems
                                };
                            }
                            await _cache.SetStringAsync(input.Session.SessionId, JsonConvert.SerializeObject(sessionData));
                        }
                        // create the speech response - cards still need a voice response
                        speech.Ssml = $"<speak>Here is the list of items available for you: {items}.</speak>";
                        // create the card response
                        //finalResponse = ResponseBuilder.TellWithCard(speech, "GetItems", $"Here is the list of items available for you: {items}.");

                        // create the speech reprompt
                        var repromptMessage = new PlainTextOutputSpeech();
                        repromptMessage.Text = "Would you like to add any of these to your shoping cart?";

                        // create the reprompt
                        var repromptBody = new Alexa.NET.Response.Reprompt();
                        repromptBody.OutputSpeech = repromptMessage;

                        // create the response
                        finalResponse = ResponseBuilder.AskWithCard(speech, "GetItems", $"Here is the list of items available for you: {items}.", repromptBody);
                    }
                    catch (Exception e)
                    {
                        // create the speech response - cards still need a voice response
                        speech.Ssml = $"<speak>Oh boy, something went very wrong. {e.Message}</speak>";
                        // create the card response
                        finalResponse = ResponseBuilder.TellWithCard(speech, "GetItems Exception", $"Oh boy, something went very wrong. {e.Message}.");
                    }
                }
                // check the name to determine what you should do
                if (intentRequest.Intent.Name.Equals("AddToBasket"))
                {
                    try
                    {
                        SessionData       sessionData = null;
                        RedeemableItem    itemR       = null;
                        PurchaseOrderItem itemP       = null;
                        string            itemName    = string.Empty;
                        int itemNo = int.Parse(intentRequest.Intent.Slots["Item"].Value);


                        var value = await _cache.GetStringAsync(input.Session.SessionId);

                        if (value != null)
                        {
                            sessionData = JsonConvert.DeserializeObject <SessionData>(value);
                        }

                        if (sessionData != null)
                        {
                            if (sessionData.RedeemableItems != null && sessionData.RedeemableItems.Count > 0)
                            {
                                redeemableItems = sessionData.RedeemableItems;
                                if ((itemNo - 1) > sessionData.RedeemableItems.Count || (itemNo - 1) < 0)
                                {
                                    throw new Exception("Sorry, you don't have that item.");
                                }
                                itemR = redeemableItems[itemNo - 1];
                                if (sessionData.PurchaseItems != null)
                                {
                                    purchaseItems = sessionData.PurchaseItems;
                                    purchaseItems.Add(new PurchaseOrderItem {
                                        DeliveryChannel = null, Quantity = 1, RedeemableItemId = itemR.Id, WalletType = new WalletType {
                                            ExternalCode = "WALLET_DEFAULT"
                                        }
                                    });
                                }
                                //else
                                //{
                                //    purchaseItems.Add(new PurchaseOrderItem { DeliveryChannel = null, Quantity = 1, RedeemableItemId = itemR.Id, WalletType = null });
                                //}
                            }
                            else
                            {
                                throw new Exception("Please query for your ityems first.");
                            }
                        }
                        else
                        {
                            sessionData = new SessionData {
                                SessionId = input.Session.SessionId, PurchaseItems = purchaseItems, RedeemableItems = redeemableItems
                            };
                        }
                        await _cache.SetStringAsync(input.Session.SessionId, JsonConvert.SerializeObject(sessionData));


                        purchaseItems.Add(new PurchaseOrderItem {
                            DeliveryChannel = null, Quantity = 1, RedeemableItemId = itemR.Id, WalletType = null
                        });

                        // create the speech response - cards still need a voice response
                        speech.Ssml = $"<speak>Your item, {itemR.Name}, was successfully added to shopping cart.</speak>";

                        // create the speech reprompt
                        var repromptMessage = new PlainTextOutputSpeech();
                        repromptMessage.Text = "Shall I proceed and buy the items in the shoping cart? You can add more items as well.";

                        // create the reprompt
                        var repromptBody = new Alexa.NET.Response.Reprompt();
                        repromptBody.OutputSpeech = repromptMessage;

                        // create the response
                        finalResponse = ResponseBuilder.AskWithCard(speech, "AddToBasket", $"Your item, {itemR.Name}, was successfully added to shopping cart.", repromptBody);
                    }
                    catch (Exception e)
                    {
                        // create the speech response - cards still need a voice response
                        speech.Ssml = $"<speak>Oh boy, something went very wrong. {e.Message}</speak>";
                        // create the card response
                        finalResponse = ResponseBuilder.TellWithCard(speech, "AddToBasket Exception", $"Oh boy, something went very wrong. {e.Message}.");
                    }
                }
                // check the name to determine what you should do
                if (intentRequest.Intent.Name.Equals("PurchaseBasket"))
                {
                    try
                    {
                        SessionData sessionData = null;
                        string      status      = string.Empty;

                        var value = await _cache.GetStringAsync(input.Session.SessionId);

                        if (value != null)
                        {
                            sessionData = JsonConvert.DeserializeObject <SessionData>(value);
                        }
                        if (sessionData != null && sessionData.PurchaseItems != null && sessionData.PurchaseItems.Count > 0)
                        {
                            purchaseItems = sessionData.PurchaseItems;
                        }
                        else
                        {
                            throw new Exception("Your shoping cart is empty. Add some items first.");
                        }

                        await _cache.RemoveAsync(input.Session.SessionId);

                        var client = new CustomApiClient();
                        // var result = await client.RedeemItemsAsync("API", "EXTERNAL", 1, "921722255", ParamType.Msisdn, 1, null, purchaseItems.ToArray(), null, null, null);
                        var result = await client.RedeemItemsAsync("API", "EXTERNAL", 1, "921722255", ParamType.Msisdn, 1, null, purchaseItems.ToArray(), null, null, null);

                        if (result != null)
                        {
                            status = result.Status.ToString();
                        }

                        // create the speech response - cards still need a voice response
                        speech.Ssml = $"<speak>Your order completed with {status}. Thank you for using our services.</speak>";

                        // create the response
                        finalResponse = ResponseBuilder.TellWithCard(speech, "PurchaseBasket", $"Your order completed with {status}. Thank you for using our services.");
                    }
                    catch (Exception e)
                    {
                        // create the speech response - cards still need a voice response
                        speech.Ssml = $"<speak>Oh boy, something went very wrong. {e.Message}</speak>";
                        // create the card response
                        finalResponse = ResponseBuilder.TellWithCard(speech, "PurchaseBasket Exception", $"Oh boy, something went very wrong. {e.Message}.");
                    }
                }
                if (intentRequest.Intent.Name.Equals("AMAZON.CancelIntent"))
                {
                    try
                    {
                        await _cache.RemoveAsync(input.Session.SessionId);

                        List <string> myList = new List <string> {
                            "OK,I'll shut up.", "Sure, I'll cleanup everything.", "Oh boy, that escalated quickly! I'm outa here!"
                        };
                        // add items to the list
                        Random r     = new Random();
                        int    index = r.Next(myList.Count);

                        // create the speech response - cards still need a voice response
                        speech.Ssml = $"<speak>{myList[index]}</speak>";

                        // create the response
                        finalResponse = ResponseBuilder.TellWithCard(speech, "Cancel Exception", $"{myList[index]}");
                    }
                    catch (Exception e)
                    {
                        // create the speech response - cards still need a voice response
                        speech.Ssml = $"<speak>Oh boy, something went very wrong. {e.Message}</speak>";
                        // create the card response
                        finalResponse = ResponseBuilder.TellWithCard(speech, "Cancel Exception", $"Oh boy, something went very wrong. {e.Message}.");
                    }
                }

                if (intentRequest.Intent.Name.Equals("Hello"))
                {
                    try
                    {
                        await _cache.RemoveAsync(input.Session.SessionId);

                        List <string> myList = new List <string> {
                            "Hi there!", "Hi, how are you.", "Hi and goodby. get back to work"
                        };
                        // add items to the list
                        Random r     = new Random();
                        int    index = r.Next(myList.Count);

                        // create the speech response - cards still need a voice response
                        speech.Ssml = $"<speak>{myList[index]}</speak>";

                        // create the response
                        finalResponse = ResponseBuilder.TellWithCard(speech, "Hello", $"{myList[index]}");
                    }
                    catch (Exception e)
                    {
                        // create the speech response - cards still need a voice response
                        speech.Ssml = $"<speak>Oh boy, something went very wrong. {e.Message}</speak>";
                        // create the card response
                        finalResponse = ResponseBuilder.TellWithCard(speech, "Cancel Exception", $"Oh boy, something went very wrong. {e.Message}.");
                    }
                }
            }
            else if (requestType == typeof(Alexa.NET.Request.Type.LaunchRequest))
            {
                // default launch path executed
            }
            else if (requestType == typeof(AudioPlayerRequest))
            {
                // do some audio response stuff
            }

            return(finalResponse);
        }
Ejemplo n.º 20
0
        //TODO: Use Alexa.NET.Middleware to verify requests come from Amazon
        public SkillResponse ProcessRequest(SkillRequest _skillRequest)
        {
            ApplicationUser user;
            var             intentRequest = _skillRequest.Request as IntentRequest;
            var             speech        = new Alexa.NET.Response.SsmlOutputSpeech();
            var             response      = new SkillResponse();

            //Get User which triggered request
            //var queryResult = _userManager.Users
            //  .Single(b => b.AlexaID == _skillRequest.Session.User.UserId);
            var queryResult = _userManager.Users;

            var queryuser = queryResult.Single(b => b.AlexaID == _skillRequest.Session.User.UserId);

            user = _context.Users.Include(ApplicationUser => ApplicationUser.AlexaSessions)
                   .Include(ApplicationUser => ApplicationUser.MedicalSensorData)
                   .Include(ApplicationUser => ApplicationUser.Fulfillments)
                   .Single(u => u.Id == queryuser.Id);

            if (user != null)
            {
                //Generate fulfillment record
                Fulfillment fulfillment = new Fulfillment()
                {
                    DeviceID  = _skillRequest.Context.System.Device.DeviceID,
                    Timestamp = _skillRequest.Request.Timestamp,
                    Source    = FulfillmentSource.Alexa
                };

                //Generate Alexa Intent History
                AlexaSession newSession = new AlexaSession()
                {
                    ApplicationUser = user,
                    Type            = _skillRequest.Request.Type,
                    RequestId       = _skillRequest.Request.RequestId,
                    Locale          = _skillRequest.Request.Locale,
                    Timestamp       = _skillRequest.Request.Timestamp,
                    ApiAccessToken  = _skillRequest.Context.System.ApiAccessToken,
                    ApiEndpoint     = _skillRequest.Context.System.ApiEndpoint,
                    UserId          = _skillRequest.Session.User.UserId,
                    DeviceID        = _skillRequest.Context.System.Device.DeviceID,
                    Fulfillment     = fulfillment
                };

                switch (intentRequest.Intent.Name)
                {
                case "sendalert":
                    return(safetyIntent(user, fulfillment, newSession));

                case "displayMedicalSummaryIntent":
                    return(medicalDataIntent(user, fulfillment, newSession));

                case "requestRide":
                    return(requestRideIntent(intentRequest.Intent.Slots, user, fulfillment, newSession));

                default:
                    var defaultResponse = new Alexa.NET.Response.SsmlOutputSpeech();
                    defaultResponse.Ssml          = "<speak>An error occured, please try again.</speak>";
                    response                      = ResponseBuilder.Tell(defaultResponse);
                    newSession.Fulfillment.Status = FulfillmentStatus.Unfulfilled;
                    return(response);
                }
            }
            else
            {
                speech.Ssml = "<speak>Please try again. Error 1</speak>";
                response    = ResponseBuilder.Tell(speech);
            }
            return(response);
        }
Ejemplo n.º 21
0
 public Reprompt(Ssml.Speech speech)
 {
     OutputSpeech = new SsmlOutputSpeech {
         Ssml = speech.ToXml()
     };
 }
Ejemplo n.º 22
0
        /// <summary>
        /// A simple Amazon Skill Example which uses the Epicor REST API
        /// </summary>
        /// <param name="input"></param>
        /// <param name="context"></param>
        /// <returns></returns>
        public SkillResponse FunctionHandler(SkillRequest input, ILambdaContext context)
        {
            //Get Access to the AWS Lambda Logger to see the status of our request
            var log = context.Logger;

            //Get the Request Type
            var requestType = input.GetRequestType();

            SkillResponse resp = null;

            //This will be said to the user after every response as a way to "reprompt" (continue)
            var reprompt = new Alexa.NET.Response.Reprompt
            {
                OutputSpeech = new PlainTextOutputSpeech()
                {
                    Text = "For a list of available commands say, Help!. What woudl you like to do?"
                }
            };

            //When the skill initially launches, give them some helpful info
            if (requestType == typeof(LaunchRequest))
            {
                log.LogLine("INFO: Initial Launch Request");

                var speech = new Alexa.NET.Response.SsmlOutputSpeech()
                {
                    Ssml = string.Format(@"<speak>Welcome to this sample Alexa Skill using the Epicor REST API. For a list of available commands say help. What would you like to do? </speak>")
                };

                resp = ResponseBuilder.Ask(speech, reprompt);
            }
            //If they askef for something specific, figure out what and respond accordingly.
            else if (requestType == typeof(IntentRequest))
            {
                var intent = input.Request as IntentRequest;
                log.LogLine($"INFO: Launched Intent:{intent.Intent.Name}");

                switch (intent.Intent.Name)
                {
                //If they involved the RunSampleBAQ Intent
                case "RunSampleBAQ":
                {
                    var speech = new Alexa.NET.Response.SsmlOutputSpeech();
                    log.LogLine($"INFO: Running BAQ");
                    speech.Ssml = RunSampleBAQ();
                    resp        = ResponseBuilder.Ask(speech, reprompt);
                }
                break;

                //If they involved the GetCompanyInfo intent
                case "GetCompanyInfo":
                {
                    var speech = new Alexa.NET.Response.SsmlOutputSpeech();
                    log.LogLine($"INFO: Getting Company Info");
                    speech.Ssml = GetCompanyInfo();
                    resp        = ResponseBuilder.Ask(speech, reprompt);
                }
                break;

                case "AMAZON.HelpIntent":
                {
                    try
                    {
                        log.LogLine("Launched Help intent");
                        StringBuilder sbCommandList = new StringBuilder();
                        sbCommandList.AppendLine($"<speak>Available commands are: <break strength='medium' />");
                        sbCommandList.AppendLine($"Run Sample BAQ <break strength='medium' />");
                        sbCommandList.AppendLine($"Get Company Info,<break strength='medium' />");
                        sbCommandList.AppendLine($"What would you like to do?</speak>");
                        log.LogLine("Finished building command List");
                        var speech = new SsmlOutputSpeech()
                        {
                            Ssml = sbCommandList.ToString()
                        };
                        log.LogLine("Assigned Response");
                        resp = ResponseBuilder.Ask(speech, reprompt);
                    }
                    catch (Exception e)
                    {
                        log.LogLine(e.ToString());
                    }
                }
                break;

                case "AMAZON.StopIntent":
                {
                    var speech = new SsmlOutputSpeech()
                    {
                        Ssml = "<speak>Thank you for Trying out this Sample Skill<break strength='medium' />. Good bye.</speak>"
                    };
                    resp = ResponseBuilder.Tell(speech);
                }
                break;

                case "AMAZON.CancelIntent":
                {
                    var speech = new SsmlOutputSpeech()
                    {
                        Ssml = "<speak>Good bye.</speak>"
                    };
                    resp = ResponseBuilder.Tell(speech);
                }
                break;

                case "Unhandled":
                default:
                {
                    var speech = new PlainTextOutputSpeech()
                    {
                        Text = "Ut oh, you've somehow ended in an unhandled intent... You shouldn't be here, GET OUT!"
                    };
                    resp = ResponseBuilder.Ask(speech, reprompt);
                }
                break;
                }
            }

            return(resp);
        }
Ejemplo n.º 23
0
        public async Task <dynamic> Post([FromBody] SkillRequest input)
        {
            var speech        = new Alexa.NET.Response.SsmlOutputSpeech();
            var finalResponse = new SkillResponse();
            // check what type of a request it is like an IntentRequest or a LaunchRequest
            var requestType = input.GetRequestType();

            if (requestType == typeof(IntentRequest))
            {
                // do some intent-based stuff
                var intentRequest = input.Request as IntentRequest;

                // check the name to determine what you should do
                if (intentRequest.Intent.Name.Equals("GetPoints"))
                {
                    long?points = 0;
                    var  client = new CustomApiClient();
                    var  result = await client.QueryPointsAsync("API", "EXTERNAL", 1, "921722255", ParamType.Msisdn, 1, null, null, null, null, false, null, null, null);

                    if (result != null)
                    {
                        foreach (var wallet in result.Wallets)
                        {
                            points = points + wallet.Points;
                        }
                    }
                    // create the speech response - cards still need a voice response
                    speech.Ssml = $"<speak>You currently have {points} loyalty points available in your account.</speak>";
                    // create the card response
                    finalResponse = ResponseBuilder.TellWithCard(speech, "GetPoints", $"You currently have {points} loyalty points available in your account.");
                }
                // check the name to determine what you should do
                if (intentRequest.Intent.Name.Equals("GetItems"))
                {
                    string items  = string.Empty;
                    var    client = new CustomApiClient();
                    var    result = await client.QueryAvailableItemsAsync("API", "EXTERNAL", 1, "921722255", ParamType.Msisdn, 1, null, null, null, null, null);

                    if (result != null)
                    {
                        items = string.Join(", ", result.Items.Select(z => z.Name));
                    }
                    // create the speech response - cards still need a voice response
                    speech.Ssml = $"<speak>Here is the list of items available for you: {items}.</speak>";
                    // create the card response
                    //finalResponse = ResponseBuilder.TellWithCard(speech, "GetItems", $"Here is the list of items available for you: {items}.");

                    // create the speech reprompt
                    var repromptMessage = new PlainTextOutputSpeech();
                    repromptMessage.Text = "Would you like to add any of these to your shoping cart?";

                    // create the reprompt
                    var repromptBody = new Alexa.NET.Response.Reprompt();
                    repromptBody.OutputSpeech = repromptMessage;

                    // create the response
                    finalResponse = ResponseBuilder.AskWithCard(speech, "GetItems", $"Here is the list of items available for you: {items}.", repromptBody);
                }
                // check the name to determine what you should do
                if (intentRequest.Intent.Name.Equals("AddToBasket"))
                {
                    // create the speech response - cards still need a voice response
                    speech.Ssml = "<speak>Your item was successfully added to shopping cart.</speak>";
                    // create the card response
                    finalResponse = ResponseBuilder.TellWithCard(speech, "AddToBasket", "Your item was successfully added to shopping cart.");
                }
            }
            else if (requestType == typeof(Alexa.NET.Request.Type.LaunchRequest))
            {
                // default launch path executed
            }
            else if (requestType == typeof(AudioPlayerRequest))
            {
                // do some audio response stuff
            }

            return(finalResponse);
        }