public async Task <AlexaResponse> ProcessAdventureRequestAsync(AlexaRequest request)
        {
            Stopwatch functionDuration = new Stopwatch();

            functionDuration.Start();
            AlexaResponse response       = new AlexaResponse();
            bool          isPing         = false;
            string        requestLogInfo = null;

            if (request.Version.Equals("ping"))
            {
                requestLogInfo = "Ping request";
                _logger.LogInformation(requestLogInfo);
                isPing = true;
            }
            else
            {
                switch (request.Request.Type)
                {
                case RequestType.SkillDisabled:
                    requestLogInfo = "Received skill disabled event";
                    _logger.LogInformation(requestLogInfo);
                    response = new AlexaResponse();
                    break;

                case RequestType.SkillEnabled:
                    requestLogInfo = "Received skill enabled event";
                    _logger.LogInformation(requestLogInfo);
                    response = new AlexaResponse();
                    break;

                case RequestType.LaunchRequest:
                    requestLogInfo = "Processing launch request";
                    _logger.LogInformation(requestLogInfo);
                    response = await GetLaunchResponseAsync(request);

                    break;

                case RequestType.IntentRequest:
                    requestLogInfo = "Processing intent request";
                    _logger.LogInformation(requestLogInfo);
                    response = await GetIntentResponseAsync(request);

                    break;

                case RequestType.SessionEndedRequest:
                    requestLogInfo = "Processing intent request";
                    _logger.LogInformation(requestLogInfo);
                    response = new AlexaResponse();
                    break;
                }
            }


            functionDuration.Stop();

            _logger.LogInformation($"Function duration: {functionDuration.ElapsedMilliseconds}");

            return(response);
        }
Example #2
0
        public async Task <ContentResult> Post([FromBody] AlexaRequest alexaRequestObject)
        {
            var intent    = alexaRequestObject?.request?.intent?.name;
            var query     = alexaRequestObject?.request?.intent?.slots?.phrase?.value;
            var sessionId = alexaRequestObject?.session?.sessionId;

            //Should change this.
            //When Alexa is invocted, it sends a null intent so we change this to a welcome message
            if (intent == null && query == null)
            {
                query = "Welcome";
            }

            _client.SendBotMessage(query, sessionId).Wait();
            var replies = _client.ReadBotMessages(sessionId).Result;

            //TODO: This pulls the last message sent by the bot. Could break for multiple messages sent
            var reply = replies.LastOrDefault();

            var response = new AlexaResponse(reply);

            var json = Newtonsoft.Json.JsonConvert.SerializeObject(response);
            var res  = json.ToString();

            return(Content(json.ToString(), "application/json"));
        }
Example #3
0
        public async Task <dynamic> AlexaAnonymousEndpoint(AlexaRequest alexaRequest)
        {
            var requestMessage = new Requests().Create(ParseRequestMessage(alexaRequest));

            AlexaResponse response = null;

            switch (requestMessage.Type)
            {
            case "LaunchRequest":
                response = await LaunchRequestHandler(requestMessage);

                break;

            case "IntentRequest":
                response = await IntentRequestHandler(requestMessage);

                break;

            case "SessionEndedRequest":
                response = SessionEndedRequestHandler(requestMessage);
                break;
            }


            return(response);
        }
Example #4
0
        public void PersistAlexaRequestAndMember(AlexaRequest alexaRequest)
        {
            // save request
            AlexaMember alexaMember = _unitOfWork.AlexaMembers.Find(m => m.AlexaUserId == alexaRequest.UserId).FirstOrDefault();

            if (alexaMember == null)
            {
                alexaRequest.AlexaMember = new AlexaMember()
                {
                    AlexaUserId     = alexaRequest.UserId,
                    CreatedDate     = DateTime.UtcNow,
                    LastRequestDate = DateTime.UtcNow,
                    RequestCount    = 1
                };

                _unitOfWork.AlexaRequests.Add(alexaRequest);
            }
            else
            {
                alexaMember.AlexaRequests.Add(alexaRequest);
                alexaMember.RequestCount += 1;
            }

            _unitOfWork.Complete();
        }
        private AlexaResponse SessionEndedRequest(AlexaRequest request, AlexaResponse response)
        {
            response.Response.OutputSpeech.Text = "Have a great day gorgeous!";
            response.Response.ShouldEndSession  = true;

            return(response);
        }
Example #6
0
        public AlexaResponse MapPlaybackResponse(AlexaRequest request)
        {
            var response = new AlexaResponse
            {
                version  = "1.0",
                response = new Response
                {
                    shouldEndSession = true,
                    directives       = new List <Directive>
                    {
                        new Directive
                        {
                            type         = "AudioPlayer.Play",
                            playBehavior = "REPLACE_ALL",
                            audioItem    = new AudioItem
                            {
                                stream = new AudioStream
                                {
                                    token = "0",
                                    offsetInMilliseconds = 0,
                                    url = "https://alexabedtime.blob.core.windows.net/sounds/10-hours-rain-96bps.mp3"
                                }
                            }
                        }
                    }
                }
            };

            return(response);
        }
Example #7
0
        private async Task <AlexaResponse> IntentRequestHandler(AlexaRequest alexaRequest)
        {
            AlexaResponse response = null;

            if (alexaRequest.RequestBody is IntentRequest intentRequest)
            {
                switch (intentRequest.Intent.Name)
                {
                case "whenNextIntent":
                    response = await WhenNextResponseHandler(intentRequest);

                    break;

                case "whoIsLiveIntent":
                    response = await WhoIsLiveResponseHandler(intentRequest);

                    break;

                case "AMAZON.StopIntent":
                case "AMAZON.CancelIntent":
                    response = CancelOrStopResponseHandler(intentRequest);
                    break;

                case "AMAZON.HelpIntent":
                    response = HelpIntentResponseHandler(intentRequest);
                    break;

                case "AMAZON.FallbackIntent":
                    response = FallbackIntentResponseHandler(intentRequest);
                    break;
                }
            }

            return(response);
        }
Example #8
0
        public async Task <IActionResult> Index([FromBody] AlexaRequest request)
        {
            try
            {
                switch (request.request.intent.name)
                {
                case "test":
                    var testresponse = await(new XeroHackService().GetError(""));
                    return(Json(testresponse));

                    break;

                case "risk":
                    var riskresponse = await(new XeroHackService().GetRisk());
                    return(Json(riskresponse));

                    break;

                case "InvoiceStatus":
                    return(Json(await(new XeroHackService().GetInvoiceStatus())));

                    break;
                }
            }
            catch (Exception e)
            {
                return(Json(new XeroHackService().GetError(e.Message)));
            }
            return(Json(new XeroHackService().GetError("")));
        }
Example #9
0
        public async Task <string> GetUserTimezone(AlexaRequest alexaRequest, ILogger logger)
        {
            var baseUrl  = alexaRequest.Context.System.ApiEndpoint;
            var token    = alexaRequest.Context.System.ApiAccessToken;
            var deviceId = alexaRequest.Context.System.Device.DeviceId;

            var url = $"{baseUrl}v2/devices/{deviceId}/settings/System.timeZone";

            logger.LogInformation($"URL = {url}");
            logger.LogInformation($"Device = {deviceId}");

            _client.DefaultRequestHeaders.Authorization =
                new AuthenticationHeaderValue("Bearer", token);

            try
            {
                var result = await _client.GetAsync(url);

                logger.LogInformation($"Status = {result.StatusCode}");

                if (result.StatusCode == System.Net.HttpStatusCode.OK)
                {
                    var timezone = await result.Content.ReadAsStringAsync();

                    logger.LogInformation($"TZ = {timezone}");
                    return(timezone);
                }
            }
            catch (Exception ex)
            {
                logger.LogError($"Error = {ex.Message}");
            }

            return(String.Empty);
        }
 private AlexaResponse ProcessFallbackIntent(AlexaRequest request, AlexaResponse response)
 {
     response.Response.OutputSpeech.Text          = "Sorry. I didn't understand the question. For help, just say help.";
     response.Response.Reprompt.OutputSpeech.Text = response.Response.OutputSpeech.Text;
     response.Response.ShouldEndSession           = false;
     return(response);
 }
 private AlexaResponse ProcessStopIntent(AlexaRequest request, AlexaResponse response)
 {
     response.Response.OutputSpeech.Text          = "Thanks for using The Ville Skill. Goodbye.";
     response.Response.Reprompt.OutputSpeech.Text = response.Response.OutputSpeech.Text;
     response.Response.ShouldEndSession           = true;
     return(response);
 }
Example #12
0
        public async Task <ActionResult> ProcessAlexaRequest([FromBody] AlexaRequest request)
        {
            // One of Alexa's policy requirements is that the request cannot take more then 150 seconds to get from the Echo to the skill processing logic.
            // This check enforces that policy
            var diff = DateTime.UtcNow - request.Request.Timestamp;

#if DEBUG
            // For the diff to be one second to satisfy conditions
            diff = new TimeSpan(0, 0, 0, 1);
#endif


            if (Math.Abs((decimal)diff.TotalSeconds) <= MAXREQUESTSENDTIME)
            {
                _logger.LogDebug("Alexa request was timestamped {0:0.00} seconds ago below the {1} second maximum.", diff.TotalSeconds, MAXREQUESTSENDTIME);
                AlexaResponse resp = await _adventureProcessor.ProcessAdventureRequestAsync(request);



                return(Ok(resp));
            }
            else
            {
                _logger.LogError("Alexa request was timestamped {0:0.00} seconds ago. It exceeds the {1} second maximum", diff.TotalSeconds, MAXREQUESTSENDTIME);

                return(new StatusCodeResult((int)HttpStatusCode.InternalServerError));
            }
        }
        private AlexaResponse HelpIntent(AlexaRequest request)
        {
            var response = new AlexaResponse("To use the Leadership Portal skill, you can say, Alexa, ask Leadership Portal for tempalte information.", false);

            response.Response.Reprompt.OutputSpeech.Text = "Please go ahead and ask your questions";
            return(response);
        }
        private AlexaResponse IntentRequestHandler(AlexaRequest request)
        {
            AlexaResponse response = null;

            switch (request.Request.Intent.Name)
            {
            case "AMAZON.CancelIntent":
            case "AMAZON.StopIntent":
                response = CancelOrStopIntentHandler(request);
                break;

            case "AMAZON.HelpIntent":
                response = HelpIntent(request);
                break;

            case "TemplateIntent":
                response = TemplateIntent(request);
                break;

            case "SearchIntent":
                response = SearchIntent(request);
                break;
            }

            return(response);
        }
Example #15
0
        private AlexaResponse IntentRequestHandler(AlexaRequest request)
        {
            AlexaResponse response = null;

            switch (request.Request.Intent.Name)
            {
            case "AMAZON.CancelIntent":
                response = CancelOrStopIntentHandler(request);
                break;

            case "AMAZON.StopIntent":
                response = CancelOrStopIntentHandler(request);
                break;

            case "AMAZON.HelpIntent":
                response = HelpIntent(request);
                break;

            case "DidNotUnderstand":
                response = DidNotUnderstandIntent(request);
                break;

            case "CurrentPowerIntent":
                response = CurrentPowerIntentHandler(request);
                break;

            default:
                response = CancelOrStopIntentHandler(request);
                break;
            }
            return(response);
        }
        //[Trait("Type", "UnitTest")]
        //[Fact]
        //public async Task FireLaunchRequestTest()
        //{
        //    AlexaRequest req = GenerateRequest(RequestType.LaunchRequest);
        //    IServiceProvider serProv = GetTestProvider();
        //    var function = new AdventureFunction(serProv);
        //    var context = new TestLambdaContext();

        //    AlexaResponse resp = null;

        //    try
        //    {
        //        resp = await function.FunctionHandlerAsync(req, context);
        //    }
        //    catch (Exception ex)
        //    {
        //        Debug.WriteLine(ex);
        //        throw;
        //    }

        //    // No email returned
        //    Assert.Contains("Welcome to the Adventure Sample", resp.Response.OutputSpeech.Text);

        //    // No directives should be returned since the request does not support the Echo Show
        //    Assert.Null(resp.Response.Directives);
        //}



        private AlexaRequest GenerateRequest(RequestType reqType)
        {
            AlexaRequest req = new AlexaRequest();

            req.Version = "1.0";

            req.Request = new RequestAttributes()
            {
                RequestId = Guid.NewGuid().ToString(),
                Timestamp = DateTime.Now,
                Locale    = "en-US",
                Type      = reqType
            };

            req.Session = new AlexaSessionAttributes()
            {
                New       = true,
                SessionId = Guid.NewGuid().ToString()
            };

            req.Context = new ContextAttributes()
            {
                System = new SystemAttributes()
                {
                    ApiEndpoint    = "https://api.amazonalexa.com",
                    ApiAccessToken = "SOMETOKEN",
                    Device         = new DeviceAttributes()
                    {
                        SupportedInterfaces = new SupportedInterfacesAttributes()
                    }
                }
            };

            return(req);
        }
Example #17
0
        public dynamic solar(AlexaRequest alexaRequest)
        {
            string ApplicationId = Properties.Settings.Default.AlexaSkillID;

            if (alexaRequest.Session.Application.ApplicationId != ApplicationId)
            {
                throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.BadRequest));
            }

            AlexaResponse response = new AlexaResponse(alexaRequest.Request.Type, true);

            try
            {
                if (!string.IsNullOrWhiteSpace(alexaRequest.Request.Type))
                {
                    switch (alexaRequest.Request.Type)
                    {
                    case "LaunchRequest":
                        response = LaunchRequestHandler(alexaRequest);
                        break;

                    case "IntentRequest":
                        response = IntentRequestHandler(alexaRequest);
                        break;
                    }
                }
            }
            catch (Exception)
            {
                throw;
            }
            return(response);
        }
        public void AllInterfaceLaunchTest()
        {
            string filePath = @"requestsamples\allsupportedinterfaceslaunchrequest.json";


            string fileContents = File.ReadAllText(filePath);

            JsonSerializerSettings serializerSettings = new JsonSerializerSettings();

            serializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();

            AlexaRequest req = JsonConvert.DeserializeObject <AlexaRequest>(fileContents, serializerSettings);

            Assert.Equal("1.0", req.Context.System.Device.SupportedInterfaces.AdvancedPresentationLanguage.Runtime.MaxVersion);

            Assert.Equal(AudioPlayerActivityEnum.Stopped, req.Context.AudioPlayer.PlayerActivity);

#if NET45 || NET47
            //     Assert.NotNull(req.Context.Display);
            object displayObj = req.Context.Display;

            Assert.NotNull(displayObj);
#else
            Assert.NotNull(req.Context.Display);
#endif
        }
Example #19
0
        public AlexaResponse MapStopRequest(AlexaRequest request)
        {
            var response = new AlexaResponse
            {
                version  = "1.1",
                response = new Response
                {
                    shouldEndSession = true,
                    card             = new Card
                    {
                        type    = "Simple",
                        title   = "Bedtime",
                        content = "Enjoy your day!"
                    },
                    directives = new List <Directive>
                    {
                        new Directive
                        {
                            type = "AudioPlayer.Stop"
                        }
                    }
                }
            };

            return(response);
        }
        public void CanInvokeDeserializationTest()
        {
            string filePath = @"requestsamples\caninvokesamplerequest.json";


            string fileContents = File.ReadAllText(filePath);


            AlexaRequest req = JsonConvert.DeserializeObject <AlexaRequest>(fileContents);

            RequestType reqType = req.Request.Type;

            string intent = req.Request.Intent.Name;

            Assert.Equal(RequestType.CanFulfillIntentRequest, req.Request.Type);

            Assert.Equal("FindTrialByCityAndConditionIntent", req.Request.Intent.Name);



            string selectedCity = req.Request.Intent.GetSlotValue("city");

            Assert.Contains("epilepsy", req.Request.Intent.GetSlotValue("condition"));


            Assert.Equal("New York", req.Request.Intent.GetSlotValue("city"));
        }
        public AlexaResponse ProcessAlexaRequest(AlexaRequestPayload alexaRequestPayload)
        {
            // validate request time stamp and app id
            // note that there is custom validation in the AlexaRequestValidationHandler
            SpeechletRequestValidationResult validationResult = _alexaRequestValidationService.ValidateAlexaRequest(alexaRequestPayload);

            if (validationResult == SpeechletRequestValidationResult.OK)
            {
                try
                {
                    // transform request
                    AlexaRequest alexaRequest = _alexaRequestMapper.MapAlexaRequest(alexaRequestPayload);

                    // persist request and member
                    _alexaRequestPersistenceService.PersistAlexaRequestAndMember(alexaRequest);

                    // create a request handler strategy from the alexarequest
                    IAlexaRequestHandlerStrategy alexaRequestHandlerStrategy = _alexaRequestHandlerStrategyFactory.CreateAlexaRequestHandlerStrategy(alexaRequestPayload);

                    // use the handlerstrategy to process the request and generate a response
                    AlexaResponse alexaResponse = alexaRequestHandlerStrategy.HandleAlexaRequest(alexaRequestPayload);

                    // return response
                    return(alexaResponse);
                }
                catch (Exception exception)
                {
                    // todo: log the error
                    return(new AlexaResponse("There was an error " + exception.Message));
                    //return new AlexaWordErrorResponse().GenerateCustomError();
                }
            }

            return(null);
        }
        public bool IsRequestValid(AlexaRequest alexaReq)
        {
            if (alexaReq == null)
            {
                throw new ArgumentNullException("alexaReq cannot be null");
            }

            if (alexaReq.Request == null)
            {
                throw new ArgumentException("alexaReq.Request cannot be null");
            }

            if (alexaReq.Request.Timestamp == DateTime.MinValue)
            {
                throw new ArgumentException("alexaReq.Request.Timestamp cannot be the default value");
            }

            var diff = DateTime.UtcNow - alexaReq.Request.Timestamp;


            if (Math.Abs((decimal)diff.TotalSeconds) <= MAXREQUESTSENDTIME)
            {
                return(true);
            }
            else
            {
                return(false);
            }
        }
        private AlexaResponse ProcessHelpIntent(AlexaRequest request, AlexaResponse response)
        {
            response.Response.OutputSpeech.Text = @"";
            response.Response.ShouldEndSession  = true;

            return(response);
        }
Example #24
0
        public AlexaResponse Process(AlexaRequest request)
        {
            AlexaResponse response;

            switch (request.Request.Type)
            {
            case "LaunchRequest":
                response = Launch();
                break;

            case "IntentRequest":
                response = Intent(request);
                break;

            case "SessionEndedRequest":
                response = GetSessionEndedResponse();
                break;

            default:
                response = null;
                break;
            }

            try
            {
                SaveLog(request, response);
            }
            catch (Exception e)
            {
            }

            return(response);
        }
 public async Task SendProgressiveResponseAsync(AlexaRequest req, string text)
 {
     await SendProgressiveResponseAsync(req?.Context?.System?.ApiEndpoint,
                                        req?.Context?.System?.ApiAccessToken,
                                        req?.Request?.RequestId,
                                        text);
 }
Example #26
0
        private static AlexaResponse Intent(AlexaRequest request)
        {
            AlexaResponse response = null;

            switch (request.Request.Intent.Name)
            {
            case "ShowSynopsisIntent":
            case "ShowStartIntent":
            case "ShowNextEpisodeIntent":
            case "ShowCastIntent":
            case "ShowPersonIntent":
            case "ShowCharacterIntent":
                response = AlexaTvShowIntentHandler.GetTvShowResponse(request.Request.Intent.Name, request);
                break;

            case "AMAZON.CancelIntent":
            case "AMAZON.StopIntent":
                response = GetSessionEndedResponse();
                break;

            case "AMAZON.HelpIntent":
                response = GetHelpResponse();
                break;
            }

            return(response);
        }
        public HttpResponseMessage DoHealthChecks([FromBody] AlexaRequest request)
        {
            var context = new HealthCheckContext(UmbracoContext.HttpContext, UmbracoContext);

            var smtp     = new SmtpCheck(context);
            var statuses = smtp.GetStatus();

            var sb    = new StringBuilder();
            var index = 0;

            foreach (var s in statuses)
            {
                if (sb.Length == 0)
                {
                    sb.Append(s.Message);
                }
                else if (index == statuses.Count() - 1 && statuses.Count() > 1)
                {
                    sb.Append(", and " + s.Message);
                }
                else
                {
                    sb.Append(", " + s.Message);
                }

                index++;
            }

            if (sb.Length == 0)
            {
                sb.Append("The health check returned no results.");
            }

            var response = new AlexaResponse
            {
                Version  = "1.0",
                Response = new Response
                {
                    OutputSpeech = new OutputSpeech
                    {
                        Type = "PlainText",
                        Text = sb.ToString()
                    },
                    Card = new Card
                    {
                        Type    = "Simple",
                        Title   = "Health Check Results",
                        Content = sb.ToString()
                    }
                },
                ShouldEndSession = true
            };

            return(new HttpResponseMessage
            {
                Content = new StringContent(JsonConvert.SerializeObject(response),
                                            Encoding.UTF8,
                                            "application/json")
            });
        }
Example #28
0
        // POST api/alexa
        public dynamic Post(AlexaRequest request)
        {
            dynamic response = null;

            //option 1 - uncomment the following to test option 1, comment out to test option 2
            //var interactionHandler1 = new Interactions(request);
            //interactionHandler1.Messages.StopMessage = "This is where you can override the default stop message.";
            //response = interactionHandler1.Process(this);

            //option 2 - uncomment the following to test option 2, comment out to test option 1
            //var interactionHandler2 = new Interactions(request);
            //interactionHandler2.IntentsList.Add("LaunchRequest", (req) => LaunchRequest(req));
            //interactionHandler2.IntentsList.Add("WelcomeIntent", (req) => WelcomeIntent(req));
            //interactionHandler2.IntentsList.Add("AMAZON.HelpIntent", (req) => HelpIntent());
            //interactionHandler2.IntentsList.Add("AMAZON.StopIntent", (req) => new { message = "This is the overriden built-in stop message." });
            //response = interactionHandler2.Process();

            //This is created as Option #1 in the Alexa.Demo.Web Project it V2 AlexaController..instead
            //of creating a intenthandler and calling them dirrectly as below, just pass a list of your
            //intent handlerst to the SDK.
            response = BuidOutWithCard(IntentsHandler.Process(request, response)) as AlexaResponse;


            return(response);
        }
        public AlexaResponse AlexaStarterSkill(AlexaRequest request)
        {
            //if (request.Session.Application.ApplicationId != ApplicationId)
            //    throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.BadRequest));

            //var totalSeconds = (DateTime.UtcNow - request.Request.Timestamp).TotalSeconds;
            //if (totalSeconds <= 0 || totalSeconds > 150)
            //    throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.BadRequest));

            AlexaResponse response = null;

            if (request != null)
            {
                switch (request.Request.Type)
                {
                case "LaunchRequest":
                    response = RequestHandlers.LaunchRequestHandler(request);
                    break;

                case "IntentRequest":
                    response = RequestHandlers.IntentRequestHandler(request);
                    break;

                case "SessionEndedRequest":
                    response = RequestHandlers.SessionEndedRequestHandler(request);
                    break;
                }
            }

            return(response);
        }
        private AlexaResponse HelpIntent(AlexaRequest request)
        {
            var response = new AlexaResponse("To use the code games skill, you can say, Alexa, I want to do action 1, 2 or 3. You can also say, Alexa, stop or Alexa, cancel, at any time to exit the code games skill. For now, do you want to do one of the actions?", false);

            response.Response.Reprompt.OutputSpeech.Text = "Please select one, action 1,2 or 3?";
            return(response);
        }