Beispiel #1
0
        private async Task YoutubeIntentAsync()
        {
            CloudRail.AppKey = Config.cloudRailApiKey;

            YouTube service = new YouTube(
                new LocalReceiver(8082),
                Config.youtubeApiKey

                );


            string youtubeur = intentRequest.Intent.Slots.First().Value.Value;

            if (youtubeur != null)
            {
                response = ResponseBuilder.Tell("Dac je lance la vidéo de " + youtubeur);
                List <VideoMetaData> listVideoYoutube = service.SearchVideos(
                    youtubeur,
                    50,
                    10
                    );
                Random rnd        = new Random();
                int    numYtVideo = rnd.Next(listVideoYoutube.Count);
                Config.youtubeUrl = "https://www.youtube.com/embed/" + listVideoYoutube[numYtVideo].GetId() + "?autoplay=1";
            }
            else
            {
                response = ResponseBuilder.Tell("Je ne conais pas ce youtubeur");
            }



            //VideolinkHub videolinkHub = new VideolinkHub();
            // await videolinkHub.ChangeVideoLink(Config.youtubeUrl);
            response.Response.ShouldEndSession = false;
        }
        private SkillResponse ErrorHandler(SkillRequest skillRequest)
        {
            var speechText = "すみません。聞き取れませんでした。";

            var skillResponse = new SkillResponse
            {
                Version  = "1.0",
                Response = new ResponseBody()
            };

            skillResponse.Response.OutputSpeech = new PlainTextOutputSpeech
            {
                Text = speechText
            };
            skillResponse.Response.Reprompt = new Reprompt
            {
                OutputSpeech = new PlainTextOutputSpeech
                {
                    Text = speechText
                }
            };

            return(skillResponse);
        }
Beispiel #3
0
        public SkillResponse Process(SkillRequest request)
        {
            var response   = new SkillResponse();
            var intentName = !(request.Request is IntentRequest intentRequest) ? "DefaultIntent" : intentRequest.Intent.Name;

            switch (intentName)
            {
            case "HelloIntent":
                response = _helloHandler.Process(request); break;

            case "FamilyLaw":
                response = _familyLawHandler.Process(request); break;

            case "ConsumerLaw":
                response = _consumerLawHandler.Process(request); break;

            case "Dental":
                response = _dentalHandler.Process(request); break;

            case "Dermatology":
                response = _dermatologyHandler.Process(request); break;

            case "ConflictIntent":
                response = _conflictIntentHandler.Process(request); break;

            case "DefaultIntent":
                response = _defaultHandler.Process(request); break;

            case "CancelMembership":
                response = _cancelMembershipHandler.Process(request); break;

            default:
                response = _defaultHandler.Process(request); break;
            }
            return(response);
        }
        public async Task Can_Invoke_Function()
        {
            // Arrange
            AlexaFunction function = await CreateFunctionAsync();

            SkillRequest   request = CreateIntentRequest("AMAZON.HelpIntent");
            ILambdaContext context = CreateContext();

            // Act
            SkillResponse actual = await function.HandlerAsync(request, context);

            // Assert
            ResponseBody response = AssertResponse(actual, shouldEndSession: false);

            response.Card.ShouldBeNull();
            response.Reprompt.ShouldBeNull();

            response.OutputSpeech.ShouldNotBeNull();
            response.OutputSpeech.Type.ShouldBe("SSML");

            var ssml = response.OutputSpeech.ShouldBeOfType <SsmlOutputSpeech>();

            ssml.Ssml.ShouldBe("<speak><p>This skill allows you to check for the status of a specific line, or for disruption in general. You can ask about any London Underground line, London Overground, the Docklands Light Railway or T.F.L. Rail.</p><p>Asking about disruption in general provides information about any lines that are currently experiencing issues, such as any delays or planned closures.</p><p>Asking for the status for a specific line provides a summary of the current service, such as whether there is a good service or if there are any delays.</p><p>If you link your account and setup your preferences in the London Travel website, you can ask about your commute to quickly find out the status of the lines you frequently use.</p></speak>");
        }
Beispiel #5
0
        public static SkillResponse MakeSkillResponseWithDirectives(string outputSpeech,
                                                                    bool shouldEndSession, List <IDirective> directives,
                                                                    string repromptText = "Reprompt Text")
        {
            var response = new ResponseBody
            {
                ShouldEndSession = shouldEndSession,
                OutputSpeech     = new PlainTextOutputSpeech {
                    Text = outputSpeech
                }
            };

            if (repromptText != null)
            {
                response.Reprompt = new Reprompt()
                {
                    OutputSpeech = new PlainTextOutputSpeech()
                    {
                        Text = repromptText
                    }
                };
            }

            var skillResponse = new SkillResponse
            {
                Response = response,
                Version  = "1.0"
            };

            if (directives != null)
            {
                response.Directives = directives;
            }

            return(skillResponse);
        }
        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);
        }
Beispiel #7
0
        public async Task Can_Invoke_Function_When_The_Api_Fails()
        {
            // Arrange
            AlexaFunction function = await CreateFunctionAsync();

            SkillRequest   request = CreateIntentRequest();
            ILambdaContext context = CreateContext();

            // Act
            SkillResponse actual = await function.HandlerAsync(request, context);

            // Assert
            ResponseBody response = AssertResponse(actual);

            response.Card.ShouldBeNull();
            response.Reprompt.ShouldBeNull();

            response.OutputSpeech.ShouldNotBeNull();
            response.OutputSpeech.Type.ShouldBe("SSML");

            var ssml = response.OutputSpeech.ShouldBeOfType <SsmlOutputSpeech>();

            ssml.Ssml.ShouldBe("<speak>Sorry, something went wrong.</speak>");
        }
        public async Task <ActionResult> ProcessAlexaRequest([FromBody] SkillRequest request)
        {
            var           requestType = request.GetRequestType();
            SkillResponse response    = null;

            var handler = new HttpClientHandler()
            {
                ServerCertificateCustomValidationCallback = HttpClientHandler.DangerousAcceptAnyServerCertificateValidator
            };

            var http = new HttpClient(handler);


            if (requestType == typeof(LaunchRequest))
            {
                response = ResponseBuilder.Tell("Welcome to Presence Light!");
                response.Response.ShouldEndSession = false;
            }
            else if (requestType == typeof(IntentRequest))
            {
                var intentRequest = request.Request as IntentRequest;

                if (intentRequest.Intent.Name == "Teams")
                {
                    var res = http.GetAsync($"{Configuration["PiUrl"]}/api/Light?command={intentRequest.Intent.Name}");
                    response = ResponseBuilder.Tell("Presence Light set to Teams!");
                }
                else if (intentRequest.Intent.Name == "Custom")
                {
                    var res = http.GetAsync($"{Configuration["PiUrl"]}/api/Light?command={intentRequest.Intent.Name}");
                    response = ResponseBuilder.Tell("Presence Light set to custom!");
                }
            }

            return(new OkObjectResult(response));
        }
Beispiel #9
0
        private SkillResponse createAnswer(String answer, bool endSession, Session _session, String repromptText = "Ich höre zu!", String bodyTitle = "Message", String content = "Everthing is working fine :)")
        {
            // create the speech response
            var speech = new SsmlOutputSpeech();

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

            // create the response
            var responseBody = new ResponseBody();

            responseBody.OutputSpeech = speech;
            responseBody.Reprompt     = new Reprompt(repromptText);
            responseBody.Card         = new SimpleCard {
                Title = bodyTitle, Content = content
            };

            var skillResponse = new SkillResponse();

            skillResponse.SessionAttributes = _session.Attributes;
            skillResponse.Response          = responseBody;
            skillResponse.Version           = "1.0";

            return(skillResponse);
        }
Beispiel #10
0
        public SkillResponse CommandVehical(SkillRequest input, ILambdaContext context)
        {
            SkillResponse skillResponse = null;

            try
            {
                context.Logger.LogLine("Hello from lambda");

                context.Logger.LogLine($"input is null: {input == null}");
                context.Logger.LogLine($"Request type: {input?.GetRequestType()}");

                if (input?.GetRequestType() == typeof(LaunchRequest))
                {
                    var speech = new PlainTextOutputSpeech()
                    {
                        Text = "Launch request complete"
                    };
                    skillResponse = ResponseBuilder.Tell(speech);
                }
                else
                {
                    var intentRequest = input.Request as IntentRequest;
                    if (intentRequest != null)
                    {
                        context.Logger.LogLine($"ConfirmationStatus: {intentRequest.Intent?.ConfirmationStatus}");
                        context.Logger.LogLine($"Name: {intentRequest.Intent?.Name}");
                        context.Logger.LogLine($"Signature: {intentRequest.Intent?.Signature}");
                        context.Logger.LogLine($"Slots: {intentRequest.Intent?.Slots}");
                    }

                    //Normally we wouldn't hard code creds here, however storing them in the AWS Secret Store would cost money.
                    var c = new OnStarClient(username, password, pin);

                    //Ensures client logs show up in Lambda logs.
                    c.SetupLogging(context.Logger.LogLine);

                    //Amazon already has a stop intent, for consistency, apply a different string for later use
                    if (intentRequest.Intent.Name == "AMAZON.StopIntent")
                    {
                        intentRequest.Intent.Name = "stop";
                    }

                    var taskList = new List <Task>();
                    switch (intentRequest.Intent.Name.ToLower())
                    {
                    case "start":
                        taskList.Add(c.StartVehical());
                        break;

                    case "stop":
                        taskList.Add(c.StopVehical());
                        break;

                    case "lock":
                        taskList.Add(c.LockVehical());
                        break;

                    case "unlock":
                        taskList.Add(c.UnlockVehical());
                        break;
                    }

                    var timeout = context.RemainingTime.Subtract(new TimeSpan(0, 0, 0, 5));
                    Task.WaitAll(taskList.ToArray(), timeout);
                    var convertedTask = (Task <CommandRequestStatus>)taskList[0];
                    if (convertedTask.IsCompletedSuccessfully && convertedTask.Result.Successful)
                    {
                        var speech = new PlainTextOutputSpeech()
                        {
                            Text = $"{intentRequest.Intent.Name} successful"
                        };
                        skillResponse = ResponseBuilder.Tell(speech);
                    }
                    else if (convertedTask.IsFaulted)
                    {
                        var speech = new PlainTextOutputSpeech()
                        {
                            Text = $"Something went wrong {convertedTask.Result.ErrorMessage}"
                        };
                        skillResponse = ResponseBuilder.Tell(speech);
                    }
                }

                context.Logger.LogLine($"RequestType: {input?.Version}");
                context.Logger.LogLine($"RequestType: {input?.Request?.Type}");

                context.Logger.LogLine("Done executing");
            }
            catch (Exception ex)
            {
                context.Logger.LogLine("Failure during execution: " + ex.ToString());
            }

            return(skillResponse);
        }
Beispiel #11
0
      public async Task <SkillResponse> FunctionHandler(SkillRequest input, ILambdaContext context)
      {
          Response      response;
          IOutputSpeech innerResponse = null;

          log = context.Logger;
          bool shouldEndSession = true;

          textForLog = "";
          string intentName = "";

          try {
              log.LogLine("1");
              innerResponse = new PlainTextOutputSpeech();
              (innerResponse as PlainTextOutputSpeech).Text = "Hi,  Just keep speaking and ask alexa to stop when you are done.";

              log.LogLine("2");
              // intent request, process the intent
              //log.LogLine($"Intent Requested {input.Request.Intent.Name}");
              try
              {
                  intentName = input.Request.Intent.Name;
              } catch
              {
                  try
                  {
                      intentName = input.Request.Type;
                  } catch
                  {
                      intentName = "-no request-";
                  }
              }

              log.LogLine("3");
              log.LogLine("intentName:" + intentName);
              textForLog += Environment.NewLine + "INTENT NAME:";
              textForLog += intentName;
              textForLog += ": BEFORE SWITCH";
              switch (intentName)
              {
              //case "AMAZON.HelpIntent":
              //    (innerResponse as PlainTextOutputSpeech).Text = "Welcome to Pick My Game.  Please try Alexa, Ask Pick My Game to decide for me";
              //    break;
              case "AMAZON.StopIntent":
                  (innerResponse as PlainTextOutputSpeech).Text = "";
                  shouldEndSession = true;
                  break;

              case "AMAZON.CancelIntent":
                  (innerResponse as PlainTextOutputSpeech).Text = "";
                  shouldEndSession = true;
                  break;

              //case "AMAZON.NextIntent":
              //    (innerResponse as PlainTextOutputSpeech).Text = "Welcome to Pick My Game.  Please try Alexa, Ask Pick My Game to decide for me";
              //    break;
              //case "AMAZON.NoIntent":
              //    (innerResponse as PlainTextOutputSpeech).Text = "OK";
              //    break;
              //case "AMAZON.PreviousIntent":
              //    (innerResponse as PlainTextOutputSpeech).Text = "OK";
              //    break;
              //case "AMAZON.RepeatIntent":
              //    (innerResponse as PlainTextOutputSpeech).Text = "OK";
              //    break;
              //case "AMAZON.ResumeIntent":
              //    (innerResponse as PlainTextOutputSpeech).Text = "OK";
              //    break;
              //case "AMAZON.YesIntent":
              //    (innerResponse as PlainTextOutputSpeech).Text = "OK";
              //    break;
              case "StopIntent":
                  (innerResponse as PlainTextOutputSpeech).Text = "";
                  shouldEndSession = true;
                  break;

              case "CancelIntent":
                  (innerResponse as PlainTextOutputSpeech).Text = "";
                  shouldEndSession = true;
                  break;

              case "LaunchRequest":
                  (innerResponse as PlainTextOutputSpeech).Text = "Hi, let me listen to you.  Just keep speaking and ask alexa to stop when you are done.";
                  shouldEndSession = false;
                  break;

              //case "HelpIntent":
              //    //(innerResponse as PlainTextOutputSpeech).Text = "Welcome to Pick My Game.  Please try Alexa, Ask Pick My Game to decide for me";
              //    shouldEndSession = false;
              //    break;
              case "UnknownIntent":
                  (innerResponse as PlainTextOutputSpeech).Text = "Uh huh";
                  break;

              case "ListenIntent":
                  (innerResponse as PlainTextOutputSpeech).Text = "Uh huh";
                  shouldEndSession = false;
                  break;

              default:
                  (innerResponse as PlainTextOutputSpeech).Text = "Uh huh";
                  shouldEndSession = false;
                  break;
              }

              //}
          }
          catch (Exception ex)
          {
              textForLog += Environment.NewLine + ex.Message + Environment.NewLine + textForLog + Environment.NewLine + ex.StackTrace.ToString();
          }
          //if (textForLog != string.Empty) { await SaveTextToLog(textForLog, input); }
          response = new Response();
          response.ShouldEndSession = shouldEndSession;
          response.OutputSpeech     = innerResponse;
          SkillResponse skillResponse = new SkillResponse();

          skillResponse.Response          = response;
          skillResponse.Version           = "1.0";
          skillResponse.SessionAttributes = new System.Collections.Generic.Dictionary <string, object>();

          return(skillResponse);
      }
Beispiel #12
0
        private SkillResponse StartLoginDialogResponse()
        {
            SkillResponse response = ResponseBuilder.TellWithLinkAccountCard("Devi autenticarti per continuare, ho inviato le istruzioni alla tua app alexa");

            return(response);
        }
Beispiel #13
0
        // LambdaFunction::LambdaFunction.Function::FunctionHandler
        public SkillResponse FunctionHandler(SkillRequest input, ILambdaContext context)
        {
            var log = context.Logger;

            try
            {
                SkillResponse response = new SkillResponse();
                response.Response = new ResponseBody();
                response.Response.ShouldEndSession = false;
                IOutputSpeech innerResponse = null;
                log.LogLine($"Skill Request Object:");
                log.LogLine(JsonConvert.SerializeObject(input));

                var currentQuestion = 0; // TODO get from session

                if (input.GetRequestType() == typeof(LaunchRequest))
                {
                    log.LogLine($"Default LaunchRequest made: 'Alexa, open numbers game");
                    innerResponse = new PlainTextOutputSpeech()
                    {
                        Text = "Welcome to the numbers game! Let's get started: " +
                               numberFacts[currentQuestion].Question
                    };
                }
                else if (input.GetRequestType() == typeof(IntentRequest))
                {
                    var intentRequest = (IntentRequest)input.Request;

                    switch (intentRequest.Intent.Name)
                    {
                    case "AnswerIntent":
                        log.LogLine($"Answer intent");

                        long answer;
                        if (!long.TryParse(intentRequest.Intent.Slots["Answer"].Value, out answer))
                        {
                            (innerResponse as PlainTextOutputSpeech).Text = "Sorry, I didn't quite get that. Please say a number.";
                            break;
                        }

                        log.LogLine($"Answer provided: {answer}");

                        innerResponse = new PlainTextOutputSpeech();

                        var correctAnswer = numberFacts[currentQuestion].Answer;

                        if (answer < correctAnswer)
                        {
                            (innerResponse as PlainTextOutputSpeech).Text = $"No, it's more than {answer}.";
                        }
                        else if (answer > correctAnswer)
                        {
                            (innerResponse as PlainTextOutputSpeech).Text = $"No, it's less than {answer}.";
                        }
                        else
                        {
                            (innerResponse as PlainTextOutputSpeech).Text = $"Yes! {answer} is correct!";
                            response.Response.ShouldEndSession            = true;
                        }

                        break;

                    case "RepeatQuestionIntent":
                        log.LogLine($"RepeatQuestionIntent");
                        innerResponse = new PlainTextOutputSpeech()
                        {
                            Text = numberFacts[currentQuestion].Question
                        };
                        break;

                    case "AMAZON.CancelIntent":
                        log.LogLine($"AMAZON.CancelIntent: send StopMessage");
                        innerResponse = new PlainTextOutputSpeech();
                        //(innerResponse as PlainTextOutputSpeech).Text = resource.StopMessage;
                        response.Response.ShouldEndSession = true;
                        break;

                    case "AMAZON.StopIntent":
                        log.LogLine($"AMAZON.StopIntent: send StopMessage");
                        innerResponse = new PlainTextOutputSpeech();
                        //(innerResponse as PlainTextOutputSpeech).Text = resource.StopMessage;
                        response.Response.ShouldEndSession = true;
                        break;

                    case "AMAZON.HelpIntent":
                        log.LogLine($"AMAZON.HelpIntent: send HelpMessage");
                        innerResponse = new PlainTextOutputSpeech();
                        //(innerResponse as PlainTextOutputSpeech).Text = resource.HelpMessage;
                        break;

                    default:
                        log.LogLine($"Unknown intent: " + intentRequest.Intent.Name);
                        innerResponse = new PlainTextOutputSpeech();
                        //(innerResponse as PlainTextOutputSpeech).Text = resource.HelpReprompt;
                        break;
                    }
                }

                response.Response.OutputSpeech = innerResponse;
                response.Version = "1.0";

                if (response.SessionAttributes == null)
                {
                    response.SessionAttributes = new System.Collections.Generic.Dictionary <string, object>();
                }
                //response.SessionAttributes.Add("foo", count++);

                log.LogLine($"Skill Response Object...");
                log.LogLine(JsonConvert.SerializeObject(response));
                return(response);
            }
            catch (Exception ex)
            {
                log.LogLine("Unhandled exception:");
                log.LogLine(ex.ToString());
                log.LogLine(JsonConvert.SerializeObject(ex));
                throw;
            }
        }
Beispiel #14
0
        public static async Task <IActionResult> Run([HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = null)] HttpRequest req, ILogger log)
        {
            string _id = Guid.NewGuid().ToString();

            AppInsightHelper.Instance.AppInsightInit(new AppInsightPayload
            {
                _operation     = "nebulaswitch",
                _type          = AppInsightLanguage.AppInsightTrace,
                _payload       = "Alexa call started",
                _correlationId = _id.ToString()
            });

            SkillResponse response = null;

            try
            {
                log.LogInformation("In Alexa Switch Skill");
                string json = await req.ReadAsStringAsync();

                //json = data;
                log.LogInformation(json);

                if (!string.IsNullOrEmpty(json))
                {
                    AppInsightHelper.Instance.AppInsightInit(new AppInsightPayload
                    {
                        _operation     = "nebulaswitch",
                        _type          = AppInsightLanguage.AppInsightTrace,
                        _payload       = "Welcome message",
                        _correlationId = _id.ToString()
                    });
                    var skillRequest = JsonConvert.DeserializeObject <SkillRequest>(json);
                    var requestType  = skillRequest.GetRequestType();

                    if (requestType != null)
                    {
                        if (requestType == typeof(LaunchRequest))
                        {
                            response = ResponseBuilder.Tell("Welcome to Nebula Switch. Please say display on or off  or tv switch on or off");
                            response.Response.ShouldEndSession = false;
                            return(new OkObjectResult(response));
                        }
                    }

                    if (skillRequest != null)
                    {
                        log.LogInformation($"In Intent");
                        if (((Alexa.NET.Request.Type.IntentRequest)skillRequest.Request).Intent.Name.ToString().ToUpper() == "displayswitch".ToUpper())
                        {
                            AppInsightHelper.Instance.AppInsightInit(new AppInsightPayload
                            {
                                _operation     = "nebulaswitch",
                                _type          = AppInsightLanguage.AppInsightTrace,
                                _payload       = "In dislayswitch",
                                _correlationId = _id.ToString()
                            });
                            log.LogInformation($"Intent Name is displayswitch ");
                            System.Collections.Generic.Dictionary <string, Slot> _slots = ((Alexa.NET.Request.Type.IntentRequest)skillRequest.Request).Intent.Slots;
                            string stateValue = _slots["item"].Value;

                            #region DBCall
                            AppInsightHelper.Instance.AppInsightInit(new AppInsightPayload
                            {
                                _operation     = "nebulaswitch",
                                _type          = AppInsightLanguage.AppInsightTrace,
                                _payload       = "Calling DB to update",
                                _correlationId = _id.ToString()
                            });
                            string commandText = string.Empty;
                            bool   dbresponse  = false;
                            if (stateValue.ToUpper().Trim().Equals("ON".ToUpper().Trim()))
                            {
                                commandText = $"Update [TRX].[tblNebulaSwitch] SET [state] =1 WHERE ID=1;";
                            }
                            else
                            {
                                commandText = $"Update [TRX].[tblNebulaSwitch] SET [state] =0 WHERE ID=1;";
                            }
                            dbresponse = await DBUpdateSwitch(log, commandText, _id.ToString());

                            #endregion

                            log.LogInformation($"State value {stateValue}");
                            response = ResponseBuilder.Tell($"Switch state set to {stateValue}. Device will be update with new state in 30 seconds");
                            response.Response.ShouldEndSession = false;
                            AppInsightHelper.Instance.AppInsightInit(new AppInsightPayload
                            {
                                _operation     = "nebulaswitch",
                                _type          = AppInsightLanguage.AppInsightTrace,
                                _payload       = "Update complete",
                                _correlationId = _id.ToString()
                            });
                            return(new OkObjectResult(response));
                        }
                        else
                        {
                            AppInsightHelper.Instance.AppInsightInit(new AppInsightPayload
                            {
                                _operation     = "nebulaswitch",
                                _type          = AppInsightLanguage.AppInsightTrace,
                                _payload       = "Intent missing",
                                _correlationId = _id.ToString()
                            });
                            log.LogInformation($"In else Intent");
                            response = ResponseBuilder.Tell("Intent missing");
                            response.Response.ShouldEndSession = false;
                            return(new OkObjectResult(response));
                        }
                    }
                    else
                    {
                        AppInsightHelper.Instance.AppInsightInit(new AppInsightPayload
                        {
                            _operation     = "nebulaswitch",
                            _type          = AppInsightLanguage.AppInsightTrace,
                            _payload       = "Skill request null",
                            _correlationId = _id.ToString()
                        });
                        log.LogInformation($"In else skillRequest");
                        response = ResponseBuilder.Tell("skillRequest is null");
                        response.Response.ShouldEndSession = false;
                        return(new OkObjectResult(response));
                    }
                }
                else
                {
                    AppInsightHelper.Instance.AppInsightInit(new AppInsightPayload
                    {
                        _operation     = "nebulaswitch",
                        _type          = AppInsightLanguage.AppInsightTrace,
                        _payload       = "Empty Json",
                        _correlationId = _id.ToString()
                    });
                    log.LogInformation($"In else json");
                    response = ResponseBuilder.Tell("No request available");
                    response.Response.ShouldEndSession = false;
                    return(new OkObjectResult(response));
                }
            }
            catch (Exception ex)
            {
                AppInsightHelper.Instance.AppInsightInit(new AppInsightPayload
                {
                    _operation     = "nebulaswitch",
                    _type          = AppInsightLanguage.AppInsightException,
                    _payload       = "Error",
                    _correlationId = _id.ToString(),
                    _ex            = ex
                });
                log.LogInformation($"In exception");
                response = ResponseBuilder.Tell($"Exception : {ex.Message}");
                response.Response.ShouldEndSession = false;
                return(new OkObjectResult(response));
            }
        }
        public static async Task <IActionResult> Run([HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = null)] HttpRequest req, ILogger log)
        {
            var json = await req.ReadAsStringAsync();

            var skillRequest = JsonConvert.DeserializeObject <SkillRequest>(json);

            // Verifies that the request is indeed coming from Alexa.
            var isValid = await skillRequest.ValidateRequestAsync(req, log);

            if (!isValid)
            {
                return(new BadRequestResult());
            }

            // Setup language resources.
            var store  = SetupLanguageResources();
            var locale = skillRequest.CreateLocale(store);

            var           request  = skillRequest.Request;
            SkillResponse response = null;

            var accessToken = skillRequest.Session.User.AccessToken;
            var graphClient = GetAuthenticatedClientForUser(accessToken, log);

            try
            {
                if (request is LaunchRequest launchRequest)
                {
                    log.LogInformation("Session started");

                    var me = await graphClient.Me.Request().GetAsync();

                    var welcomeMessage = await locale.Get(LanguageKeys.Welcome, new string[] { me.DisplayName });

                    var welcomeRepromptMessage = await locale.Get(LanguageKeys.WelcomeReprompt, null);

                    response = ResponseBuilder.Ask(welcomeMessage, RepromptBuilder.Create(welcomeRepromptMessage));
                }
                else if (request is IntentRequest intentRequest)
                {
                    // Checks whether to handle system messages defined by Amazon.
                    var systemIntentResponse = await HandleSystemIntentsAsync(intentRequest, locale);

                    if (systemIntentResponse.IsHandled)
                    {
                        response = systemIntentResponse.Response;
                    }
                    else
                    {
                        if (intentRequest.Intent.Name == "Quota")
                        {
                            var drive = await graphClient.Me.Drive.Request().GetAsync();

                            int free = (int)(drive.Quota.Remaining.Value / 1024 / 1024 / 1024);

                            var quotaMessage = await locale.Get(LanguageKeys.Quota, new string[] { free.ToString() });

                            response = ResponseBuilder.Tell(quotaMessage);
                        }
                    }
                }
                else if (request is SessionEndedRequest sessionEndedRequest)
                {
                    log.LogInformation("Session ended");
                    response = ResponseBuilder.Empty();
                }
            }
            catch
            {
                var message = await locale.Get(LanguageKeys.Error, null);

                response = ResponseBuilder.Tell(message);
                response.Response.ShouldEndSession = false;
            }

            return(new OkObjectResult(response));
        }
Beispiel #16
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 SkillResponse FunctionHandler(SkillRequest input, ILambdaContext context)
        {
            SkillResponse response = new SkillResponse();

            response.Response = new ResponseBody();
            response.Response.ShouldEndSession = false;
            IOutputSpeech innerResponse = null;

            log = context.Logger;
            log.LogLine($"Skill Request Object:");
            log.LogLine(JsonConvert.SerializeObject(input));

            _session = input.Session;

            var allResources = GetResources();
            var resource     = allResources.FirstOrDefault();

            if (input.GetRequestType() == typeof(LaunchRequest))
            {
                log.LogLine($"Default LaunchRequest made: 'Alexa, open Loan Calculator");
                innerResponse = new PlainTextOutputSpeech();
                (innerResponse as PlainTextOutputSpeech).Text = resource.WelcomeMessage;
            }
            else if (input.GetRequestType() == typeof(IntentRequest))
            {
                var intentRequest = (IntentRequest)input.Request;


                switch (intentRequest.Intent.Name)
                {
                case "AMAZON.CancelIntent":
                    log.LogLine($"AMAZON.CancelIntent: send StopMessage");
                    innerResponse = new PlainTextOutputSpeech();
                    (innerResponse as PlainTextOutputSpeech).Text = resource.StopMessage;
                    response.Response.ShouldEndSession            = true;
                    break;

                case "AMAZON.StopIntent":
                    log.LogLine($"AMAZON.StopIntent: send StopMessage");
                    innerResponse = new PlainTextOutputSpeech();
                    (innerResponse as PlainTextOutputSpeech).Text = resource.StopMessage;
                    response.Response.ShouldEndSession            = true;
                    break;

                case "AMAZON.HelpIntent":
                    log.LogLine($"AMAZON.HelpIntent: send HelpMessage");
                    innerResponse = new PlainTextOutputSpeech();
                    (innerResponse as PlainTextOutputSpeech).Text = resource.HelpMessage;
                    break;

                case "GetInterestRate":
                    log.LogLine($"GetInterestRate sent:");
                    innerResponse = new PlainTextOutputSpeech();
                    getInterestRate(resource, intentRequest.Intent);
                    (innerResponse as PlainTextOutputSpeech).Text = getLoanPayments(resource, intentRequest.Intent);
                    break;

                case "LoanIntent":
                    log.LogLine($"LoanIntent sent:");
                    innerResponse = new PlainTextOutputSpeech();
                    (innerResponse as PlainTextOutputSpeech).Text = getLoanPayments(resource, intentRequest.Intent);
                    break;

                default:
                    log.LogLine($"Unknown intent: " + intentRequest.Intent.Name);
                    innerResponse = new PlainTextOutputSpeech();
                    (innerResponse as PlainTextOutputSpeech).Text = resource.HelpReprompt;
                    break;
                }
            }
            log.LogLine("Building Response");

            response.Response.OutputSpeech = innerResponse;
            if (lr != null)
            {
                response.SessionAttributes = new Dictionary <string, object>();
                response.SessionAttributes.Add("LoanAmount", lr.PurchasePrice.ToString());
                response.SessionAttributes.Add("InterestRate", lr.InterestRate.ToString());
                response.SessionAttributes.Add("LoanTermsYears", lr.LoanTermYears.ToString());
                response.SessionAttributes.Add("DownPayment", lr.DownPayment.ToString());
            }
            response.Version = "1.0";
            log.LogLine($"Skill Response Object...");
            log.LogLine(JsonConvert.SerializeObject(response));
            return(response);
        }
 private static void VerifyCardAttachmentAndDirectiveResponse(SkillResponse skillResponse, ICard card, IList <IDirective> directives)
 {
     card.IsSameOrEqualTo(skillResponse.Response.Card);
     Assert.Equal(directives.Count, skillResponse.Response.Directives.Count);
     directives.IsSameOrEqualTo(skillResponse.Response.Directives);
 }
        public static async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = null)] HttpRequest req,
            ILogger log)
        {
            string json = await req.ReadAsStringAsync();

            var skillRequest = JsonConvert.DeserializeObject <SkillRequest>(json);

            //this is the language used to invoke the skill
            string language = skillRequest.Request.Locale;

            bool isValid = await ValidateRequest(req, log, skillRequest);

            if (!isValid)
            {
                return(new BadRequestResult());
            }

            var requestType = skillRequest.GetRequestType();

            SkillResponse response = null;

            if (requestType == typeof(LaunchRequest))
            {
                response = ResponseBuilder.Ask("Welcome to dNext!!! Thanks for the invite Carlos! Glad to see my everis brothers and sisters today!", new Reprompt());
            }
            else if (requestType == typeof(IntentRequest))
            {
                var intentRequest = skillRequest.Request as IntentRequest;

                if (intentRequest.Intent.Name == "namespaces")
                {
                    var endpoint    = "https://localhost:5001/api/pods/namespaces";
                    var k8sresponse = await restClient.GetAsync(endpoint);

                    if (k8sresponse.IsSuccessStatusCode)
                    {
                        var namespaces = await k8sresponse.Content.ReadAsAsync <string[]>();

                        var message = string.Join(",", namespaces);
                        response = ResponseBuilder.Tell($"Found the following namespaces: {message}");
                    }
                }

                if (intentRequest.Intent.Name == "pods")
                {
                    var endpoint    = "https://localhost:5001/api/pods";
                    var k8sresponse = await restClient.GetAsync(endpoint);

                    if (k8sresponse.IsSuccessStatusCode)
                    {
                        var pods = await k8sresponse.Content.ReadAsAsync <string[]>();

                        var message = string.Join(",", pods);
                        response = ResponseBuilder.Tell($"Found the following pods in the default namespace: {pods}");
                    }
                }

                if (intentRequest.Intent.Name == "scale")
                {
                    var endpoint = "https://localhost:5001/api/pods/scale";

                    var replicas = intentRequest.Intent.Slots["replicas"].Value;

                    HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Patch, endpoint)
                    {
                        Content = new StringContent(replicas, Encoding.UTF8, "application/json")
                    };

                    var k8sresponse = await restClient.SendAsync(request);

                    if (k8sresponse.IsSuccessStatusCode)
                    {
                        response = ResponseBuilder.Tell($"Deployment scaled to {replicas} invaders");
                    }
                }
                else if (intentRequest.Intent.Name == "AMAZON.CancelIntent")
                {
                    response = ResponseBuilder.Tell("I'm cancelling the request...");
                }
                else if (intentRequest.Intent.Name == "AMAZON.HelpIntent")
                {
                    response = ResponseBuilder.Tell("Sorry due you are on your own.");
                    response.Response.ShouldEndSession = false;
                }
                else if (intentRequest.Intent.Name == "AMAZON.StopIntent")
                {
                    response = ResponseBuilder.Tell("bye");
                }
            }
            else if (requestType == typeof(SessionEndedRequest))
            {
                log.LogInformation("Session ended");
                response = ResponseBuilder.Empty();
                response.Response.ShouldEndSession = true;
            }

            return(new OkObjectResult(response));
        }
 public static SetLightDirective GadgetColor(this SkillResponse response, string color, int durationMilliseconds = 1000)
 {
     return(GadgetColor(response, color, null, durationMilliseconds));
 }
        public SkillResponse Prescreen(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));

            switch (alexaRequestInput.Request.Type)
            {
            case "LaunchRequest":

                //    logger.Debug("Launch request in");

                response.Response      = new ResponseBody();
                response.Response.Card = new SimpleCard()
                {
                    //                        Content = "Hello! Enjoy your game while I keep the scores. You can tell me to start a game or ask for the score of your current game.",
                    Content = "Hello!! Welcome to Childcare pre-screening! Please note: This is a demo skill to demonstrate voice driven pre-screening process. Outcomes have no real world significance.",

                    Title = "Welcome!!"
                };
                response.Response.OutputSpeech = new PlainTextOutputSpeech()
                {
                    Text = "Hello!! welcome to Childcare pre-screening! You can now say, check my eligibility"
                };
                response.Response.ShouldEndSession = false;

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

            case "SessionEndedRequest":
                response.Response      = new ResponseBody();
                response.Response.Card = new SimpleCard()
                {
                    //                        Content = "Hello! Enjoy your game while I keep the scores. You can tell me to start a game or ask for the score of your current game.",
                    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
                {
                    CaseInfo      caseInfo      = Helpers.GetCaseInfo(alexaRequestInput.Session.SessionId);
                    IntentRequest intentRequest = (IntentRequest)alexaRequestInput.Request;

                    if (intentRequest.Intent.Name == "PreScreen")
                    {
                        UpdateModel(caseInfo, intentRequest.Intent);
                        string       slot = GetNextSlot(caseInfo);
                        ResponseBody body = GetResponseForSlot(slot, caseInfo.ChildName);
                        caseInfo.LastAskedSlot = slot;
                        response.Response      = body;
                        if (body.ShouldEndSession == true)
                        {
                            Helpers.RemoveCaseInfo(alexaRequestInput.Session.SessionId);
                        }
                    }
                    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));
            response.Response.Reprompt = new Reprompt("Sorry, I didn't hear you, can you repeat that?");
            return(response);
        }
Beispiel #21
0
        public SkillResponse FunctionHandler(SkillRequest input, ILambdaContext context)
        {
            Shared.RequestId = context.AwsRequestId;
            Shared.Logger    = context.Logger;
            var response = new SkillResponse()
            {
                Version  = "1.0.0",
                Response = new ResponseBody()
                {
                    ShouldEndSession = true
                }
            };
            IOutputSpeech output = null;

            try
            {
                var requestType = input.GetRequestType();
                if (requestType == typeof(LaunchRequest))
                {
                    response.Response.ShouldEndSession = HandleRandomColorIntent(out output);
                }
                else if (requestType == typeof(SessionEndedRequest))
                {
                    output = Shared.GetOutput(StopMessage);
                }
                else if (requestType == typeof(IntentRequest))
                {
                    var intentRequest = (IntentRequest)input.Request;
                    switch (intentRequest.Intent.Name)
                    {
                    case "AMAZON.CancelIntent":
                        output = Shared.GetOutput(StopMessage);
                        break;

                    case "AMAZON.StopIntent":
                        output = Shared.GetOutput(StopMessage);
                        break;

                    case "AMAZON.HelpIntent":
                        response.Response.ShouldEndSession = false;
                        output = Shared.GetOutput(HelpMessage);
                        break;

                    case "RandomColorIntent":
                        response.Response.ShouldEndSession = HandleRandomColorIntent(out output);
                        break;

                    default:
                        response.Response.ShouldEndSession = false;
                        output = Shared.GetOutput(HelpMessage);
                        break;
                    }
                }
            }
            catch (Exception ex)
            {
                Shared.LogError("FunctionHandler", $"input = {input}; context = {context}", ex);
                output = Shared.GetOutput(Error_Unknown);
                response.Response.ShouldEndSession = false;
            }
            finally
            {
                response.Response.OutputSpeech = output;
            }
            return(response);
        }
 public Response()
 {
     Skill = new SkillResponse();
     Skill = ResponseBuilder.Empty();
 }
Beispiel #23
0
        public static async Task <IActionResult> Run([HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequest req, ILogger log)
        {
            //log.LogInformation("C# HTTP trigger function processed a request.");

            string json = await req.ReadAsStringAsync();

            SkillRequest skillRequest = JsonConvert.DeserializeObject <SkillRequest>(json);

            var requestType = skillRequest.GetRequestType();

            SkillResponse response = null;

            switch (requestType)
            {
            case Type _ when requestType == typeof(LaunchRequest):
                response = ResponseBuilder.Tell("Bienvenidos a CodeFest 2019");
                response.Response.ShouldEndSession = false;
                return(new OkObjectResult(response));

            case Type _ when requestType == typeof(IntentRequest):
                var    intentRequest = (IntentRequest)skillRequest.Request;
                string mensaje       = string.Empty;

                switch (intentRequest.Intent.Name)
                {
                case "DevolverTweets":
                    int numOfTweets;
                    _ = Int32.TryParse(intentRequest.Intent.Slots["NumTweets"].Value, out numOfTweets);
                    if (numOfTweets > 10)
                    {
                        mensaje = "Uffff Eso es mucho compañero. Pideme un número más pequeño.";
                    }
                    else
                    {
                        using var client = new HttpClient
                              {
                                  BaseAddress = new Uri("https://codefesttwitterapi.azurewebsites.net")
                              };
                        client.DefaultRequestHeaders.Add("User-Agent", "C# console program");
                        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

                        var url = "/api/Twitter";
                        HttpResponseMessage response1 = await client.GetAsync(url);

                        response1.EnsureSuccessStatusCode();
                        var resp = await response1.Content.ReadAsStringAsync();

                        List <Tweet> contributors = JsonConvert.DeserializeObject <List <Tweet> >(resp);


                        //return name != null ? (ActionResult)new OkObjectResult($"Hello, {name}") : new BadRequestObjectResult("Please pass a name on the query string or in the request body");

                        //mensaje = "";
                    }

                    break;

                case "DevolverTweetMasAlegre":
                    mensaje = "Lo siento, no hay ningun twit alegre. ¿Será culpa de las charlas?";
                    break;

                case "DevolverTweetMasTriste":
                    mensaje = "Tu si que eres triste. ¿Has venido obligado?";
                    break;
                }

                response = ResponseBuilder.Tell(mensaje);
                response.Response.ShouldEndSession = false;
                return(new OkObjectResult(response));

            case Type _ when requestType == typeof(Error):
                response = ResponseBuilder.Tell("Algo le pasa hoy a tu boca, ¿puedes repetir? ");
                response.Response.ShouldEndSession = false;
                return(new OkObjectResult(response));

            default:
                response = ResponseBuilder.Tell("Upppssss algo desconocido sucedió. Efecto demo");
                response.Response.ShouldEndSession = false;
                return(new OkObjectResult(response));
            }
        }
 public void AddAudioPlayer(PlayBehavior behavior, string url, string token)
 {
     RemoveDirective();
     Skill = ResponseBuilder.AudioPlayerPlay(behavior, url, token);
     Skill.Response.ShouldEndSession = true;
 }
Beispiel #25
0
        public async Task InvokeAsync(HttpContext context, GrossIncomeIntentWorker grossIncomeIntentWorker, NetIncomeIntentWorker netIncomeIntentWorker, OutgoingInvoicePaymentCheckWorker outgoingInvoicePaymentCheckWorker, HelpWorker helpWorker, GreetingWorker greetingWorker)
        {
            var streamReader = new StreamReader(context.Request.Body);
            var rawBody      = await streamReader.ReadToEndAsync();

            var           skillRequest = JsonConvert.DeserializeObject <SkillRequest>(rawBody.ToString());
            SkillResponse response     = null;

            if (skillRequest.Request is IntentRequest)
            {
                var request    = (IntentRequest)skillRequest.Request;
                var intentName = request.Intent.Name;
                if (intentName == "Gross_Income")
                {
                    var isUserSignedIn = IsUserSignedIn(skillRequest);
                    if (isUserSignedIn == true)
                    {
                        var queryParams = QueryParametersFactory
                                          .Accountancy
                                          .GrossIncome.Parse(request);
                        var msg = grossIncomeIntentWorker.Do(queryParams);
                        response = ResponseBuilder.Tell(msg);
                    }
                    else
                    {
                        response = StartLoginDialogResponse();
                    }
                }
                else if (intentName == "Net_Income")
                {
                    var isUserSignedIn = IsUserSignedIn(skillRequest);
                    if (isUserSignedIn == true)
                    {
                        var queryParams = QueryParametersFactory
                                          .Accountancy
                                          .NetIncome.Parse(request);
                        var msg = netIncomeIntentWorker.Do(queryParams);
                        response = ResponseBuilder.Tell(msg);
                    }
                    else
                    {
                        response = StartLoginDialogResponse();
                    }
                }
                else if (intentName == "Outgoing_Invoice_Payment_Check")
                {
                    var isUserSignedIn = IsUserSignedIn(skillRequest);
                    if (isUserSignedIn == true)
                    {
                        var queryParams = QueryParametersFactory
                                          .Accountancy
                                          .OutgoingInvoicePaymentCheck.Parse(request);
                        var msg = outgoingInvoicePaymentCheckWorker.Do(queryParams);
                        response = ResponseBuilder.Tell(msg);
                    }
                    else
                    {
                        response = StartLoginDialogResponse();
                    }
                }
                else if (intentName == "AMAZON.HelpIntent")
                {
                    var msg      = helpWorker.Do();
                    var reprompt = $"Ground control to major Tom: {msg}";
                    response = ResponseBuilder.Ask(msg, new Reprompt(reprompt));
                }
                else if (intentName == "Greeting")
                {
                    var msg      = greetingWorker.Do();
                    var reprompt = greetingWorker.Do();
                    response = ResponseBuilder.Ask(msg, new Reprompt(reprompt));
                }
                else
                {
                    var msg = "Alas, I couldn't understand what you asked for.";
                    response = ResponseBuilder.Tell(msg);
                }
            }
            else if (skillRequest.Request is LaunchRequest)
            {
                var request  = (LaunchRequest)skillRequest.Request;
                var msg      = "Hi, I am Martin: how can I help you?";
                var reprompt = "Ground control to major Tom: Martin's still waiting for you here.";
                response = ResponseBuilder.Ask(msg, new Reprompt(reprompt));
            }

            var responseJson = JsonConvert.SerializeObject(response);
            await context.Response.WriteAsync(responseJson);

            await _next(context);
        }
 public void AddAudioPlayer(PlayBehavior behavior, string url, string enqueuedToken, string token, int offset)
 {
     RemoveDirective();
     Skill = ResponseBuilder.AudioPlayerPlay(behavior, url, enqueuedToken, token, offset);
     Skill.Response.ShouldEndSession = true;
 }
        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);
        }
 public void ClearAudioPlayer()
 {
     Skill = ResponseBuilder.AudioPlayerClearQueue(ClearBehavior.ClearEnqueued);
 }
        internal static SkillResponse CommonModelToAlexa(CommonModel commonModel)
        {
            var response = new SkillResponse()
            {
                Version  = "1.0",
                Response = new ResponseBody()
            };

            if (commonModel.Request.State == "STARTED" || commonModel.Request.State == "IN_PROGRESS")
            {
                var directive = new DialogDelegate
                {
                    UpdatedIntent = new Alexa.NET.Request.Intent
                    {
                        Name  = commonModel.Request.Intent,
                        Slots = commonModel.Request.Parameters?.ToDictionary(p => p.Key, p => new Slot {
                            Name = p.Key, Value = p.Value
                        })
                    }
                };

                response.Response.Directives.Add(directive);
                response.Response.ShouldEndSession = false;

                return(response);
            }

            if (string.IsNullOrWhiteSpace(commonModel.Response.Ssml))
            {
                response.Response.OutputSpeech = new PlainTextOutputSpeech
                {
                    Text = commonModel.Response.Text
                };
            }
            else
            {
                response.Response.OutputSpeech = new SsmlOutputSpeech {
                    Ssml = "<speak>" + commonModel.Response.Ssml + "</speak>"
                };
            }

            if (commonModel.Response.Card != null)
            {
                response.Response.Card = new SimpleCard
                {
                    Title   = commonModel.Response.Card.Title,
                    Content = commonModel.Response.Card.Text
                };
            }

            if (!string.IsNullOrWhiteSpace(commonModel.Response.Prompt))
            {
                response.Response.Reprompt = new Reprompt
                {
                    OutputSpeech = new PlainTextOutputSpeech
                    {
                        Text = commonModel.Response.Prompt
                    }
                }
            }
            ;

            response.Response.ShouldEndSession = commonModel.Session.EndSession;

            return(response);
        }
 public void StopAudioPlayer()
 {
     Skill = ResponseBuilder.AudioPlayerStop();
 }