public IniciarRotinaIntent(ILocaleSpeech locale, SkillRequest input)
 {
     _locale = locale;
     _input  = input;
     _acc    = _input.Session.Attributes["pin"] as String;
     _token  = _input.Session.Attributes["Auth"] as String;
 }
Example #2
0
 public ConsultaExtratoIntent(ILocaleSpeech locale, SkillRequest input)
 {
     _locale = locale;
     _input  = input;
     _acc    = _input.Session.Attributes["pin"] as String;
     _token  = _input.Session.Attributes["Auth"] as String;
 }
Example #3
0
        public static async Task <SkillResponse> ValidatorAsync(SkillRequest _input, ILocaleSpeech _locale)
        {
            //Autorização - Necessario estáo com o pin valido para ter acesso a essa informação
            if (string.IsNullOrEmpty(_input.Session.Attributes["pin"] as String))
            {
                _input.Session.Attributes["ExecIntent"] = "ConsultaExtratoIntent";
                var message = await _locale.Get(LanguageKeys.AcessoProtegido, null);

                SkillResponse response = ResponseBuilder.Ask(message, null, _input.Session);
                return(response);
            }

            return(null);
        }
        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);
        }
Example #5
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);
        }
Example #6
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);
        }
Example #7
0
        public override async Task <ActionResult <IActionResult> > HandleAsync(SkillRequest input)
        {
            /// <summary>
            /// Bloco de segurança para verificando e validar o request enviado pela Alexa,
            /// identificando possiveis fraudes.
            /// </summary>
            var req     = HttpContext.Request;
            var isValid = await input.ValidateRequestAsync(req, _logger);

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


            var           request  = input.Request;
            SkillResponse response = new SkillResponse {
                Response = new ResponseBody()
            };

            DictionaryLocaleSpeechStore store = LanguagesResource.SetupLanguageResources();
            ILocaleSpeech locale = input.CreateLocale(store);

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

                if (!(request is IntentRequest intentRequest))
                {
                    return(new BadRequestResult());
                }

                string IntentName = intentRequest.Intent.Name;

                if (string.IsNullOrEmpty((String)input.Session.Attributes["Auth"]))
                {
                    //Autenticação
                    string token = await HttpSenderApi.Call();

                    input.Session.Attributes["Auth"] = token;
                }

                if (intentRequest.Intent.Name == "PinUsuarioIntent")
                {
                    Account user = await new LogInPinAlexa(_repository).LogInAlexaAsync(intentRequest.Intent.Slots["pin"].Value);
                    if (user != null)
                    {
                        input.Session.Attributes.Add("pin", user.AccountId);
                        IOutputSpeech message = await locale.Get(LanguageKeys.Pinvalido, null);

                        response = ResponseBuilder.Ask(message, null, input.Session);
                        return(new OkObjectResult(response));
                    }
                    else
                    {
                        IOutputSpeech message = await locale.Get(LanguageKeys.PinInvalido, null);

                        response = ResponseBuilder.Ask(message, null, input.Session);
                        return(new OkObjectResult(response));
                    }
                }

                if (intentRequest.Intent.Name != "PinUsuarioIntent")
                {
                    response = await ExecuteIntentAlexaAsync(IntentName, input, locale);
                }
            }
            catch (Exception ex)
            {
                var message = await locale.Get(LanguageKeys.Error, null);

                response = ResponseBuilder.Tell(message);
                _logger.LogError(ex.Message + " : ", message);
            }

            return(new OkObjectResult(response));
        }
Example #8
0
        public static async Task <SkillResponse> ExecuteIntentAlexaAsync(string IntentName, SkillRequest input, ILocaleSpeech locale)
        {
            //Acha o Intent correto entre as classes e executa seu processo
            Type            repType = Type.GetType("SafraAssistenteVirtualInteligente.Web.Intents.Alexa." + IntentName);
            IIntentResponse intent  = Activator.CreateInstance(repType, locale, input) as IIntentResponse;

            return(await intent.ExecuteIntentAsync());
        }