public override async Task <SkillResponse> Handle(WorkItemStore workItemStore, SkillRequest skillRequest)
        {
            if (!(skillRequest.Request is IntentRequest intentRequest))
            {
                throw new InvalidOperationException(
                          $"Expected type {typeof(IntentRequest)} but got {skillRequest.Request.GetType()}");
            }

            // First step: check for cancel

            string intentName = intentRequest.Intent.Name;

            if (intentRequest.Intent.Name.Equals("AMAZON.CancelIntent", StringComparison.OrdinalIgnoreCase))
            {
                Log.LogTrace($"Cancel Intent");
                return(await Task.Run(() =>
                {
                    return ResponseBuilder.Tell("Goodbye then!");
                }).ConfigureAwait(false));
            }

            // Try to read the affected item
            //    and run AzDoBridge actions

            if (AzDoBridgeActionFactory.TryGetAction(intentName, Log, out IAzDoBridgeAction action))
            {
                return(await Task.Run(() =>
                {
                    return action.Run(workItemStore, skillRequest);
                }).ConfigureAwait(false));
            }

            Log.LogTrace($"intent not recognized");
            return(await Task.Run(() =>
            {
                return ResponseBuilder.Ask("IntentRequest Not Recognized, you can say, set item ID to Item State", null);
            }).ConfigureAwait(false));
        }
Beispiel #2
0
        internal override SkillResponse processRequest()
        {
            m_log.LogInformation("Session started");
            string first       = null;
            string last        = null;
            bool   isDesignate = false;

            if (LastRequest.Session.Attributes.ContainsKey("designated_last"))
            {
                isDesignate = true;
            }
            else
            {
                last  = (string)LastRequest.Session.Attributes["account_last"];
                first = (string)LastRequest.Session.Attributes["account_first"];
            }
            var speech = new SsmlOutputSpeech();

            if (isDesignate)
            {
                speech.Ssml = "<speak>I cannot report hours for a designated volunteer. If you cancel I will reset to the account owner.</speak>";
                SkillResponse response = ResponseBuilder.Tell(speech);
                response.Response.ShouldEndSession = false;
                return(response);
            }
            speech.Ssml =
                "<speak>You have <say-as interpret-as=\"cardinal\">10</say-as> volunteer hours.</speak>";
            SsmlOutputSpeech reprompt = null;

            reprompt      = new SsmlOutputSpeech();
            reprompt.Ssml = "<speak>I am ready for more requests. You can ask me something like <prosody rate=\"slow\">add hours or report hours.</prosody></speak>";
            return(ResponseBuilder.Ask(
                       speech,
                       new Reprompt
            {
                OutputSpeech = reprompt
            }));
        }
Beispiel #3
0
        private static async Task <(bool IsHandled, SkillResponse Response)> HandleSystemIntentsAsync(IntentRequest request, ILocaleSpeech locale)
        {
            SkillResponse response = null;

            if (request.Intent.Name == IntentNames.Cancel)
            {
                var message = await locale.Get(LanguageKeys.Cancel, null);

                response = ResponseBuilder.Tell(message);
            }
            else if (request.Intent.Name == IntentNames.Help)
            {
                var message = await locale.Get(LanguageKeys.Help, null);

                response = ResponseBuilder.Ask(message, RepromptBuilder.Create(message));
            }
            else if (request.Intent.Name == IntentNames.Stop)
            {
                var message = await locale.Get(LanguageKeys.Stop, null);

                response = ResponseBuilder.Tell(message);
            }
            else if (request.Intent.Name == IntentNames.ReadList)
            {
                var message = await GetUserListMessage();

                var reprompt = new Reprompt("Do you want to hear the winner?");
                response = ResponseBuilder.Ask(message, reprompt);
            }
            else if (request.Intent.Name == IntentNames.PickWinner)
            {
                var names = await TypeformAPI.GetNames();

                var winner = names.Shuffle().FirstOrDefault();
                response = ResponseBuilder.Tell($"The winner is {winner}");
            }
            return(response != null, response);
        }
        private SkillResponse Usage()
        {
            var commonUsage = "You can say 'What are today's threats?' to list today's space-based threats to earth, or say Help to get more information.";

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

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

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

            repromptMessage.Text = commonUsage;

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

            repromptBody.OutputSpeech = repromptMessage;

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

            return(finalResponse);
        }
        public SkillResponse Handle(SkillRequest input)
        {
            IntentRequest request   = input.Request as IntentRequest;
            string        stateName = request.Intent.Slots["statecapitals"].Value;

            if (request.Intent.Slots["statecapitals"].Resolution.Authorities.Any())
            {
                stateName = request.Intent.Slots["statecapitals"].Resolution.Authorities[0].Values[0].Value.Name;
            }

            var capital = _stateCapitalRepo.GetCapital(stateName);

            if (capital == null)
            {
                return(ResponseBuilder.Ask(" I do not know the capital you are asking about, how may I help you? "
                                           , new Reprompt("I do not have all day, how may I help you?")));
            }

            var output = ResponseBuilder.Ask($" The capital city of {stateName} is {capital.capital}. Got any more brain busters I can answer? "
                                             , new Reprompt("I do not have all day, how may I help you?"));

            return(output);
        }
        public static SkillResponse RequestHandler(SkillRequest skillRequest)
        {
            SkillResponse response = new SkillResponse();

            switch (skillRequest.Request.Type)
            {
            case "LaunchRequest":
                response = ResponseBuilder.Ask("YOUR RESPONSE TEXT HERE", new Reprompt("YOUR REPROMPT TEXT HERE"));
                break;

            case "SessionEndedRequest":
                response.Response = new ResponseBody()
                {
                    ShouldEndSession = true
                };
                break;

            case "IntentRequest":
                response = IntentRequestHandler(skillRequest);
                break;
            }
            return(response);
        }
Beispiel #7
0
        static SkillResponse HandleAskForAnotherDeployIntent(IntentRequest request, Session session, ILogger log)
        {
            SkillResponse response;

            session.Attributes.Clear();

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

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

            return(response);
        }
Beispiel #8
0
        private SkillResponse CheckFoodFunction(SkillRequest input, ILambdaContext context, IntentRequest intentRequest, SsmlOutputSpeech speech)
        {
            SkillResponse finalResponse;
            // get the slots
            var foodName = intentRequest.Intent.Slots["foodname"].Value;

            context.Logger.Log($"What is it {foodName}");

            if (IsPaleoFood(foodName))
            {
                // create the speech response - cards still need a voice response
                speech.Ssml = "<speak>Yes. No limit but only once in a day! Would you like to know more about paleo activities?</speak>";
            }
            else
            {
                // create the speech response - cards still need a voice response
                speech.Ssml = "<speak>No! It is not paleo food. Would you like to know more about paleo activities?</speak>";
            }

            // create the speech reprompt
            var repromptMessage = new PlainTextOutputSpeech();

            repromptMessage.Text = "Would you like to know more paleo activities?";

            input.Session.Attributes["paleoActivities"] = "true";

            // create the reprompt
            var repromptBody = new Reprompt();

            repromptBody.OutputSpeech = repromptMessage;

            // create the response
            finalResponse = ResponseBuilder.Ask(speech, repromptBody, input.Session);

            return(finalResponse);
        }
Beispiel #9
0
        private SkillResponse ExplainPalexo(SkillRequest input, ILambdaContext context, IntentRequest intentRequest, SsmlOutputSpeech speech)
        {
            SkillResponse finalResponse;

            // get the slots
            // create the speech response - cards still need a voice response
            speech.Ssml = $"<speak>A proven diet plan, helps you to reduce your weight in 90 days! To know more about paleo please visit offical Facebook Paleo C U G group. Would you like to know how to start the paleo diet?</speak>";

            // create the speech reprompt
            var repromptMessage = new PlainTextOutputSpeech();

            repromptMessage.Text = "Would you like to know how to start the paleo diet?";

            //context.Logger.Log(input.Session.Attributes.ToString());

            foreach (var item in input.Session.Attributes.Values)
            {
                context.Logger.Log(item.ToString());
            }

            input.Session.Attributes["startpaleodiet"] = "true";
            //var yesIntentValuePaleofoodlist = Convert.ToBoolean(input.Session.Attributes["paleofoodlist"]);
            //var yesIntentValueStartPaleoDiet = Convert.ToBoolean(input.Session.Attributes["startpaleodiet"]);

            //context.Logger.Log("ExplainPaleo "+yesIntentValuePaleofoodlist.ToString());
            //context.Logger.Log("ExplainPaleo " + yesIntentValueStartPaleoDiet.ToString());

            // create the reprompt
            var repromptBody = new Reprompt();

            repromptBody.OutputSpeech = repromptMessage;

            // create the response
            finalResponse = ResponseBuilder.Ask(speech, repromptBody, input.Session);
            return(finalResponse);
        }
        public SkillResponse FunctionHandler(SkillRequest input, ILambdaContext context)
        {
            var log = context.Logger;

            log.LogLine($"Skill request: {JsonConvert.SerializeObject(input)}");

            switch (input.Request)
            {
            case LaunchRequest _:
                return(ResponseBuilder.Ask("Welcome at Making Software.", new Reprompt
                {
                    OutputSpeech = new PlainTextOutputSpeech
                    {
                        Text = "You can ask me something about Making Software"
                    }
                }));

            case IntentRequest intentRequest:
                return(GetIntentResponse(intentRequest));

            default:
                return(ResponseBuilder.Empty());
            }
        }
Beispiel #11
0
        private SkillResponse StartGame(Session session)
        {
            var cardValue = new Random().Next(0, Cards.Length);

            session.Attributes = new Dictionary <string, object>
            {
                { "count", 0 },
                { "value", cardValue }
            };

            var speech   = $"Let's begin. So we start your game with a {Cards[cardValue]}. Is the next card higher or lower?";
            var reminder = $"The question is, is the next card higher or lower than a {Cards[cardValue]}";

            return(ResponseBuilder.Ask(
                       new PlainTextOutputSpeech {
                Text = speech
            },
                       new Reprompt {
                OutputSpeech = new PlainTextOutputSpeech {
                    Text = reminder
                }
            },
                       session));
        }
        public void AalmadaTest()
        {
            var response = ResponseBuilder
                           .Ask("Welcome to my skill. How can I help", new Reprompt());


            var json = JObject.FromObject(new APLDocument(APLDocumentVersion.V1_2));
            var launchTemplateApl = JObject.FromObject(json);

            var launchTemplateData = new ObjectDataSource
            {
                ObjectId     = "launchScreen",
                Properties   = new Dictionary <string, object>(),
                TopLevelData = new Dictionary <string, object>(),
            };

            launchTemplateData.Properties.Add("textContent", "My Skill");
            launchTemplateData.Properties.Add("hintText", "Try, \"What can you do?\"");

            var directive = CreateAplDirective(launchTemplateApl, ("launchTemplateData", launchTemplateData));

            response.Response.Directives.Add(directive);
            var output = JsonConvert.SerializeObject(response);
        }
 public override SkillResponse HandleSyncRequest(RequestInformation information)
 {
     return(ResponseBuilder.Ask(response, new Reprompt(reprompt)));
 }
        public void AskWithPlainTextMismatchPhrase()
        {
            var response = ResponseBuilder.Ask("test phrase", null);

            Assert.Throws <PredicateFailedException>(() => response.Asks <PlainTextOutputSpeech>(s => s.Text == "not the test phrase"));
        }
        public void AskWithPlainTextMatchingPhrase()
        {
            var response = ResponseBuilder.Ask("test phrase", null);

            response.Asks <PlainTextOutputSpeech>(s => s.Text == "test phrase");
        }
        public void AskNegativeShouldEndSession()
        {
            var response = ResponseBuilder.Ask("test", null);

            response.Asks();
        }
        public void AskRepromptPlainTextNegativeCheck()
        {
            var response = ResponseBuilder.Ask("test", new Reprompt("invalid phrase"));

            Assert.Throws <PredicateFailedException>(() => response.HasReprompt <PlainTextOutputSpeech>(pt => pt.Text == "test reprompt"));
        }
Beispiel #18
0
        public static async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequest req,
            ILogger log)
        {
            //log the invocation
            log.LogInformation("DaveMusic HTTP trigger function processed a request.");

            //Create a new HTTP Client
            HttpClient httpclient = new HttpClient();

            //read the http request
            string json = await req.ReadAsStringAsync();

            //deserialize it into skillRequest
            var skillRequest = JsonConvert.DeserializeObject <SkillRequest>(json);

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

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

            //Get the token from the account linking
            string mytoken = skillRequest.Context.System.User.AccessToken;

            //check the type of request
            var requestType = skillRequest.GetRequestType();

            //lookup the IPAddress for the user - using the AccessToken to connect to the IPAddress
            DatabaseLookup dblookup = new DatabaseLookup();

            IPAddress = dblookup.GetIPAddress(mytoken);

            //create a skill response to send back to Alexa
            SkillResponse response = null;

            //if it's the launch then do initial processing
            if (requestType == typeof(LaunchRequest))
            {
                //first check for ipaddress
                if (IPAddress != "")
                {
                    //Tell sends a message - use Ask to ask a question
                    response = ResponseBuilder.Tell("Welcome to My Music. What do you want to play?");


                    //by default the conversation ends, use ShouldEndSession = False to keep the dialog open
                    response.Response.ShouldEndSession = false;
                }
            }
            //Get the intent request
            else if (requestType == typeof(IntentRequest))
            {
                //initialize artist and room variables
                var artist = "";
                var room   = "";

                //check to see which type of intent it is (PlayMusic or SkipMusic)
                var intentRequest = skillRequest.Request as IntentRequest;

                //get the slots (Artist and Room)
                if (intentRequest.Intent.Slots != null)
                {
                    if (intentRequest.Intent.Slots["Artist"].Value != null || intentRequest.Intent.Slots["Artist"].SlotValue != null)
                    {
                        //Get the artist name
                        artist = intentRequest.Intent.Slots["Artist"].Value;

                        //convert first character to upper case - Required for Telnet
                        artist = char.ToUpper(artist[0]) + artist.Substring(1);
                    }
                    if (intentRequest.Intent.Slots["Room"].Value != null || intentRequest.Intent.Slots["Room"].SlotValue != null)
                    {
                        //get the room name
                        room = intentRequest.Intent.Slots["Room"].Value;

                        //remove the word "the" if it's there. Required for Telnet
                        if (room.Substring(0, 4) == "the ")
                        {
                            room = room.Substring(4);
                        }

                        //convert first character to upper case - Required for Telnet
                        room = char.ToUpper(room[0]) + room.Substring(1);
                    }



                    //if there's a room then direct the music there.
                    if (room.Length > 0)
                    {
                        if (intentRequest.Intent.Name == "PlayMusic")
                        {
                            //Have alexa repeat the request using Tell
                            response = ResponseBuilder.Tell($"Playing {artist} in {room}");
                        }
                        else if (intentRequest.Intent.Name == "PlayRadio")
                        {
                            //Have alexa repeat the request using Tell
                            response = ResponseBuilder.Tell($"Playing {artist} radio in {room}");
                        }

                        //Leave the dialog open
                        response.Response.ShouldEndSession = true;
                    }
                    else
                    //no room so just change the music
                    {
                        //have alexa repeat the command
                        if (response.Response == null)
                        {
                            response = ResponseBuilder.Tell($"Playing {artist}");

                            //leave the dialog open
                            response.Response.ShouldEndSession = true;
                        }
                    }
                }
                //Spotify request
                if (intentRequest.Intent.Name == "PlayMusic")
                {
                    var client = new RestClient();
                    client.BaseUrl = new Uri(URL + "?ipaddress=" + IPAddress + "&Service=Spotify&Room=" + room + "&Artist=" + artist);
                    var request = new RestRequest();

                    //Fire and forget the API call
                    functionCallAndForget foo = new functionCallAndForget();
                    Task.Run(() => foo.callAPI(client, request));
                }

                //If it's a radio request ("PlayRadio") then send it to Pandora
                else if (intentRequest.Intent.Name == "PlayRadio") //Pandora
                {
                    try
                    {
                        //Create new Rest Sharp Client
                        var client = new RestClient();

                        //Set the URL and the room
                        client.BaseUrl = new Uri(URL + "?ipaddress=" + IPAddress + "&Service=Pandora&Room=" + room + "&Artist=" + artist);

                        //Create new Rest Sharp Request
                        var request = new RestRequest();

                        //execute the request
                        //  IRestResponse myresponse = client.Execute(request);

                        //Fire and forget the API call
                        functionCallAndForget foo = new functionCallAndForget();
                        Task.Run(() => foo.callAPI(client, request));
                    }
                    catch (Exception ex)
                    {
                        throw ex;
                    }
                }
                // if the intent was to skip the song
                else if (intentRequest.Intent.Name == "SkipMusic")
                {
                    //Have alexa repeat the request
                    response = ResponseBuilder.Tell("Skipping Song");

                    //TODO: Replace hardcoded IP address
                    //create telnet client to send request
                    using (Client client = new Client(IPAddress, 5004, new System.Threading.CancellationToken()))
                    {
                        //ping the media server
                        await client.WriteLine("Ping");

                        string s = await client.TerminatedReadAsync("Server=", TimeSpan.FromMilliseconds(1000));

                        Console.WriteLine(s);

                        //Skip the song
                        await client.WriteLine("SKIPNEXT");

                        string u = await client.TerminatedReadAsync(">", TimeSpan.FromMilliseconds(1000));

                        Console.WriteLine(u);
                    }
                }
                else if (intentRequest.Intent.Name == "AMAZON.CancelIntent" || intentRequest.Intent.Name == "AMAZON.StopIntent")  //Stop or Cancel
                {
                    try
                    {
                        //Stop the music if asked to stop or cancel
                        response = ResponseBuilder.Tell("Stopping Music");

                        //Create new Rest Sharp Client
                        var client = new RestClient();

                        //Set the URL and the room
                        client.BaseUrl = new Uri("https://elan-api-music.azurewebsites.net/stop?ipaddress=" + IPAddress);

                        //Create new Rest Sharp Request
                        var request = new RestRequest();

                        //execute the request
                        //  IRestResponse myresponse = client.Execute(request);

                        //Fire and forget the API call
                        functionCallAndForget foo = new functionCallAndForget();
                        Task.Run(() => foo.callAPI(client, request));
                        return(new OkObjectResult(response));
                    }
                    catch (Exception ex)
                    {
                        throw ex;
                    }
                }
                else if (intentRequest.Intent.Name == "AMAZON.HelpIntent")  //Stop or Cancel
                {
                    try
                    {
                        //Stop the music if asked to stop or cancel
                        response = ResponseBuilder.Ask("Try saying something like Play Prince in the Kitchen.", null);
                        response.Response.ShouldEndSession = false;
                    }
                    catch (Exception ex)
                    {
                        throw ex;
                    }
                }
            }
            //if the session is ending
            else if (requestType == typeof(SessionEndedRequest))
            {
                //have alexa say goodbye
                response = ResponseBuilder.Tell("See you next time!");

                //end the dialog
                response.Response.ShouldEndSession = true;
            }
            return(new OkObjectResult(response));
        }
        public void AskWithSsmlMatchingPhrase()
        {
            var response = ResponseBuilder.Ask(new Speech(new PlainText("test phrase")), null);

            response.Asks <SsmlOutputSpeech>(s => s.Ssml == "<speak>test phrase</speak>");
        }
        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));
        }
        //--- Methods ---
        public SkillResponse FunctionHandler(SkillRequest skill, ILambdaContext context)
        {
            // load adventure from S3
            var game = GameLoader.Parse(ReadTextFromS3(_s3Client, _adventureFileBucket, _adventureFilePath));

            // restore player object from session
            GamePlayer player;

            if (skill.Session.New)
            {
                // TODO: can we restore the player from DynamoDB?
                player = new GamePlayer(Game.StartPlaceId);
            }
            else
            {
                player = SessionLoader.Deserialize(game, skill.Session);
            }

            // decode skill request
            IEnumerable <AGameResponse> responses;
            IEnumerable <AGameResponse> reprompt = null;

            switch (skill.Request)
            {
            // skill was activated without an intent
            case LaunchRequest launch:
                LambdaLogger.Log($"*** INFO: launch\n");
                responses = game.TryDo(player, GameCommandType.Restart);
                reprompt  = game.TryDo(player, GameCommandType.Help);
                return(ResponseBuilder.Ask(
                           ConvertToSpeech(responses),
                           new Reprompt {
                    OutputSpeech = ConvertToSpeech(reprompt)
                },
                           SessionLoader.Serialize(game, player)
                           ));

            // skill was activated with an intent
            case IntentRequest intent:

                // check if the intent is an adventure intent
                if (Enum.TryParse(intent.Intent.Name, true, out GameCommandType command))
                {
                    LambdaLogger.Log($"*** INFO: adventure intent ({intent.Intent.Name})\n");
                    responses = game.TryDo(player, command);
                    reprompt  = game.TryDo(player, GameCommandType.Help);
                }
                else
                {
                    switch (intent.Intent.Name)
                    {
                    // built-in intents
                    case BuiltInIntent.Help:
                        LambdaLogger.Log($"*** INFO: built-in help intent ({intent.Intent.Name})\n");
                        responses = game.TryDo(player, GameCommandType.Help);
                        reprompt  = game.TryDo(player, GameCommandType.Help);
                        break;

                    case BuiltInIntent.Stop:
                    case BuiltInIntent.Cancel:
                        LambdaLogger.Log($"*** INFO: built-in stop/cancel intent ({intent.Intent.Name})\n");
                        responses = game.TryDo(player, GameCommandType.Quit);
                        break;

                    // unknown & unsupported intents
                    default:
                        LambdaLogger.Log("*** WARNING: intent not recognized\n");
                        responses = new[] { new GameResponseNotUnderstood() };
                        reprompt  = game.TryDo(player, GameCommandType.Help);
                        break;
                    }
                }

                // respond with serialized player state
                if (reprompt != null)
                {
                    return(ResponseBuilder.Ask(
                               ConvertToSpeech(responses),
                               new Reprompt {
                        OutputSpeech = ConvertToSpeech(reprompt)
                    },
                               SessionLoader.Serialize(game, player)
                               ));
                }
                return(ResponseBuilder.Tell(ConvertToSpeech(responses)));

            // skill session ended (no response expected)
            case SessionEndedRequest ended:
                LambdaLogger.Log("*** INFO: session ended\n");
                return(ResponseBuilder.Empty());

            // exception reported on previous response (no response expected)
            case SystemExceptionRequest error:
                LambdaLogger.Log("*** INFO: system exception\n");
                LambdaLogger.Log($"*** EXCEPTION: skill request: {JsonConvert.SerializeObject(skill)}\n");
                return(ResponseBuilder.Empty());

            // unknown skill received (no response expected)
            default:
                LambdaLogger.Log($"*** WARNING: unrecognized skill request: {JsonConvert.SerializeObject(skill)}\n");
                return(ResponseBuilder.Empty());
            }
        }
Beispiel #22
0
        public SkillResponse HandleGetVersicherungsprodukteIntent(string gesellschaft, SkillResponse response)
        {
            hilfsAttributes.Clear();// = new Dictionary<string, object>();
            if (gesellschaft != "")
            {
                switch (gesellschaft)
                {
                case "hallesche":
                case "hallesche krankenversicherung":
                    log.LogLine($"GetVersicherungsprodukte: Gesellschaft {gesellschaft}");
                    response = ResponseBuilder.Ask(new PlainTextOutputSpeech()
                    {
                        Text = messageRessource.VersicherungsprodukteHallesche
                               //"Informationen über Versicherungsprodukte der Halleschen Krankenversicherung. Versicherungsprodukt?"
                    }, new Reprompt()
                    {
                        OutputSpeech = new PlainTextOutputSpeech {
                            Text = "Reprompt"
                        },
                    });
                    response.Response.ShouldEndSession = false;
                    hilfsAttributes.Add(sessionId.ToString(), HILFSTATES.HandleGetVersicherungsprodukteIntent);
                    break;

                case "alte leipziger":
                case "alte leipziger lebensversicherung":
                    log.LogLine($"GetVersicherungsprodukte: Gesellschaft {gesellschaft}");
                    response = ResponseBuilder.Ask(new PlainTextOutputSpeech()
                    {
                        Text = messageRessource.VersicherungsprodukteAlteLeipziger
                               //"Informationen über Versicherungsprodukte der Alten Leipziger Lebensversicherung. Versicherungsprodukt?"
                    }, new Reprompt()
                    {
                        OutputSpeech = new PlainTextOutputSpeech {
                            Text = "Reprompt"
                        },
                    });
                    response.Response.ShouldEndSession = false;
                    hilfsAttributes.Add(sessionId.ToString(), HILFSTATES.HandleGetVersicherungsprodukteIntent);
                    break;

                case "konzern":
                case "gesamten konzern":
                    log.LogLine($"GetVersicherungsprodukte: Gesellschaft {gesellschaft}");
                    response = ResponseBuilder.Ask(new PlainTextOutputSpeech()
                    {
                        Text = messageRessource.VersicherungsprodukteKonzern
                               //"Informationen über Versicherungsprodukte des gesamten Konzerns. Versicherungsprodukt?"
                    }, new Reprompt()
                    {
                        OutputSpeech = new PlainTextOutputSpeech {
                            Text = "Reprompt"
                        },
                    });
                    response.Response.ShouldEndSession = false;
                    hilfsAttributes.Add(sessionId.ToString(), HILFSTATES.HandleGetVersicherungsprodukteIntent);
                    break;
                }
            }
            // gesellschaft unbekannt
            else
            {
                response = this.GetGesellschaft();
                response.Response.ShouldEndSession = false;
            }
            return(response);
        }
Beispiel #23
0
        public SkillResponse Handle(SkillRequest input)
        {
            var output = ResponseBuilder.Ask("Hello world likes to say hello, say Hi or hello. How can I help you today?", new Reprompt("Hello world likes to say hello, say Hi or hello., how may I help you?"));

            return(output);
        }
Beispiel #24
0
 public override Task <SkillResponse> HandleAsync(SkillRequest request)
 {
     return(Task.FromResult(ResponseBuilder.Ask("Welcome to abstracted .NET Alexa Skills. How can I help?", null)));
 }
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 AskWithSpeechMatchingPhrase()
        {
            var response = ResponseBuilder.Ask(new Speech(new PlainText("test phrase")), null);

            response.Asks <SsmlOutputSpeech>(s => s.Ssml == new Speech(new PlainText("test phrase")).ToXml());
        }
Beispiel #27
0
 public override SkillResponse HandleSyncRequest(RequestInformation information)
 {
     return(ResponseBuilder.Ask(
                "Hi there, thanks for wanting to learn more about Alexa dot net. What feature would you like to find out about?",
                new Reprompt("What feature would you like to find out about?")));
 }
        public void AskWithSsmlMismatchPhrase()
        {
            var response = ResponseBuilder.Ask(new Speech(new PlainText("test phrase")), null);

            Assert.Throws <PredicateFailedException>(() => response.Asks <SsmlOutputSpeech>(s => s.Ssml == "not the test phrase"));
        }
        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 async Task <ActionResult> HandleRequest([FromBody] SkillRequest skillRequest)
        {
            // validate the alexa request: https://developer.amazon.com/docs/custom-skills/host-a-custom-skill-as-a-web-service.html
            //var isValid = await ValidateRequest(Request, skillRequest);
            //if (!isValid)
            //    return BadRequest("Validation errors");


            // if it's Launch request, then say hello and tell the user the commands
            if (skillRequest?.GetRequestType() == typeof(LaunchRequest))
            {
                return(Ok(ResponseBuilder.Ask("Welcome to the dark souls controller, issue a command like 'roll' or 'Fireball!'. Prepare to die!", null)));
            }
            // if it's an intent request, then choose what command based on the name of the intent
            else if (skillRequest?.GetRequestType() == typeof(IntentRequest))
            {
                var intentRequest = skillRequest.Request as IntentRequest;
                await _hub.Clients.All.SendAsync(intentRequest.Intent.Name, intentRequest);

                switch (intentRequest.Intent.Name)
                {
                case "RightLightIntent":
                    return(Ok(ResponseBuilder.Tell("Light attack")));

                case "RightHeavyIntent":
                    return(Ok(ResponseBuilder.Tell("Heavy attack")));

                case "LeftLightIntent":
                    return(Ok(ResponseBuilder.Tell("Left Light attack")));

                case "LeftHeavyIntent":
                    return(Ok(ResponseBuilder.Tell("Left Heavy attack")));

                case "RollIntent":
                    return(Ok(ResponseBuilder.Ask("Rolling!", null)));

                case "ItemIntent":
                    return(Ok(ResponseBuilder.Tell("Using item. Hopefully it isn't estus")));

                case "SwapLeftWeaponIntent":
                    return(Ok(ResponseBuilder.Tell("Swapping left")));

                case "SwapRightWeaponIntent":
                    return(Ok(ResponseBuilder.Tell("Swapping right")));

                case "MoveForwardIntent":
                case "MoveBackwardsIntent":
                case "MoveLeftIntent":
                case "MoveRightIntent":
                    return(Ok(ResponseBuilder.Tell("Moving!")));

                case "QuickQuitIntent": return(Ok(ResponseBuilder.Tell("Abort!")));


                case "AMAZON.HelpIntent": return(Ok(ResponseBuilder.Ask("Happy to help! You can issue commands such as 'jump', 'reload', 'put on shields' and more! Try saying one of those.", null)));

                case "AMAZON.StopIntent":
                case "AMAZON.CancelIntent": return(Ok(ResponseBuilder.Tell("Thanks for using the DarkSouls Controller. Come back later.")));

                default: return(Ok(ResponseBuilder.Tell("Executing command")));
                }
            }

            return(Ok(ResponseBuilder.Ask("You said something I don't know what to do with. Try saying something like 'jump' or 'reload'.", null)));
        }