Ejemplo n.º 1
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);
            }

            return(response != null, response);
        }
Ejemplo n.º 2
0
        private async Task <(bool IsHandled, SkillResponse Response)> HandleSystemIntentsAsync()
        {
            SkillResponse response = null;

            if (_accessor.IntentRequest.Intent.Name == IntentNames.Cancel)
            {
                var message = await _accessor.LocaleSpeech.Get(LanguageKeys.Cancel, null);

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

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

                response = ResponseBuilder.Tell(message);
            }
            else if (_accessor.IntentRequest.Intent.Name == IntentNames.Favorites ||
                     Equals(_accessor.Session.Attributes.GetValueOrDefault(SessionAtributeNames.lastIntent), IntentNames.Favorites))
            {
                response = await _favDialog.HandleFavIntent();
            }
            return(response != null, response);
        }
Ejemplo n.º 3
0
        internal async Task <SkillResponse> HandleTranslationPossibilityAsync()
        {
            _accessor.Session.Attributes.Add(SessionAtributeNames.lastIntent, _accessor.IntentRequest.Intent.Name);

            var message = await _accessor.LocaleSpeech.Get(LanguageKeys.Translate, null);

            var messageReprompt = await _accessor.LocaleSpeech.Get(LanguageKeys.TranslateReprompt, null);

            var response = ResponseBuilder.Ask(message, RepromptBuilder.Create(messageReprompt), _accessor.Session);

            return(response);
        }
Ejemplo n.º 4
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);
        }
Ejemplo n.º 5
0
        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));
        }
Ejemplo n.º 6
0
        public 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());
            }

            _accessor.Session = skillRequest.Session;
            if (_accessor.Session.Attributes == null)
            {
                _accessor.Session.Attributes = new Dictionary <string, object>();
            }

            // Setup language resources. if lang slot detected set resources in slot's language, otherwise set store's one
            var store = _languageService.SetupLanguageResources();

            _accessor.LocaleSpeech = skillRequest.CreateLocale(store);

            _accessor.Request = skillRequest.Request;
            _accessor.Lang    = _languageService.AdaptCulture(_accessor.Request.Locale);

            _accessor.LocaleResources = _languageService.SetupAuxLanguageResourcesByLang(_accessor.Lang);

            SkillResponse response = null;

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

                    var welcomeMessage = await _accessor.LocaleSpeech.Get(LanguageKeys.Welcome, null);

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

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

                    if (systemIntentResponse.IsHandled)
                    {
                        response = systemIntentResponse.Response;
                    }
                    else
                    {
                        // Processes request according to intentRequest.Intent.Name...
                        var message = await _accessor.LocaleSpeech.Get(LanguageKeys.Error, null);

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

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

            return(new OkObjectResult(response));
        }
Ejemplo n.º 7
0
        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;

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

                    var welcomeMessage = await locale.Get(LanguageKeys.Welcome, null);

                    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
                    {
                        // Processes request according to intentRequest.Intent.Name...
                        var message = await locale.Get(LanguageKeys.Response, null);

                        string slotValue = intentRequest.Intent.Slots["location"].Value;
                        if (!String.IsNullOrEmpty(slotValue))
                        {
                            slotValue = intentRequest.Intent.Slots["location"].Value.Trim().ToUpper();
                        }
                        log.LogInformation("Supplied Slot Value - " + slotValue);
                        string covidData = await GetCurrentData(slotValue, log).ConfigureAwait(false);

                        log.LogInformation("Data recvd - " + covidData);
                        response = ResponseBuilder.Tell(covidData);

                        // Note: The ResponseBuilder.Tell method automatically sets the
                        // Response.ShouldEndSession property to true, so the session will be
                        // automatically closed at the end of the response.
                    }
                }
                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));
        }
Ejemplo n.º 8
0
        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;

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

                    var givenName   = "Sconosciuto";
                    var accessToken = skillRequest.Session?.User?.AccessToken;
                    if (!string.IsNullOrWhiteSpace(accessToken))
                    {
                        var client = GetAuthenticatedClientForUser(accessToken);
                        var me     = await client.Me.Request().GetAsync();

                        givenName = me.GivenName;
                    }

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

                    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 == "rolldice")
                        {
                            var faces = Convert.ToInt32(intentRequest.Intent.Slots["faces"].Value);

                            var random = new Random();
                            var number = random.Next(1, faces);

                            var message = await locale.Get(LanguageKeys.Response, new string[] { faces.ToString(), number.ToString() });

                            response = ResponseBuilder.Tell(message);
                        }

                        // Note: The ResponseBuilder.Tell method automatically sets the
                        // Response.ShouldEndSession property to true, so the session will be
                        // automatically closed at the end of the response.
                    }
                }
                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));
        }
Ejemplo n.º 9
0
        public static async Task <IActionResult> Run([HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = null)] HttpRequest req,
                                                     [CosmosDB(databaseName: "spyfalldb", collectionName: "locations", ConnectionStringSetting = "CosmosDBConnection")] DocumentClient locationClient,
                                                     [CosmosDB(databaseName: "spyfalldb", collectionName: "games", ConnectionStringSetting = "CosmosDBConnection")] DocumentClient gameClient,
                                                     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());
            }
            Session session = skillRequest.Session;
            // Setup language resources.
            var store  = SetupLanguageResources();
            var locale = skillRequest.CreateLocale(store);

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

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

                    //var welcomeMessage = await locale.Get(LanguageKeys.Welcome, null);
                    var welcomeMessage = "Hello";
                    //var welcomeRepromptMessage = await locale.Get(LanguageKeys.WelcomeReprompt, null);
                    var welcomeRepromptMessage = "Hello Again!";
                    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, locationClient, gameClient, session, log);

                    if (systemIntentResponse.IsHandled)
                    {
                        response = systemIntentResponse.Response;
                    }
                    else
                    {
                        // Processes request according to intentRequest.Intent.Name...
                        var message = await locale.Get(LanguageKeys.Response, null);

                        response = ResponseBuilder.Tell(message);

                        // Note: The ResponseBuilder.Tell method automatically sets the
                        // Response.ShouldEndSession property to true, so the session will be
                        // automatically closed at the end of the response.
                    }
                }
                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));
        }
Ejemplo n.º 10
0
        private static async Task <(bool IsHandled, SkillResponse Response)> HandleSystemIntentsAsync(IntentRequest request,
                                                                                                      ILocaleSpeech locale,
                                                                                                      DocumentClient locationClient,
                                                                                                      DocumentClient gameClient,
                                                                                                      Session session,
                                                                                                      ILogger log)
        {
            SkillResponse response = null;

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

                response = ResponseBuilder.Tell(message);
                break;
            }

            case IntentNames.Help:
            {
                var message = await locale.Get(LanguageKeys.Help, null);

                response = ResponseBuilder.Ask(message, RepromptBuilder.Create(message));
                break;
            }

            case IntentNames.Stop:
            {
                var message = await locale.Get(LanguageKeys.Stop, null);

                response = ResponseBuilder.Tell(message);
                break;
            }

            case IntentNames.StartGame:
            {
                var message = await locale.Get(LanguageKeys.StartGame, null);

                await gameClient.CreateDocumentAsync(UriFactory.CreateDocumentCollectionUri("spyfalldb", "games"), new Game
                    {
                        id             = session.SessionId,
                        Players        = new Dictionary <string, double>(),
                        QuestionsAsked = new List <string>(),
                        Location       = "",
                        Cards          = new List <int>()
                    });

                response = ResponseBuilder.Ask(message, RepromptBuilder.Create(message));
                break;
            }

            case IntentNames.AddPlayer:
            {
                var collectURI = UriFactory.CreateDocumentCollectionUri("spyfalldb", "games");
                int generated  = 0;
                try
                {
                    Game next = gameClient.CreateDocumentQuery <Game>(collectURI, new FeedOptions {
                            EnableCrossPartitionQuery = true
                        }).Where(p => p.id.Equals(session.SessionId)).AsEnumerable().FirstOrDefault();
                    next.Players.Add(request.Intent.Slots["player"].Value, 0.3);
                    Random rnd = new Random();
                    do
                    {
                        generated = rnd.Next(29) + 1;
                    } while (next.Cards.Contains(generated));
                    next.Cards.Add(generated);
                    await gameClient.UpsertDocumentAsync(collectURI, next);
                }
                catch (Exception e)
                {
                    log.LogError(e.ToString());
                    throw e;
                }
                log.LogInformation("Something very distinct");

                var message = "I have assigned you card number " + generated;
                response = ResponseBuilder.Ask(message, RepromptBuilder.Create(message));
                break;
            }

            case IntentNames.PlayGame:
            {
                Random r = new Random();
                var    collectLocalURI = UriFactory.CreateDocumentCollectionUri("spyfalldb", "locations");
                var    collectURI      = UriFactory.CreateDocumentCollectionUri("spyfalldb", "games");
                try
                {
                    LocationIndex locIn = locationClient.CreateDocumentQuery <LocationIndex>(collectLocalURI, new FeedOptions {
                            EnableCrossPartitionQuery = true
                        }).Where(p => p.id.Equals("index")).AsEnumerable().FirstOrDefault();
                    Cards cards = locationClient.CreateDocumentQuery <Cards>(collectLocalURI, new FeedOptions {
                            EnableCrossPartitionQuery = true
                        }).Where(p => p.id.Equals("cards")).AsEnumerable().FirstOrDefault();
                    Game game = gameClient.CreateDocumentQuery <Game>(collectURI, new FeedOptions {
                            EnableCrossPartitionQuery = true
                        }).Where(p => p.id.Equals(session.SessionId)).AsEnumerable().FirstOrDefault();
                    log.LogInformation("ourLocal");
                    string ourLocal = locIn.locations[r.Next(locIn.locations.Count)];
                    game.Location = ourLocal;
                    int spy = r.Next(game.Cards.Count);
                    log.LogInformation("spy " + spy);
                    StringBuilder strbuilder = new StringBuilder("For every player, I will read out your card number and the symbol you should look for: ");
                    for (int i = 0; i < game.Cards.Count; i++)
                    {
                        var card   = game.Cards[i];
                        var symbol = "";
                        if (i == spy)
                        {
                            symbol = cards.symbols["Spy"][card];
                        }
                        else
                        {
                            symbol = cards.symbols[ourLocal][card];
                        }
                        strbuilder.Append("Card ").Append(card).Append(". ").Append(symbol).Append(". ");
                    }
                    log.LogInformation("For loop exit");
                    if (session.Attributes == null)
                    {
                        session.Attributes = new Dictionary <string, object>();
                    }
                    session.Attributes["questions"]      = 0;
                    session.Attributes["askedQuestion"]  = 0;
                    session.Attributes["expectedAnswer"] = 0;
                    session.Attributes["playerAsked"]    = -1;
                    await gameClient.UpsertDocumentAsync(collectURI, game);

                    var message = strbuilder.ToString();
                    response = ResponseBuilder.Ask(message, RepromptBuilder.Create(message), session);
                }
                catch (Exception e)
                {
                    log.LogError(e.ToString());
                    throw e;
                }
                break;
            }

            case IntentNames.StartQuestions:
            {
                try
                {
                    Random r = new Random();
                    var    collectLocalURI = UriFactory.CreateDocumentCollectionUri("spyfalldb", "locations");
                    var    collectURI      = UriFactory.CreateDocumentCollectionUri("spyfalldb", "games");
                    Game   game            = gameClient.CreateDocumentQuery <Game>(collectURI, new FeedOptions {
                            EnableCrossPartitionQuery = true
                        }).Where(p => p.id.Equals(session.SessionId)).AsEnumerable().FirstOrDefault();
                    Location location = locationClient.CreateDocumentQuery <Location>(collectLocalURI, new FeedOptions {
                            EnableCrossPartitionQuery = true
                        }).Where(p => p.id.Equals(game.Location)).AsEnumerable().FirstOrDefault();
                    if ((long)session.Attributes["questions"] == 0)
                    {
                        var playername = game.Players.First().Key;
                        var question   = location.questions.Keys.ElementAt(r.Next(location.questions.Count));
                        game.QuestionsAsked.Add(question);
                        session.Attributes["questions"]      = 1;
                        session.Attributes["playerAsked"]    = playername;
                        session.Attributes["playerNumAsked"] = 0;
                        session.Attributes["expectedAnswer"] = location.questions[question];
                        await gameClient.UpsertDocumentAsync(collectURI, game);

                        var message = playername + " " + question;
                        response = ResponseBuilder.Ask(message, RepromptBuilder.Create(message), session);
                    }
                }
                catch (Exception e)
                {
                    log.LogError(e.ToString());
                    throw e;
                }
                break;
            }

            case IntentNames.Yes:
            {
                try
                {
                    var  collectLocalURI = UriFactory.CreateDocumentCollectionUri("spyfalldb", "locations");
                    var  collectURI      = UriFactory.CreateDocumentCollectionUri("spyfalldb", "games");
                    Game game            = gameClient.CreateDocumentQuery <Game>(collectURI, new FeedOptions {
                            EnableCrossPartitionQuery = true
                        }).Where(p => p.id.Equals(session.SessionId)).AsEnumerable().FirstOrDefault();
                    Location location = locationClient.CreateDocumentQuery <Location>(collectLocalURI, new FeedOptions {
                            EnableCrossPartitionQuery = true
                        }).Where(p => p.id.Equals(game.Location)).AsEnumerable().FirstOrDefault();
                    if ((long)session.Attributes["questions"] != 0)
                    {
                        var player     = session.Attributes["playerAsked"] as string;
                        var difference = Math.Abs((long)session.Attributes["expectedAnswer"] - 1);
                        if (difference == 0)
                        {
                            game.Players[player] = Math.Max(game.Players[player] - .2, 0);
                        }
                        else if (difference == 1)
                        {
                            game.Players[player] = Math.Min(game.Players[player] + .3, 1);
                        }
                        else if (difference == 2)
                        {
                            game.Players[player] = Math.Min(game.Players[player] + .5, 1);
                        }
                    }

                    var    message  = "";
                    Random r        = new Random();
                    var    question = "";
                    do
                    {
                        question = location.questions.Keys.ElementAt(r.Next(location.questions.Count));
                    } while (game.QuestionsAsked.Contains(question));
                    game.QuestionsAsked.Add(question);
                    var questions = (long)session.Attributes["questions"] + 1;
                    if (questions > Math.Min(game.Players.Count * 3, 12))
                    {
                        message = "Hmmm Ok. I am ready to make my guess.";
                        session.Attributes["guess"] = game.Players.Aggregate((a, b) => a.Value > b.Value ? a : b).Key;
                        response = ResponseBuilder.Ask(message, RepromptBuilder.Create(message), session);
                        break;
                    }
                    session.Attributes["questions"] = questions;

                    long playerNum = (long)session.Attributes["playerNumAsked"];
                    if (++playerNum > game.Players.Count - 1)
                    {
                        playerNum = 0;
                    }
                    string playername = game.Players.Keys.ElementAt((int)playerNum);
                    session.Attributes["playerNumAsked"] = playerNum;
                    session.Attributes["playerAsked"]    = playername;
                    session.Attributes["expectedAnswer"] = location.questions[question];
                    await gameClient.UpsertDocumentAsync(collectURI, game);

                    message  = "Hmmm Ok. " + playername + ", " + question;
                    response = ResponseBuilder.Ask(message, RepromptBuilder.Create(message), session);
                }
                catch (Exception e)
                {
                    log.LogError(e.ToString());
                    throw e;
                }
                break;
            }

            case IntentNames.No:
            {
                try
                {
                    var  collectLocalURI = UriFactory.CreateDocumentCollectionUri("spyfalldb", "locations");
                    var  collectURI      = UriFactory.CreateDocumentCollectionUri("spyfalldb", "games");
                    Game game            = gameClient.CreateDocumentQuery <Game>(collectURI, new FeedOptions {
                            EnableCrossPartitionQuery = true
                        }).Where(p => p.id.Equals(session.SessionId)).AsEnumerable().FirstOrDefault();
                    Location location = locationClient.CreateDocumentQuery <Location>(collectLocalURI, new FeedOptions {
                            EnableCrossPartitionQuery = true
                        }).Where(p => p.id.Equals(game.Location)).AsEnumerable().FirstOrDefault();
                    if ((long)session.Attributes["questions"] != 0)
                    {
                        var player     = session.Attributes["playerAsked"] as string;
                        var difference = Math.Abs((long)session.Attributes["expectedAnswer"] + 1);
                        if (difference == 0)
                        {
                            game.Players[player] = Math.Max(game.Players[player] - .2, 0);
                        }
                        else if (difference == 1)
                        {
                            game.Players[player] = Math.Min(game.Players[player] + .3, 1);
                        }
                        else if (difference == 2)
                        {
                            game.Players[player] = Math.Min(game.Players[player] + .5, 1);
                        }
                    }

                    var    message  = "";
                    Random r        = new Random();
                    var    question = "";
                    do
                    {
                        question = location.questions.Keys.ElementAt(r.Next(location.questions.Count));
                    } while (game.QuestionsAsked.Contains(question));
                    game.QuestionsAsked.Add(question);
                    var questions = (long)session.Attributes["questions"] + 1;
                    if (questions > Math.Min(game.Players.Count * 3, 12))
                    {
                        message = "Hmmm Ok. I am ready to make my guess.";
                        session.Attributes["guess"] = game.Players.Aggregate((a, b) => a.Value > b.Value ? a : b).Key;
                        response = ResponseBuilder.Ask(message, RepromptBuilder.Create(message), session);
                        break;
                    }
                    session.Attributes["questions"] = questions;

                    long playerNum = (long)session.Attributes["playerNumAsked"];
                    if (++playerNum > game.Players.Count - 1)
                    {
                        playerNum = 0;
                    }
                    string playername = game.Players.Keys.ElementAt((int)playerNum);
                    session.Attributes["playerNumAsked"] = playerNum;
                    session.Attributes["playerAsked"]    = playername;
                    session.Attributes["expectedAnswer"] = location.questions[question];
                    await gameClient.UpsertDocumentAsync(collectURI, game);

                    message  = "Hmmm Ok. " + playername + ", " + question;
                    response = ResponseBuilder.Ask(message, RepromptBuilder.Create(message), session);
                }
                catch (Exception e)
                {
                    log.LogError(e.ToString());
                    throw e;
                }
                break;
            }

            case IntentNames.Maybe:
            {
                try
                {
                    var  collectLocalURI = UriFactory.CreateDocumentCollectionUri("spyfalldb", "locations");
                    var  collectURI      = UriFactory.CreateDocumentCollectionUri("spyfalldb", "games");
                    Game game            = gameClient.CreateDocumentQuery <Game>(collectURI, new FeedOptions {
                            EnableCrossPartitionQuery = true
                        }).Where(p => p.id.Equals(session.SessionId)).AsEnumerable().FirstOrDefault();
                    Location location = locationClient.CreateDocumentQuery <Location>(collectLocalURI, new FeedOptions {
                            EnableCrossPartitionQuery = true
                        }).Where(p => p.id.Equals(game.Location)).AsEnumerable().FirstOrDefault();
                    if ((long)session.Attributes["questions"] != 0)
                    {
                        var player     = session.Attributes["playerAsked"] as string;
                        var difference = Math.Abs((long)session.Attributes["expectedAnswer"] + 1);
                        if (difference == 1)
                        {
                            game.Players[player] = Math.Min(game.Players[player] + .4, 1);
                        }
                    }
                    var    message  = "";
                    Random r        = new Random();
                    var    question = "";
                    do
                    {
                        question = location.questions.Keys.ElementAt(r.Next(location.questions.Count));
                    } while (game.QuestionsAsked.Contains(question));
                    game.QuestionsAsked.Add(question);
                    var questions = (long)session.Attributes["questions"] + 1;
                    if (questions > Math.Min(game.Players.Count * 3, 12))
                    {
                        message = "Hmmm Ok. I am ready to make my guess.";
                        session.Attributes["guess"] = game.Players.Aggregate((a, b) => a.Value > b.Value ? a : b).Key;
                        response = ResponseBuilder.Ask(message, RepromptBuilder.Create(message), session);
                        break;
                    }
                    session.Attributes["questions"] = questions;

                    long playerNum = (long)session.Attributes["playerNumAsked"];
                    if (++playerNum > game.Players.Count - 1)
                    {
                        playerNum = 0;
                    }
                    string playername = game.Players.Keys.ElementAt((int)playerNum);
                    session.Attributes["playerNumAsked"] = playerNum;
                    session.Attributes["playerAsked"]    = playername;
                    session.Attributes["expectedAnswer"] = location.questions[question];
                    await gameClient.UpsertDocumentAsync(collectURI, game);

                    message  = "Hmmm Ok. " + playername + ", " + question;
                    response = ResponseBuilder.Ask(message, RepromptBuilder.Create(message), session);
                }
                catch (Exception e)
                {
                    log.LogError(e.ToString());
                    throw e;
                }
                break;
            }

            case IntentNames.Reveal:
            {
                string message = "I think the spy is " + session.Attributes["guess"] + ". Was I right? Thanks for playing! Goodbye.";
                response = ResponseBuilder.Tell(message, session);
                break;
            }
            }
            return(response != null, response);
        }
Ejemplo n.º 11
0
        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;

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

                    var welcomeMessage = await locale.Get(LanguageKeys.Welcome, null);

                    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
                    {
                        // Processes request according to intentRequest.Intent.Name...
                        if (intentRequest.Intent.Name == "RollDice")
                        {
                            Random random  = new Random();
                            int    value   = random.Next(1, 6);
                            var    message = await locale.Get(LanguageKeys.RollDice, new string[] { value.ToString() });

                            response = ResponseBuilder.Tell(message);
                        }
                    }
                }
                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));
        }