public static SkillResponse GetWocheNachKategorieResponse(SkillRequest request, List <SpeisePlan> wochenPlan, int kategorie, int kw)
        {
            var items     = new List <ListItem>();
            var pageToken = SkillTypen.WocheNachKategorie;
            var plaene    = wochenPlan.FindAll(p => p.Kategorie == kategorie);

            if (plaene != null)
            {
                foreach (var menue in plaene)
                {
                    var tag  = cInfo.DateTimeFormat.GetDayName(menue.Datum.DayOfWeek);
                    var item = AddListItemWithImage(pageToken.ToString(), menue.Id, TextStyle.SetFont2(menue.Beschreibung), tag, "", "");
                    items.Add(item);
                }

                var preis  = plaene[0].Preis;
                var speech = CreateSpeech(pageToken, plaene, kategorie, kw);
                var title  = CreateTitle(pageToken, kategorie, preis, kw);
                var card   = CreateCard(pageToken, plaene, title);
                return(CreateListSkillResponse(request, pageToken, items, speech, card, title, DateTime.Now, null));
            }

            return(GibEinfacheAntwort(request, SkillTypen.Error, FehlerTypen.NoSpeisePlan.ToDescription(), "", null, DateTime.Now, false));
        }
Пример #2
0
        public void HandleRequest(SkillRequest request)
        {
            var eventResponse = new[] { "Treffen", "das" };
            var rqEvent       = request.Slots
                                .FirstOrDefault(slot => string.Compare(slot.Key, "Event", StringComparison.InvariantCultureIgnoreCase) == 0)
                                .Value.ToLower();

            if (rqEvent.Contains("in"))
            {
                eventResponse = new[] { "Termin", "der" };
            }
            else if (rqEvent.Contains("event"))
            {
                eventResponse = new[] { "Event", "das" };
            }
            else if (rqEvent.Contains("meet") || rqEvent.Contains("ieder"))
            {
                eventResponse = new[] { "Meet-up", "das" };
            }
            Trace.TraceInformation($"Event({rqEvent}) => {eventResponse[1]} {eventResponse[0]}");

            switch (request.Intent)
            {
            case "UG_Current":
                HandleCurrent(request, eventResponse);
                break;

            case "UG_Month":
                HandleMonth(request, eventResponse);
                break;

            case "UG_Date":
                HandleSpecificDate(request, eventResponse);
                break;
            }
        }
Пример #3
0
        public SkillResponse FunctionHandler(SkillRequest input, ILambdaContext context)
        {
            IntentParameters parameters;

            using (new OperationTimer(context.Logger.LogLine, "Init", EnableOperationTimerLogging))
            {
                parameters = SetupFunction(input, context);

                context.Logger.LogLine("Input: " + JsonConvert.SerializeObject(input));

                var initResponse = FunctionInit(parameters);

                if (initResponse != null)
                {
                    return(initResponse);
                }
            }

            SkillResponse innerResponse;

            using (new OperationTimer(context.Logger.LogLine, "Run function", EnableOperationTimerLogging))
            {
                innerResponse = new AlexaFunctionRunner(_intentFactory, NoIntentMatchedText).Run(input, parameters);

                innerResponse.SessionAttributes = parameters.SessionAttributes();

                context.Logger.LogLine("Output: " + JsonConvert.SerializeObject(innerResponse));
            }

            using (new OperationTimer(context.Logger.LogLine, "Function complete", EnableOperationTimerLogging))
            {
                FunctionComplete(innerResponse);
            }

            return(innerResponse);
        }
        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));
        }
        public static ConsultarTransferenciaRequestDTO MappingIntentDtoRequest(SkillRequest _input)
        {
            Request request = _input.Request;
            ConsultarTransferenciaRequestDTO consultarTransferenciaRequestDTO = new ConsultarTransferenciaRequestDTO();

            if (request is IntentRequest intentRequest)
            {
                consultarTransferenciaRequestDTO.amount          = new ConsultarTransferenciaRequestDTO.Amount();
                consultarTransferenciaRequestDTO.amount.amount   = intentRequest.Intent.Slots["amount"].Value;
                consultarTransferenciaRequestDTO.amount.Currency = "BRL";

                consultarTransferenciaRequestDTO.destinyAccount        = new ConsultarTransferenciaRequestDTO.DestinyAccount();
                consultarTransferenciaRequestDTO.destinyAccount.Bank   = intentRequest.Intent.Slots["Bank"].Value;;
                consultarTransferenciaRequestDTO.destinyAccount.Agency = intentRequest.Intent.Slots["Agency"].Value;
                consultarTransferenciaRequestDTO.destinyAccount.Cpf    = intentRequest.Intent.Slots["Cpf"].Value;
                consultarTransferenciaRequestDTO.destinyAccount.Name   = intentRequest.Intent.Slots["Name"].Value;
                consultarTransferenciaRequestDTO.destinyAccount.Goal   = intentRequest.Intent.Slots["Goal"].Value;

                consultarTransferenciaRequestDTO.Type = intentRequest.Intent.Slots["Type"].Value;
                consultarTransferenciaRequestDTO.TransactionInformation = intentRequest.Intent.Slots["TransactionInformation"].Value;
            }

            return(consultarTransferenciaRequestDTO);
        }
Пример #6
0
        internal static CommonModel AlexaToCommonModel(SkillRequest skillRequest)
        {
            var CommonModel = new CommonModel()
            {
                Id = skillRequest.Request.RequestId
            };

            var requestType = skillRequest.GetRequestType();

            if (requestType == typeof(IntentRequest))
            {
                var intentRequest = skillRequest.Request as IntentRequest;
                CommonModel.Request.Intent = intentRequest.Intent.Name;
                if (intentRequest.Intent.Slots != null)
                {
                    CommonModel.Request.Parameters = intentRequest.Intent.Slots.ToList().ConvertAll(s => new KeyValuePair <string, string>(s.Value.Name, s.Value.Value));
                }
            }

            else if (requestType == typeof(LaunchRequest))
            {
                CommonModel.Request.Intent = "DefaultWelcomeIntent";
            }

            else if (requestType == typeof(LaunchRequest))
            {
                CommonModel.Request.Intent = "Default Welcome Intent";
            }

            else if (requestType == typeof(SessionEndedRequest))
            {
                return(null);
            }

            return(CommonModel);
        }
Пример #7
0
 public SkillResponse FunctionHandler(SkillRequest skillRequest, ILambdaContext context)
 {
     try
     {
         var requestService = RequestFactory.Get(skillRequest);
         var output         = requestService.Execute();
         var card           = output.Response?.Card == null ? null : (SimpleCard)output.Response.Card;
         return(output);
     }
     catch
     {
         var speechOutput = "Sorry I did not understand. Please create order or check status";
         return(new SkillResponse
         {
             Response = new Response
             {
                 OutputSpeech = new PlainTextOutputSpeech
                 {
                     Text = speechOutput
                 }
             }
         });
     }
 }
Пример #8
0
        public IActionResult HandleSkillRequest([FromBody] SkillRequest input)
        {
            // Security check
            // Only accept requests with known app id
            if (input.Session.Application.ApplicationId != _appid)
            {
                return(BadRequest());
            }

            var requestType = input.GetRequestType();

            if (requestType == typeof(IntentRequest))
            {
                var response = HandleIntents(input);
                return(Ok(response));
            }
            else if (requestType == typeof(LaunchRequest))
            {
                var speech = new SsmlOutputSpeech
                {
                    Ssml = "<speak>Launch repsonse</speak>"
                };
                var finalResponse = ResponseBuilder.Tell(speech);
                return(Ok(finalResponse));
            }
            else if (requestType == typeof(AudioPlayerRequest))
            {
                var speech = new SsmlOutputSpeech
                {
                    Ssml = "<speak>Audio player repsonse</speak>"
                };
                var finalResponse = ResponseBuilder.Tell(speech);
                return(Ok(finalResponse));
            }
            return(Ok(ErrorResponse()));
        }
Пример #9
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>");
        }
Пример #10
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 async Task <SkillResponse> FunctionHandler(SkillRequest input, ILambdaContext context)
        {
            // check what type of a request it is like an IntentRequest or a LaunchRequest
            var requestType = input.GetRequestType();

            if (requestType == typeof(IntentRequest))
            {
                return(await HandleIntentRequest(input.Request as IntentRequest));
            }
            else if (requestType == typeof(LaunchRequest))
            {
                // default launch path executed
                return(null);
            }
            else if (requestType == typeof(AudioPlayerRequest))
            {
                // do some audio response stuff
                return(null);
            }
            else
            {
                return(null);
            }
        }
        public SkillResponse Handle(SkillRequest skillRequest, TokenUser tokenUser)
        {
            if (!base.skillRequestValidator.IsValid(skillRequest))
            {
                throw new ArgumentNullException("skillRequest");
            }

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

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

            SkillResponse response;

            tokenUser.Players = new List <Player>();

            response = string.Format("Alright, I removed everyone from your list of tokens.").Tell(true);

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

            return(response);
        }
Пример #12
0
        public SkillResponse FunctionHandler(SkillRequest input, ILambdaContext context)
        {
            if (input.GetRequestType() == typeof(ILaunchRequest))
            {
                // Default launch request, let's just let them know what you can do.

                var launchHandler = new LaunchRequestHandler(input, context);

                return(launchHandler.HandleRequest());
            }
            else if (input.GetRequestType() == typeof(IIntentRequest))
            {
                // Intent request, process the intent.
                // It's not currently necessary to route intents (by name) to a request handler since we're only supporting one intent.

                // Poor man's IoC...
                var locatorFactory = new FamilyMemberLocatorFactory();
                var intentHandler  = new FamilyMemberIntentHandler(locatorFactory, input, context);

                return(intentHandler.HandleRequest());
            }

            return(new SkillResponse());
        }
Пример #13
0
 private string GetMastreenoAuthUserToken(SkillRequest skillRequest)
 {
     return(skillRequest.Context.System.User.AccessToken);
 }
Пример #14
0
 private bool IsUserSignedIn(SkillRequest skillRequest)
 {
     return(skillRequest.Context.System.User.AccessToken != null);
 }
Пример #15
0
        public SkillResponse FunctionHandler(SkillRequest request, ILambdaContext context)
        {
            var alexaSkill = ServiceContainer.GetOrCreate <AlexaSkill>();

            return(alexaSkill.Process(request, context));
        }
Пример #16
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));
            }
        }
Пример #17
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;
            }
        }
Пример #18
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);
        }
Пример #19
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);
        }
Пример #20
0
 public FunctionTests()
 {
     _function         = new Function();
     _anyLaunchRequest = Create(new LaunchRequest());
 }
        public Task <SkillResponse> HandleIntent(IntentRequest input, Session session, SkillRequest request = null)
        {
            var sessionAttr = session.Attributes["prayer_request"];
            var pry_msg     = "";

            if (sessionAttr == null)
            {
                pry_msg = "You have no active prayer point";
            }
            else
            {
                pry_msg = (string)session.Attributes["prayer_request"];
            }

            Reprompt rp       = new Reprompt(pry_msg);
            var      response = ResponseBuilder.Ask(pry_msg, rp, session);

            return(Task.FromResult(response));
        }
Пример #22
0
 /// <summary>
 /// Return true if the inputted request is an IntentRequest and it's Intent is not null.
 /// </summary>
 /// <param name="request"></param>
 /// <returns></returns>
 public override bool IsHandlerForRequest(SkillRequest request)
 {
     return(request.Request is IntentRequest &&
            (request.Request as IntentRequest).Intent != null);
 }
Пример #23
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);
      }
Пример #24
0
        public void UseSkill(Skill skill)
        {
            var request = new SkillRequest(skill);

            Send(request.RawPacket);
        }
Пример #25
0
        public SkillResponse HandleResponse(SkillRequest alexaRequestInput)
        {
            AlexaRequestValidationService    validator        = new AlexaRequestValidationService();
            SpeechletRequestValidationResult validationResult = validator.ValidateAlexaRequest(alexaRequestInput);

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

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

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

                logger.Debug("Launch request in");

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

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

                response.Response.ShouldEndSession = false;

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

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

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

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


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

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

            return(response);
        }
Пример #26
0
        public void OpenDoor()
        {
            var request = new SkillRequest(0x58, null);

            Send(request.RawPacket);
        }
Пример #27
0
 private static SkillResponse AskAboutNextOpponent(SkillRequest request, Intent intent, string nextOpponent)
 {
     intent.Slots[SlotNames.Opponent].Value = nextOpponent;
     return(ResponseBuilder.DialogConfirmSlot(Responses.NextChallenger(nextOpponent), SlotNames.Opponent,
                                              request.Session, intent));
 }
Пример #28
0
        public async Task <SkillResponse> Post([FromBody] SkillRequest request)
        {
            var requestType = request.GetRequestType();

            if (requestType == typeof(IntentRequest))
            {
                var intentRequest = request.Request as IntentRequest;
                var phrase        = intentRequest.Intent.Slots["Search"].Value;

                var intentResponse = await this.IntentFinder.GetIntentAsync(phrase);

                var speechText = new StringBuilder();
                switch (intentResponse.Intent)
                {
                case "GetLastVisitingPlace":
                    speechText.Append(await GetLastVisitingPlaceAsync());
                    break;

                case "GetAllVisitingPlace":
                    speechText.Append(await GetAllVisitingPlaceAsync());
                    break;

                case "GetVisitingPlace":
                    if (intentResponse.Entities.Count <= 0)
                    {
                        speechText.Append("No he podido encontrar ningún lugar que haya visitado Rodolfo. ");
                    }
                    else
                    {
                        speechText.Append(await GetVisitingPlaceAsync(intentResponse.Entities.FirstOrDefault().Name));
                    }
                    break;

                default:
                    speechText.Append("Rodolfo no parece que tenga ningún mensaje interesante que compartir con nosotros.");
                    break;
                }

                var speechTextString = speechText.ToString();

                return(new SkillResponse
                {
                    Version = "1.0",
                    Response = new ResponseBody
                    {
                        OutputSpeech = new PlainTextOutputSpeech {
                            Text = speechTextString
                        },
                        Card = new SimpleCard {
                            Title = "Rodolfo Viajero", Content = speechTextString
                        },
                        ShouldEndSession = true
                    }
                });
            }

            return(new SkillResponse
            {
                Version = "1.0",
                Response = new ResponseBody
                {
                    // Use SSML here to make voice more realistic.
                    OutputSpeech = new PlainTextOutputSpeech {
                        Text = $"Hmmm, Rodolfo no ha entendido tu mensaje, tal vez esté sin cobertura en algún lugar recóndito."
                    },
                    Card = new SimpleCard {
                        Title = "Rodolfo Viajero", Content = "Hmmm, Rodolfo no ha entendido tu mensaje, tal vez esté sin cobertura en algún lugar recóndito."
                    },
                    ShouldEndSession = true
                }
            });
        }
        public SkillResponse Handle(SkillRequest skillRequest)
        {
            var intentRequest = (IntentRequest)skillRequest.Request;

            return(Handle(intentRequest, skillRequest.Session, skillRequest.Context));
        }
Пример #30
0
 public PersonProfileClient(SkillRequest request) : this(
         request.Context.System.ApiEndpoint,
         request.Context.System.ApiAccessToken)
 {
 }