Exemplo n.º 1
0
    def check_memorized(self, chat_id, correct_answer=None):
        next_word, next_word_translate = Api().get_next_word(chat_id)
        if next_word is None:  # завершение обучения
            LangBotApi.add_rating(chat_id, 5)
            text = "Изучение слов завершенно, получи 5 ❤\n\n"
            text += """🔹Теперь эти слова ты можешь изучать в *Интервальном повторении*, для того чтобы быстрее их запомнить

🔹Ты можешь учить неограниченное количество слов в разделе *Изучать слова*, по 10/20/50 в день! 
"""
            keyboard = types.InlineKeyboardMarkup()
        else:
            randoms_words = Api().get_random_words(chat_id)
            keyboard = types.InlineKeyboardMarkup()
            buttons = [
                types.InlineKeyboardButton(text=next_word_translate,
                                           callback_data="good " + next_word)
            ]
            for word in list(randoms_words):
                buttons.append(
                    types.InlineKeyboardButton(text=word, callback_data="bad"))
            random.shuffle(buttons)
            for bt in buttons:
                keyboard.add(bt)
            text = ""
            if correct_answer is not None:
                text += "**Неверно!**\nПравильный ответ:\n"
                text += correct_answer[0] + " - " + correct_answer[1] + "**\n\n"
                text += "возможно нужна кнопка подробной информации"
            text += "*Выбери правильный перевод*\n\n"
            text += f"*{next_word}*"

        return {"keyboard": keyboard, "text": text}
Exemplo n.º 2
0
    def start_game(ref_id, user_id):
        global game_data, invites

        if ref_id in invites:
            topic = invites[ref_id]
            del invites[ref_id]
            data = LangBotApi.get_words_for_game(topic)
            words = list(data)
            random.shuffle(words)

            ref_user = LangBotApi.get_user(ref_id)
            user_user = LangBotApi.get_user(user_id)
            try:
                if not (ref_user and user_user):
                    print("WTF\n" * 10)
                    print(ref_user, user_user)
                    print(topic)
                    print(ref_id, user_id)
            except Exception as e:
                print(e)
            game_data[ref_id] = [
                words, data, {
                    ref_id: [-1, 0, ref_user],
                    user_id: [-1, 0, user_user]
                },
                datetime.now(), None
            ]

            game_data[user_id] = game_data[ref_id]
            return topic
Exemplo n.º 3
0
 def get_word_to_repeat(self, user_id):
     word = LangBotApi.get_word_to_repeat(user_id)
     if isinstance(word, dict):
         self.users_word_to_repeat[user_id] = word
         text = '_(↘️ Нажми Показать перевод, чтобы проверить себя)_'
         text += "\n\nПомнишь слово *" + word.get('word') + "* ?"
         keyboard = self.open_card_keyboard()
         return text, keyboard
     else:
         rating = self.users_rating.get(user_id)
         if rating:
             LangBotApi.add_rating(user_id, rating)
             self.users_rating.pop(user_id, None)
             return f"Сегодня больше нет слов для повторения получи {rating} ❤", learn_markup
         else:
             return "Сегодня больше нет слов для повторения.", learn_markup
Exemplo n.º 4
0
 def get_topics(self, user_id=None):
     data = LangBotApi.get_topics()
     topics_b = []
     for topic in data[:50]:
         print(topic)
         if user_id is None:
             text = 'Выбрана тема: ' + topic['name']
             keyboard = None
         else:
             text = 'Вас пригласили на битву!\nТема: ' + topic['name']
             keyboard = types.InlineKeyboardMarkup()
             keyboard.add(
                 types.InlineKeyboardButton(text="принять участвие в игре",
                                            url=get_tg_link('g' +
                                                            str(user_id))))
         if topic['image'] and ("http://5.187.6.15" in topic['image']):
             topic['image'] = topic['image'].replace(
                 "http://5.187.6.15", "https://botenglish.ru")
         topics_b.append(
             types.InlineQueryResultArticle(
                 topic['id'],
                 title=topic['name'],
                 # description='Вами выучено 0 из 54',
                 thumb_url=topic['image'],
                 input_message_content=types.InputTextMessageContent(text),
                 reply_markup=keyboard))
     return topics_b
Exemplo n.º 5
0
 def get_user_dict(self, user_id, page=1):
     data = LangBotApi.get_user_dict(user_id, page=page)
     text = ""
     for item in data["words"]:
         word = f"*{item}*"
         tr = data["words"][item]["translate"].get("tr",
                                                   ["нет перевода"])[0]
         text += f"\n{word} - {tr}"
     return text, self.pages_keyboard(page, data["pages"])
Exemplo n.º 6
0
 def get_progress(self, chat_id):
     print("users count ", len(self.users_stat))
     data = LangBotApi.get_progress(chat_id)
     print(data)
     text = "\n*Рейтинг:* " + str(data["rating"]) + " ❤"
     text += "\n*Словарный запас:* " + str(data["count_words"])
     text += "\n*Сегодня изучено:* " + str(data["count_words_today"])
     text += "\n*Новых слов за неделю:* " + str(data["count_words_week"])
     text += "\n*Непрерывная серия:* " + str(data["lifelong_learning"])
     return text
Exemplo n.º 7
0
 def is_allowed_today(self, chat_id):
     global end_dates
     present_day = datetime.now()
     if True or chat_id not in end_dates or end_dates[chat_id] < present_day:
         end_dates[chat_id] = LangBotApi.get_allowed_date(chat_id)
     if type(end_dates[chat_id]) is bool:
         print(chat_id, "is_allowed_today(self, chat_id): is bool")
         return True
     end_day = end_dates[chat_id]
     return end_day.date() >= present_day.date()
Exemplo n.º 8
0
    def start_new_test(self, chat_id):
        global users_words_dict, for_test, test_score, current_word

        data = LangBotApi.get_words_for_test(chat_id)
        if data:
            users_words_dict.update(data)
            for_test[chat_id] = list(data)
            test_score[chat_id] = [0, len(data)]
            current_word[chat_id] = None
            return data
Exemplo n.º 9
0
    def get_new_words(self, chat_id, topic_id=None):
        global for_memorized
        global users_words_dict
        global poor_learned_words_count
        if self.is_allowed_today(chat_id):
            data = LangBotApi.get_words_for_learn(chat_id, topic_id)
            poor_learned_words_count[chat_id] = 0
        else:
            if chat_id not in poor_learned_words_count:
                poor_learned_words_count[chat_id] = 0
            if poor_learned_words_count[chat_id] >= 5:
                return False
            n_words = poor_learned_words_count[chat_id]
            print(n_words)

            data = LangBotApi.get_words_for_learn(chat_id, topic_id)
            data = {i: data[i] for i in list(data.keys())[:5 - n_words]}
        users_words_dict.update(data)
        for_memorized[chat_id] = list(data)
        return data
Exemplo n.º 10
0
    def test_question_data(self, chat_id):
        next_word, next_word_translate, count = Api().get_next_test_word(
            chat_id)
        if next_word is None:  # завершение обучения
            goal = 80
            score = Api().get_test_score(chat_id)
            percent = int((score[0] / score[1]) * 100)
            if percent > goal:
                LangBotApi.add_rating(chat_id, 20)
                text = "Поздравляю! Тест завершен.\nВы получили новый уровень: *" + \
                       levels_str[Api().get_next_level(chat_id)] + "* и 20 ❤"
                Api().set_next_level(chat_id)
            else:
                text = "Тест завершен.\n"
                text += "К сожалению, вы не прошли тест.\nДо уровня " + levels_str[
                    Api().get_next_level(chat_id)] + "\n"
                text += "Вам не хватило " + str(goal - percent + 1) + "%"
            text += "\nВы набрали " + str(percent) + "% (" + str(
                score[0]) + " из " + str(score[1]) + ")."
            keyboard = types.InlineKeyboardMarkup()
        else:
            # randoms_words = Api().get_random_test_words(chat_id)
            randoms_words = Api().get_random_words(chat_id)
            keyboard = types.InlineKeyboardMarkup()
            buttons = [
                types.InlineKeyboardButton(text=next_word_translate,
                                           callback_data="good " + next_word)
            ]
            for word in list(randoms_words):
                buttons.append(
                    types.InlineKeyboardButton(text=word, callback_data="bad"))
            random.shuffle(buttons)
            for bt in buttons:
                keyboard.add(bt)
            text = ""
            text += f"_Осталось {count} вопросов_\n\n"
            text += "**Выбери правильный перевод**\n\n"
            text += f"*{next_word}*"

        return {"keyboard": keyboard, "text": text}
Exemplo n.º 11
0
 def next_word(self, user_id, mem_status):
     if mem_status in ("good" or "not_good"):
         self.users_rating[user_id] = self.users_rating.get(user_id, 0) + 1
     prev_word_id = self.users_word_to_repeat.get(user_id, dict()).get("id")
     LangBotApi.change_repeat_word_status(user_id, prev_word_id, mem_status)
     return self.get_word_to_repeat(user_id)
Exemplo n.º 12
0
 def edit_notify(self, user, time):
     print("Уведолмения установлены")
     LangBotApi.send_time_notify(user, time)
Exemplo n.º 13
0
    def get_word_keys_data(self, chat_id, word_number, more=False):
        words_list, words_dict = Api().get_list_words(chat_id)
        n_words = len(words_list)
        word_number = int(word_number)
        prev_n = word_number - 1 if word_number else word_number
        next_n = word_number + 1 if word_number + 1 < n_words else word_number

        keyboard = types.InlineKeyboardMarkup()
        buttons = [
            types.InlineKeyboardButton(text="⬅️",
                                       callback_data="goto " + str(prev_n))
        ]
        buttons += [
            types.InlineKeyboardButton(text=str(word_number + 1) + "/" +
                                       str(n_words),
                                       callback_data="start_quiz")
        ]
        buttons += [
            types.InlineKeyboardButton(text="➡️",
                                       callback_data="goto " + str(next_n))
        ]
        buttons += [
            types.InlineKeyboardButton(text="Подробнее",
                                       callback_data="more " +
                                       str(word_number))
        ]
        buttons += [
            types.InlineKeyboardButton(text="Перейти к тесту",
                                       callback_data="start_quiz")
        ]
        keyboard.add(*buttons[:3])
        keyboard.add(buttons[3])
        if word_number + 1 == n_words:
            keyboard.add(buttons[4])

        word = words_list[word_number]

        pos = words_dict[word].get("pos", "")
        level = words_dict[word].get("level", "")

        ts = words_dict[word]["translate"]
        audio = words_dict[word].get("audio", "")
        audio = LangBotApi.get_word_audio_by_path(audio)
        transcription = ts.get("ts")
        meanings = ts.get("tr")
        examples = ts.get("ex", list())
        synonyms = ts.get("syn", list())
        # Транскрипция: [kɒnstɪˈtjuːʃn]
        # Существительное
        text = f"*{word}*"
        if transcription:
            text += "\nТранскрипция: [" + transcription + "]"
        text += "\n" + pos_dict.get(pos, pos)
        if level and False:
            text += " topic: " + level
        text += "\n"
        for mng in meanings:
            text += "\n· " + mng
            if more:  # обычно ложь, может когда-то заработает
                try:
                    if mng in synonyms and synonyms[mng]:
                        text += "\n  " + "synonyms:\n" + ",".join(
                            synonyms[mng])
                    if mng in examples and examples[mng]:
                        text += "\n  " + "examples:"
                        for exmpl in examples[mng]:
                            text += "\n·" + exmpl["text"]
                            for ex_tr in exmpl["tr"]:
                                text += " - " + ex_tr["text"]

                except Exception as e:
                    print(e)
                    text += "\n error \n"
        if more:
            text += ""
        data = {"text": text, "audio": audio, "keyboard": keyboard}

        return data
Exemplo n.º 14
0
 def get_allowed_days_date(self, chat_id):
     global end_date
     present_day = datetime.now()
     end_dates[chat_id] = LangBotApi.get_allowed_date(chat_id)
     end_day = end_dates[chat_id]
     return (end_day - present_day).days + 1, end_day
Exemplo n.º 15
0
 def set_next_level(self, chat_id):
     if self.get_next_level(chat_id) is not None:
         LangBotApi.set_user_level(chat_id, self.get_next_level(chat_id))
Exemplo n.º 16
0
 def get_current_level(self, chat_id):
     level = LangBotApi.get_user_level(chat_id)
     if bool(level) is False:
         level = "начальный"
     return level