Beispiel #1
0
        public async Task <QuestionResult> Pass(ChatRoom chat, UserWordModel word,
                                                UserWordModel[] examList)
        {
            var originTranslation = word.RuTranslations.ToList().GetRandomItemOrNull();

            var variants = examList.SelectMany(e => e.TextTranslations)
                           .Where(e => !word.TextTranslations.Contains(e))
                           .Distinct()
                           .Shuffle()
                           .Take(5)
                           .Append(originTranslation.Word)
                           .Shuffle()
                           .ToList();

            var msg = QuestionMarkups.TranslateTemplate(word.Word, chat.Texts.ChooseTheTranslation);

            await chat.SendMarkdownMessageAsync(msg, InlineButtons.CreateVariants(variants));

            var choice = await chat.TryWaitInlineIntKeyboardInput();

            if (choice == null)
            {
                return(QuestionResult.RetryThisQuestion);
            }

            var selected = variants[choice.Value];

            return(word.TextTranslations.Any(t => t.AreEqualIgnoreCase(selected))
                ? QuestionResult.Passed(chat.Texts)
                : QuestionResult.Failed(chat.Texts));
        }
        public async Task <QuestionResult> Pass(ChatRoom chat, UserWordModel word,
                                                UserWordModel[] examList)
        {
            var translations = string.Join(", ", word.TextTranslations.Shuffle().Take(3));

            var variants = examList
                           .Where(e => e.AllTranslationsAsSingleString != word.AllTranslationsAsSingleString)
                           .Select(e => string.Join(", ", e.TextTranslations.Shuffle().Take(3)))
                           .Shuffle()
                           .Take(5)
                           .Append(translations)
                           .ToList();

            var msg = QuestionMarkups.TranslateTemplate(word.Word, chat.Texts.ChooseTheTranslation);
            await chat.SendMarkdownMessageAsync(msg, InlineButtons.CreateVariants(variants));

            var choice = await chat.TryWaitInlineIntKeyboardInput();

            if (choice == null)
            {
                return(QuestionResult.RetryThisQuestion);
            }

            var answer = variants[choice.Value].Split(",")
                         .Select(e => e.Trim()).ToList();

            return(!answer.Except(word.TextTranslations).Any()
                ? QuestionResult.Passed(chat.Texts)
                : QuestionResult.Failed(chat.Texts));
        }
        public async Task <QuestionResult> Pass(ChatRoom chat, UserWordModel word, UserWordModel[] examList)
        {
            var(phrase, translation) = word.GetExamplesThatLoadedAndFits().GetRandomItemOrNull();
            if (phrase == null)
            {
                return(QuestionResult.Impossible);
            }
            var(enPhrase, ruPhrase) = phrase.Deconstruct();

            var allWordsWithPhraseOfSimilarTranslate = examList
                                                       .SelectMany(e => e.Examples)
                                                       .Where(p => p.TranslatedPhrase.AreEqualIgnoreCase(ruPhrase))
                                                       .Select(e => e.OriginWord)
                                                       .ToList();

            var enReplaced = enPhrase.Replace(phrase.OriginWord, "\\.\\.\\.");

            if (enReplaced == enPhrase)
            {
                return(QuestionResult.Impossible);
            }

            await chat.SendMarkdownMessageAsync(
                QuestionMarkups.TranslatesAsTemplate(
                    ruPhrase,
                    chat.Texts.translatesAs,
                    enReplaced,
                    chat.Texts.EnterMissingWord + ":"));

            var enter = await chat.WaitNonEmptyUserTextInputAsync();

            if (enter.IsRussian())
            {
                await chat.SendMessageAsync(chat.Texts.EnglishInputExpected);

                return(QuestionResult.RetryThisQuestion);
            }

            var(closestWord, comparation) = allWordsWithPhraseOfSimilarTranslate.GetClosestTo(enter.Trim());
            if (comparation == StringsCompareResult.Equal)
            {
                return(QuestionResult.Passed(chat.Texts));
            }
            if (enter.Contains(word.Word, StringComparison.InvariantCultureIgnoreCase) && enPhrase.Contains(enter))
            {
                //if user enters whole world (as it is in phrase) - it is ok
                return(QuestionResult.Passed(chat.Texts));
            }

            if (comparation == StringsCompareResult.SmallMistakes)
            {
                await chat.SendMessageAsync(chat.Texts.TypoAlmostRight);

                return(QuestionResult.RetryThisQuestion);
            }

            return(QuestionResult.Failed(
                       $"{chat.Texts.FailedOriginExampleWasMarkdown}\r\n*\"{phrase.OriginPhrase}\"*",
                       chat.Texts));
        }
        public async Task <QuestionResult> Pass(ChatRoom chat, UserWordModel word, UserWordModel[] examList)
        {
            var originTranslation = word.RuTranslations.GetRandomItemOrNull();

            if (string.IsNullOrWhiteSpace(originTranslation.Transcription) || originTranslation.Transcription != "")
            {
                return(QuestionResult.Impossible);
            }

            var variants = examList.Where(e => e.RuTranslations.All(t => t.Transcription != originTranslation.Transcription))
                           .SelectMany(e => e.TextTranslations)
                           .Take(5)
                           .Append(originTranslation.Word)
                           .Shuffle()
                           .ToList();


            var msg = QuestionMarkups.TranscriptionTemplate(originTranslation.Transcription, chat.Texts.ChooseWhichWordHasThisTranscription);
            await chat.SendMarkdownMessageAsync(msg, InlineButtons.CreateVariants(variants));

            var choice = await chat.TryWaitInlineIntKeyboardInput();

            if (choice == null)
            {
                return(QuestionResult.RetryThisQuestion);
            }

            if (word.TextTranslations.Contains(variants[choice.Value]))
            {
                return(QuestionResult.Passed(chat.Texts));
            }
            return(QuestionResult.Failed(chat.Texts));
        }
        public async Task <QuestionResult> Pass(
            ChatRoom chat, UserWordModel word,
            UserWordModel[] examList)
        {
            var(phrase, translation) = word.GetExamplesThatLoadedAndFits().GetRandomItemOrNull();
            if (phrase == null)
            {
                return(QuestionResult.Impossible);
            }
            var(enPhrase, ruPhrase) = phrase.Deconstruct();
            var replacedRuPhrase = ruPhrase.Replace(phrase.TranslatedWord, "\\.\\.\\.");

            if (replacedRuPhrase == ruPhrase)
            {
                return(QuestionResult.Impossible);
            }

            await chat.SendMarkdownMessageAsync(
                QuestionMarkups.TranslatesAsTemplate(
                    enPhrase,
                    chat.Texts.translatesAs,
                    replacedRuPhrase,
                    chat.Texts.EnterMissingWord + ":"));

            var enter = await chat.WaitNonEmptyUserTextInputAsync();

            if (!enter.IsRussian())
            {
                await chat.SendMessageAsync(chat.Texts.RussianInputExpected);

                return(QuestionResult.RetryThisQuestion);
            }

            var comparation = translation.Word.CheckCloseness(enter.Trim());

            if (comparation == StringsCompareResult.Equal)
            {
                return(QuestionResult.Passed(chat.Texts));
            }

            //if user enters whole word in phrase- it is ok!
            if (enter.Contains(translation.Word, StringComparison.InvariantCultureIgnoreCase) &&
                phrase.OriginPhrase.Contains(enter, StringComparison.InvariantCultureIgnoreCase))
            {
                return(QuestionResult.Passed(chat.Texts));
            }

            if (comparation == StringsCompareResult.SmallMistakes)
            {
                await chat.SendMessageAsync(chat.Texts.RetryAlmostRightWithTypo);

                return(QuestionResult.RetryThisQuestion);
            }


            return(QuestionResult.Failed($"{chat.Texts.FailedOriginExampleWas2} *\"{phrase.TranslatedPhrase}\"*",
                                         chat.Texts));
        }
Beispiel #6
0
        public async Task <QuestionResult> Pass(ChatRoom chat, UserWordModel word, UserWordModel[] examList)
        {
            var msg = QuestionMarkups.TranslateTemplate(word.AllTranslationsAsSingleString, chat.Texts.DoYouKnowTranslationMarkdown);
            var id  = Rand.Next();

            await chat.SendMarkdownMessageAsync(msg,
                                                new InlineKeyboardButton()
            {
                CallbackData = id.ToString(),
                Text         = chat.Texts.ShowTheTranslationButton
            });

            while (true)
            {
                var update = await chat.WaitUserInputAsync();

                if (update.CallbackQuery?.Data == id.ToString())
                {
                    break;
                }
                var input = update.Message?.Text;
                if (!string.IsNullOrWhiteSpace(input))
                {
                    if (word.Word.AreEqualIgnoreCase(input))
                    {
                        return(QuestionResult.Passed(chat.Texts));
                    }
                    await chat.SendMessageAsync(chat.Texts.ItIsNotRightTryAgain);
                }
            }

            await chat.SendMarkdownMessageAsync($"_{chat.Texts.TranslationIs} _\r\n" +
                                                $"*\"{word.Word}\"*\r\n\r\n" +
                                                $"{chat.Texts.DidYouGuess}",
                                                new[] {
                new[] {
                    new InlineKeyboardButton {
                        CallbackData = "1",
                        Text         = chat.Texts.YesButton
                    },
                    new InlineKeyboardButton {
                        CallbackData = "0",
                        Text         = chat.Texts.NoButton
                    }
                }
            }
                                                );

            var choice = await chat.WaitInlineIntKeyboardInput();

            return(choice == 1
                ? QuestionResult.Passed(
                       chat.Texts.PassedOpenIHopeYouWereHonestMarkdown,
                       chat.Texts.PassedHideousWell2)
                : QuestionResult.Failed(
                       chat.Texts.FailedOpenButYouWereHonestMarkdown,
                       chat.Texts.FailedHideousHonestyIsGoldMarkdown));
        }
Beispiel #7
0
        public async Task <QuestionResult> Pass(ChatRoom chat, UserWordModel word, UserWordModel[] examList)
        {
            if (!word.HasAnyExamples)
            {
                return(QuestionResult.Impossible);
            }

            var targetPhrase = word.GetRandomExample();

            string shuffled;

            while (true)
            {
                var wordsInExample = targetPhrase.SplitWordsOfPhrase;

                if (wordsInExample.Length < 2)
                {
                    return(QuestionResult.Impossible);
                }

                shuffled = string.Join(" ", wordsInExample.Shuffle());
                if (shuffled != targetPhrase.OriginPhrase)
                {
                    break;
                }
            }

            await chat.SendMarkdownMessageAsync(
                QuestionMarkups.FreeTemplate($"{chat.Texts.WordsInPhraseAreShuffledWriteThemInOrderMarkdown}:\r\n*\"{shuffled}\"*"));

            var entry = await chat.WaitUserTextInputAsync();

            if (entry.IsRussian())
            {
                await chat.SendMessageAsync(chat.Texts.EnglishInputExpected);

                return(QuestionResult.RetryThisQuestion);
            }

            var closeness = targetPhrase.OriginPhrase.CheckCloseness(entry.Trim());

            if (closeness == StringsCompareResult.Equal)
            {
                return(QuestionResult.Passed(chat.Texts));
            }

            if (closeness == StringsCompareResult.BigMistakes)
            {
                await chat.SendMessageAsync(chat.Texts.RetryAlmostRightWithTypo);

                return(QuestionResult.RetryThisQuestion);
            }

            return(QuestionResult.Failed(
                       $"{chat.Texts.FailedOriginExampleWas2Markdown}:\r\n*\"{targetPhrase.OriginPhrase}\"*",
                       chat.Texts));
        }
Beispiel #8
0
        public async Task <QuestionResult> Pass(ChatRoom chat, UserWordModel word,
                                                UserWordModel[] examList)
        {
            if (!word.Examples.Any())
            {
                return(QuestionResult.Impossible);
            }

            var phrase = word.GetRandomExample();

            var replaced = phrase.OriginPhrase.Replace(phrase.OriginWord, "\\.\\.\\.");

            if (replaced == phrase.OriginPhrase)
            {
                return(QuestionResult.Impossible);
            }

            var variants = examList
                           .Where(p => !p.Examples.Select(e => e.TranslatedPhrase)
                                  .Any(t => t.AreEqualIgnoreCase(phrase.TranslatedPhrase)))
                           .Select(e => e.Word)
                           .Shuffle()
                           .Take(5)
                           .Append(phrase.OriginWord)
                           .Shuffle()
                           .ToArray();

            var _ = await chat.SendMarkdownMessageAsync(
                QuestionMarkups.TranslatesAsTemplate(
                    phrase.TranslatedPhrase,
                    chat.Texts.translatesAs,
                    replaced,
                    chat.Texts.ChooseMissingWord + ":")
                , InlineButtons.CreateVariants(variants));

            var choice = await chat.TryWaitInlineIntKeyboardInput();

            if (choice == null)
            {
                return(QuestionResult.RetryThisQuestion);
            }

            if (variants[choice.Value].AreEqualIgnoreCase(word.Word))
            {
                return(QuestionResult.Passed(chat.Texts.Passed1Markdown,
                                             chat.Texts));
            }

            return(QuestionResult.Failed($"{chat.Texts.OriginWas}:\r\n*\"{phrase.OriginPhrase}\"*",
                                         chat.Texts));
        }
Beispiel #9
0
        public async Task UpdateCurrentScore(User user, int count)
        {
            var sw    = Stopwatch.StartNew();
            var words = await _userWordsRepository.GetOldestUpdatedWords(user, count);

            foreach (var word in words)
            {
                var model = new UserWordModel(word);
                model.UpdateCurrentScore();
                await _userWordsRepository.UpdateMetrics(model.Entity);
            }
            sw.Stop();
            Botlog.Metric(user.TelegramId, nameof(UpdateCurrentScore), $"{words.Count}", sw.Elapsed);
        }
Beispiel #10
0
        public async Task <ExamResult> Pass(
            ChatIO chatIo,
            UsersWordsService service,
            UserWordModel word,
            UserWordModel[] examList)
        {
            if (!word.HasAnyPhrases)
            {
                return(ExamResult.Impossible);
            }

            var targetPhrase = word.GetRandomExample();

            var otherExamples = examList
                                .SelectMany(e => e.Phrases)
                                .Where(p => p != targetPhrase)
                                .Take(8).ToArray();

            if (!otherExamples.Any())
            {
                return(ExamResult.Impossible);
            }

            var variants = otherExamples
                           .Append(targetPhrase)
                           .Randomize()
                           .Select(e => e.TranslatedPhrase)
                           .ToArray();

            var msg = $"=====>   {targetPhrase.OriginPhrase}    <=====\r\n" +
                      $"Choose the translation";
            await chatIo.SendMessageAsync(msg, InlineButtons.CreateVariants(variants));

            var choice = await chatIo.TryWaitInlineIntKeyboardInput();

            if (choice == null)
            {
                return(ExamResult.Retry);
            }

            if (variants[choice.Value] == targetPhrase.TranslatedPhrase)
            {
                await service.RegisterSuccess(word);

                return(ExamResult.Passed);
            }
            await service.RegisterFailure(word);

            return(ExamResult.Failed);
        }
        public async Task <QuestionResult> Pass(ChatRoom chat, UserWordModel word,
                                                UserWordModel[] examList)
        {
            var translation = examList.SelectMany(e => e.TextTranslations)
                              .Where(e => word.RuTranslations.All(t => t.Word != e))
                              .Shuffle()
                              .Take(1)
                              .Union(word.TextTranslations)
                              .ToList()
                              .GetRandomItemOrNull();

            var msg = QuestionMarkups.TranslatesAsTemplate(
                word.Word,
                chat.Texts.translatesAs,
                translation,
                chat.Texts.IsItRightTranslation);

            await chat.SendMarkdownMessageAsync(msg,
                                                new[] {
                new[] {
                    new InlineKeyboardButton {
                        CallbackData = "1",
                        Text         = chat.Texts.YesButton
                    },
                    new InlineKeyboardButton {
                        CallbackData = "0",
                        Text         = chat.Texts.NoButton
                    }
                }
            });

            var choice = await chat.WaitInlineIntKeyboardInput();

            if (
                choice == 1 && word.TextTranslations.Contains(translation) ||
                choice == 0 && !word.TextTranslations.Contains(translation)
                )
            {
                return(QuestionResult.Passed(chat.Texts));
            }
            else
            {
                return(QuestionResult.Failed(
                           $"{chat.Texts.Mistaken}\\.\r\n\"{word.Word}\" {chat.Texts.translatesAs} " +
                           $"*\"{word.TextTranslations.FirstOrDefault()}\"* ",
                           chat.Texts));
            }
        }
        public async Task <QuestionResult> Pass(ChatRoom chat, UserWordModel word, UserWordModel[] examList)
        {
            if (!word.Examples.Any())
            {
                return(QuestionResult.Impossible);
            }

            var targetPhrase = word.GetRandomExample();

            var other = examList.SelectMany(e => e.Examples)
                        .Where(p => !string.IsNullOrWhiteSpace(p?.OriginPhrase) && p.TranslatedPhrase != targetPhrase.TranslatedPhrase)
                        .Shuffle()
                        .Take(5)
                        .ToArray();

            if (!other.Any())
            {
                return(QuestionResult.Impossible);
            }

            var variants = other
                           .Append(targetPhrase)
                           .Shuffle()
                           .Select(e => e.OriginPhrase)
                           .ToArray();

            var msg = QuestionMarkups.TranslateTemplate(targetPhrase.TranslatedPhrase, chat.Texts.ChooseTheTranslation);
            await chat.SendMarkdownMessageAsync(msg,
                                                variants.Select((v, i) => new InlineKeyboardButton
            {
                CallbackData = i.ToString(),
                Text = v
            }).ToArray());

            var choice = await chat.TryWaitInlineIntKeyboardInput();

            if (choice == null)
            {
                return(QuestionResult.RetryThisQuestion);
            }

            return(variants[choice.Value].AreEqualIgnoreCase(targetPhrase.OriginPhrase)
                ? QuestionResult.Passed(chat.Texts)
                : QuestionResult.Failed(chat.Texts));
        }
Beispiel #13
0
        public IQuestion GetNextQuestionFor(bool isFirstExam, UserWordModel model)
        {
            if (isFirstExam && model.AbsoluteScore < WordLeaningGlobalSettings.IncompleteWordMinScore)
            {
                return(_simpleExamsList.GetRandomItemOrNull().Question);
            }

            var score = model.AbsoluteScore - (isFirstExam ? (WordLeaningGlobalSettings.LearnedWordMinScore / 2) : 0);

            if (model.AbsoluteScore < WordLeaningGlobalSettings.FamiliarWordMinScore)
            {
                return(ChooseExam(score, _intermidiateExamsList));
            }
            else
            {
                return(ChooseExam(score, _advancedExamsList));
            }
        }
Beispiel #14
0
        public IExam GetNextQuestionFor(bool isFirstExam, UserWordModel model)
        {
            if (isFirstExam && model.AbsoluteScore < 7)
            {
                return(_simpleExamsList.GetRandomItem().Exam);
            }

            var score = model.AbsoluteScore - (isFirstExam ? 2 : 0);

            if (model.AbsoluteScore < 4)
            {
                return(ChooseExam(score, _intermidiateExamsList));
            }
            else
            {
                return(ChooseExam(score, _advancedExamsList));
            }
        }
Beispiel #15
0
        public async Task <QuestionResult> Pass(ChatRoom chat,
                                                UserWordModel word,
                                                UserWordModel[] examList)
        {
            if (!word.HasAnyExamples)
            {
                return(QuestionResult.Impossible);
            }

            var targetPhrase = word.GetRandomExample();

            var otherExamples = examList
                                .SelectMany(e => e.Examples)
                                .Where(p => !p.TranslatedPhrase.AreEqualIgnoreCase(targetPhrase.TranslatedPhrase))
                                .Shuffle()
                                .Take(5)
                                .ToArray();

            if (!otherExamples.Any())
            {
                return(QuestionResult.Impossible);
            }

            var variants = otherExamples
                           .Append(targetPhrase)
                           .Select(e => e.TranslatedPhrase)
                           .Shuffle()
                           .ToArray();
            var msg = QuestionMarkups.TranslateTemplate(targetPhrase.OriginPhrase, chat.Texts.ChooseTheTranslation);

            await chat.SendMarkdownMessageAsync(msg, InlineButtons.CreateVariants(variants));

            var choice = await chat.TryWaitInlineIntKeyboardInput();

            if (choice == null)
            {
                return(QuestionResult.RetryThisQuestion);
            }

            return(variants[choice.Value].AreEqualIgnoreCase(targetPhrase.TranslatedPhrase)
                ? QuestionResult.Passed(chat.Texts)
                : QuestionResult.Failed(chat.Texts));
        }
Beispiel #16
0
        public async Task <QuestionResult> Pass(ChatRoom chat, UserWordModel word,
                                                UserWordModel[] examList)
        {
            var originalTranslation = word.RuTranslations.GetRandomItemOrNull();

            if (originalTranslation == null || !originalTranslation.HasTranscription)
            {
                return(QuestionResult.Impossible);
            }

            var variants = examList
                           .SelectMany(e => e.RuTranslations)
                           .Select(e => e.Transcription)
                           .Where(e => word.RuTranslations.All(t => t.Transcription != e))
                           .Distinct()
                           .Shuffle()
                           .Take(5)
                           .Append(originalTranslation.Transcription)
                           .Where(w => w != null)
                           .Shuffle()
                           .ToList();

            if (variants.Count <= 1)
            {
                return(QuestionResult.Impossible);
            }

            var msg = QuestionMarkups.TranslateTemplate(word.Word, chat.Texts.ChooseTheTranscription);
            await chat.SendMarkdownMessageAsync(msg, InlineButtons.CreateVariants(variants));

            var choice = await chat.TryWaitInlineIntKeyboardInput();

            if (choice == null)
            {
                return(QuestionResult.RetryThisQuestion);
            }

            return(word.RuTranslations.Any(t => t.Transcription == variants[choice.Value])
                ? QuestionResult.Passed(chat.Texts)
                : QuestionResult.Failed(chat.Texts));
        }
        public async Task<ExamResult> Pass(ChatIO chatIo, UsersWordsService service, UserWordModel word, UserWordModel[] examList)
        {
            if (!word.Phrases.Any())
                return ExamResult.Impossible;
            
            var targetPhrase = word.GetRandomExample();

            var other = examList.SelectMany(e => e.Phrases)
                .Where(p => !string.IsNullOrWhiteSpace(p?.OriginPhrase) && p!= targetPhrase)
                .Take(8).ToArray();

            if(!other.Any())
                return ExamResult.Impossible;

            var variants = other
                .Append(targetPhrase)
                .Randomize()
                .Select(e => e.OriginPhrase)
                .ToArray();
            
            var msg = $"=====>   {targetPhrase.TranslatedPhrase}    <=====\r\n" +
                      $"Choose the translation";
            await chatIo.SendMessageAsync(msg,
                variants.Select((v, i) => new InlineKeyboardButton
                {
                    CallbackData = i.ToString(),
                    Text = v
                }).ToArray());
            
            var choice = await chatIo.TryWaitInlineIntKeyboardInput();
            if (choice == null)
                return ExamResult.Retry;
            
            if (variants[choice.Value] == targetPhrase.OriginPhrase)
            {
                await service.RegisterSuccess(word);
                return ExamResult.Passed;
            }
            await service.RegisterFailure(word);
            return ExamResult.Failed;
        }
Beispiel #18
0
        private async Task <QuestionResult> PassWithRetries(
            IQuestion question,
            UserWordModel word,
            UserWordModel[] learnList,
            int wordQuestionNumber)
        {
            int retrieNumber = 0;

            for (int i = 0; i < 40; i++)
            {
                var result = await question.Pass(Chat, word, learnList);

                if (result.Results == ExamResult.Impossible)
                {
                    var qName = question.Name;
                    for (int iteration = 0; question.Name == qName; iteration++)
                    {
                        question = QuestionSelector.Singletone.GetNextQuestionFor(wordQuestionNumber == 0, word);
                        if (iteration > 100)
                        {
                            return(QuestionResult.Failed("", ""));
                        }
                    }
                }
                else if (result.Results == ExamResult.Retry)
                {
                    wordQuestionNumber++;
                    retrieNumber++;
                    if (retrieNumber >= 4)
                    {
                        return(QuestionResult.Failed("", ""));
                    }
                }
                else
                {
                    return(result);
                }
            }
            return(QuestionResult.Failed("", ""));
        }
Beispiel #19
0
        public async Task <QuestionResult> Pass(ChatRoom chat, UserWordModel word, UserWordModel[] examList)
        {
            var variants = examList.Where(e => e.AllTranslationsAsSingleString != word.AllTranslationsAsSingleString)
                           .Select(e => e.Word)
                           .Take(5)
                           .Append(word.Word)
                           .Shuffle()
                           .ToArray();


            var msg = QuestionMarkups.TranslateTemplate(word.AllTranslationsAsSingleString, chat.Texts.ChooseTheTranslation);
            await chat.SendMarkdownMessageAsync(msg, InlineButtons.CreateVariants(variants));

            var choice = await chat.TryWaitInlineIntKeyboardInput();

            if (choice == null)
            {
                return(QuestionResult.RetryThisQuestion);
            }

            return(variants[choice.Value].AreEqualIgnoreCase(word.Word)
                ? QuestionResult.Passed(chat.Texts)
                : QuestionResult.Failed(chat.Texts));
        }
        public async Task <ExamResult> Pass(ChatIO chatIo, UsersWordsService service, UserWordModel word, UserWordModel[] examList)
        {
            if (!word.HasAnyPhrases)
            {
                return(ExamResult.Impossible);
            }

            var targetPhrase = word.GetRandomExample();

            string shuffled;

            while (true)
            {
                var wordsInExample = targetPhrase.OriginWords;

                if (wordsInExample.Length < 2)
                {
                    return(ExamResult.Impossible);
                }

                shuffled = string.Join(" ", wordsInExample.Randomize());
                if (shuffled != targetPhrase.OriginPhrase)
                {
                    break;
                }
            }

            await chatIo.SendMessageAsync("Words in phrase are shuffled. Write them in correct order:\r\n'" + shuffled + "'");

            var entry = await chatIo.WaitUserTextInputAsync();

            entry = entry.Trim();

            if (string.Compare(targetPhrase.OriginPhrase, entry.Trim(), StringComparison.OrdinalIgnoreCase) == 0)
            {
                await service.RegisterSuccess(word);

                return(ExamResult.Passed);
            }

            await chatIo.SendMessageAsync($"Original phrase was: '{targetPhrase.OriginPhrase}'");

            await service.RegisterFailure(word);

            return(ExamResult.Failed);
        }
        private async Task <string?> EnterSingleWordAsync(string?word = null)
        {
            if (string.IsNullOrWhiteSpace(word))
            {
                await Chat.SendMessageAsync($"{Emojis.Translate} {Chat.Texts.EnterWordOrStart}");

                word = await Chat.WaitUserTextInputAsync();
            }

            Chat.User.OnAnyActivity();

            // Search translations in local dictionary

            UserWordModel alreadyExistUserWord = null;

            if (!word.IsRussian())
            {
                alreadyExistUserWord = await _addWordService.GetWordNullByEngWord(Chat.User, word);
            }

            var translations = await _addWordService.FindInLocalDictionaryWithExamples(word);

            if (!translations.Any()) // if not, search it in Ya dictionary
            {
                translations = await _addWordService.TranslateAndAddToDictionary(word);
            }

            if (translations?.Any() != true)
            {
                await Chat.SendMessageAsync(Chat.Texts.NoTranslationsFound);

                return(null);
            }

            // get button selection marks. It works only for english words!
            bool[] selectionMarks = GetSelectionMarks(translations, alreadyExistUserWord);

            if (!selectionMarks[0])
            {
                // Automaticly select first translation if it was not selected before
                await _addWordService.AddTranslationToUser(Chat.User, translations[0].GetEnRu());

                selectionMarks[0] = true;
            }

            // getting first transcription
            var transcription = translations.FirstOrDefault(t => !string.IsNullOrWhiteSpace(t.EnTranscription))
                                ?.EnTranscription;

            var handler = new LastTranslationHandler(
                translations: translations,
                chat: Chat,
                addWordService: _addWordService);

            _translationSelectedUpdateHook.SetLastTranslationHandler(handler);

            await handler.SendTranslationMessage(word, transcription, selectionMarks);

            if (word.IsRussian())
            {
                Chat.User.OnRussianWordTranslationRequest();
            }
            else
            {
                Chat.User.OnEnglishWordTranslationRequest();
            }

            try
            {
                // user request next word
                var res = await Chat.WaitUserTextInputAsync();

                // notify handler, that we leave the flow
                return(res);
            }
            finally
            {
                handler.OnNextTranslationRequest();
            }
        }
Beispiel #22
0
 public async Task RegisterSuccess(UserWordModel model)
 {
     model.OnExamPassed();
     model.UpdateCurrentScore();
     await _userWordsRepository.UpdateMetrics(model.Entity);
 }
        public async Task <ExamResult> Pass(ChatIO chatIo, UsersWordsService service, UserWordModel word,
                                            UserWordModel[] examList)
        {
            if (!word.Phrases.Any())
            {
                return(ExamResult.Impossible);
            }

            var phrase = word.GetRandomExample();

            var replaced = phrase.TranslatedPhrase.Replace(phrase.TranslatedWord, "...");

            if (replaced == phrase.TranslatedPhrase)
            {
                return(ExamResult.Impossible);
            }

            var sb = new StringBuilder();

            sb.AppendLine($"\"{phrase.OriginPhrase}\"");
            sb.AppendLine($" translated as ");
            sb.AppendLine($"\"{replaced}\"");
            sb.AppendLine();
            sb.AppendLine($"Enter missing word: ");
            await chatIo.SendMessageAsync(sb.ToString());

            while (true)
            {
                var enter = await chatIo.WaitUserTextInputAsync();

                if (string.IsNullOrWhiteSpace(enter))
                {
                    continue;
                }
                if (string.Compare(phrase.OriginWord, enter.Trim(), StringComparison.OrdinalIgnoreCase) == 0)
                {
                    await service.RegisterSuccess(word);

                    return(ExamResult.Passed);
                }

                await chatIo.SendMessageAsync($"Origin phrase was \"{phrase.TranslatedPhrase}\"");

                await service.RegisterFailure(word);

                return(ExamResult.Failed);
            }
        }
Beispiel #24
0
 public async Task RegisterFailure(UserWordModel userWordForLearning)
 {
     userWordForLearning.OnExamFailed();
     userWordForLearning.UpdateCurrentScore();
     await _userWordsRepository.UpdateMetrics(userWordForLearning.Entity);
 }
Beispiel #25
0
 public Task UpdateWord(UserWordModel model) =>
 _userWordsRepository.Update(model.Entity);
Beispiel #26
0
        public async Task <ExamResult> Pass(ChatIO chatIo, UsersWordsService service, UserWordModel word,
                                            UserWordModel[] examList)
        {
            var variants = examList.Randomize().SelectMany(e => e.GetTranslations()).ToArray();

            var msg = $"=====>   {word.Word}    <=====\r\n" +
                      $"Choose the translation";
            await chatIo.SendMessageAsync(msg, InlineButtons.CreateVariants(variants));

            var choice = await chatIo.TryWaitInlineIntKeyboardInput();

            if (choice == null)
            {
                return(ExamResult.Retry);
            }

            if (word.GetTranslations().Contains(variants[choice.Value]))
            {
                await service.RegisterSuccess(word);

                return(ExamResult.Passed);
            }

            await service.RegisterFailure(word);

            return(ExamResult.Failed);
        }
Beispiel #27
0
        public async Task <ExamResult> Pass(ChatIO chatIo, UsersWordsService service, UserWordModel word, UserWordModel[] examList)
        {
            if (!word.Phrases.Any())
            {
                return(ExamResult.Impossible);
            }

            var phrase = word.GetRandomExample();

            var replaced = phrase.OriginPhrase.Replace(phrase.OriginWord, "...");

            if (replaced == phrase.OriginPhrase)
            {
                return(ExamResult.Impossible);
            }

            var sb = new StringBuilder();

            sb.AppendLine($"\"{phrase.TranslatedPhrase}\"");
            sb.AppendLine();
            sb.AppendLine($" translated as ");
            sb.AppendLine();
            sb.AppendLine($"\"{replaced}\"");
            sb.AppendLine($"Choose missing word...");

            var variants = examList.Randomize().Select(e => e.Word).ToArray();
            var _        = chatIo.SendMessageAsync(sb.ToString(), InlineButtons.CreateVariants(variants));

            var choice = await chatIo.TryWaitInlineIntKeyboardInput();

            if (choice == null)
            {
                return(ExamResult.Retry);
            }

            if (variants[choice.Value] == word.Word)
            {
                await service.RegisterSuccess(word);

                return(ExamResult.Passed);
            }

            await chatIo.SendMessageAsync($"Origin was: \"{phrase.OriginPhrase}\"");

            await service.RegisterFailure(word);

            return(ExamResult.Failed);
        }
Beispiel #28
0
        public async Task <ExamResult> Pass(ChatIO chatIo, UsersWordsService service, UserWordModel word, UserWordModel[] examList)
        {
            var msg = $"=====>   {word.TranslationAsList}    <=====\r\n" +
                      $"Do you know the translation?";
            var _ = chatIo.SendMessageAsync(msg,
                                            new InlineKeyboardButton()
            {
                CallbackData = "1",
                Text         = "See the translation"
            });
            await chatIo.WaitInlineIntKeyboardInput();

            _ = chatIo.SendMessageAsync($"Translation is \r\n" +
                                        $"{word.Word}\r\n" +
                                        $" Did you guess?",

                                        new InlineKeyboardButton
            {
                CallbackData = "1",
                Text         = "Yes"
            },
                                        new InlineKeyboardButton {
                CallbackData = "0",
                Text         = "No"
            });

            var choice = await chatIo.WaitInlineIntKeyboardInput();

            if (choice == 1)
            {
                await service.RegisterSuccess(word);

                return(ExamResult.Passed);
            }
            else
            {
                await service.RegisterFailure(word);

                return(ExamResult.Failed);
            }
        }
Beispiel #29
0
        public async Task <ExamResult> Pass(ChatIO chatIo, UsersWordsService service, UserWordModel word,
                                            UserWordModel[] examList)
        {
            var translations = word.GetTranslations().ToArray();

            var minCount = translations.Min(t => t.Count(c => c == ' '));

            if (minCount > 0 && word.AbsoluteScore < minCount * 4)
            {
                return(ExamResult.Impossible);
            }

            await chatIo.SendMessageAsync($"=====>   {word.Word}    <=====\r\n" +
                                          $"Write the translation... ");

            var translation = await chatIo.WaitUserTextInputAsync();

            if (string.IsNullOrEmpty(translation))
            {
                return(ExamResult.Retry);
            }

            if (translations.Any(t => string.Compare(translation.Trim(), t, StringComparison.OrdinalIgnoreCase) == 0))
            {
                await service.RegisterSuccess(word);

                return(ExamResult.Passed);
            }

            var allMeaningsOfWord = await _dictionaryService.GetAllTranslationWords(word.Word);

            if (allMeaningsOfWord
                .Any(t => string.Compare(translation, t, StringComparison.OrdinalIgnoreCase) == 0))
            {
                await chatIo.SendMessageAsync(
                    $"Chosen translation is out of scope (but it is correct). Expected translations are: " +
                    word.TranslationAsList);

                return(ExamResult.Impossible);
            }

            await chatIo.SendMessageAsync("The translation was: " + word.TranslationAsList);

            await service.RegisterFailure(word);

            return(ExamResult.Failed);
        }
Beispiel #30
0
        public async Task <QuestionResult> Pass(ChatRoom chat, UserWordModel word,
                                                UserWordModel[] examList)
        {
            var translations = word.TextTranslations.ToArray();

            var minCount = translations.Min(t => t.Count(c => c == ' '));

            if (minCount > 0 && word.AbsoluteScore < minCount * WordLeaningGlobalSettings.FamiliarWordMinScore)
            {
                return(QuestionResult.Impossible);
            }


            await chat.SendMarkdownMessageAsync(QuestionMarkups.TranslateTemplate(word.Word, chat.Texts.WriteTheTranslationMarkdown));

            var entry = await chat.WaitUserTextInputAsync();

            if (string.IsNullOrEmpty(entry))
            {
                return(QuestionResult.RetryThisQuestion);
            }

            if (!entry.IsRussian())
            {
                await chat.SendMessageAsync(chat.Texts.RussianInputExpected);

                return(QuestionResult.RetryThisQuestion);
            }

            var(text, comparation) = translations.GetClosestTo(entry.Trim());

            switch (comparation)
            {
            case StringsCompareResult.Equal:
                return(QuestionResult.Passed(chat.Texts));

            case StringsCompareResult.SmallMistakes:
                await chat.SendMarkdownMessageAsync(chat.Texts.YouHaveATypoLetsTryAgainMarkdown(text));

                return(QuestionResult.RetryThisQuestion);

            case StringsCompareResult.BigMistakes:
                return(QuestionResult.Failed(chat.Texts.FailedMistakenMarkdown(text),
                                             chat.Texts));
            }
            var allMeaningsOfWord = await _localDictionaryService.GetAllTranslationWords(word.Word);

            var(otherMeaning, otherComparation) = allMeaningsOfWord.GetClosestTo(entry);
            if (otherComparation == StringsCompareResult.Equal)
            {
                await chat.SendMarkdownMessageAsync(
                    $"{chat.Texts.OutOfScopeTranslationMarkdown}: " +
                    $"*{word.AllTranslationsAsSingleString}*");

                return(QuestionResult.RetryThisQuestion);
            }
            if (otherComparation == StringsCompareResult.SmallMistakes)
            {
                await chat.SendMarkdownMessageAsync(
                    chat.Texts.OutOfScopeWithCandidateMarkdown(otherMeaning) + ": " +
                    "*\"" + word.AllTranslationsAsSingleString + "\"*");

                return(QuestionResult.RetryThisQuestion);
            }

            return(QuestionResult.Failed(
                       chat.Texts.FailedTranslationWasMarkdown + $"\r\n*\"{word.AllTranslationsAsSingleString}\"*",
                       chat.Texts));
        }