Beispiel #1
0
    def __preview(self, update, context):
        metadata = self.__get_chat_meta(update, context)
        if metadata['action']:
            if len(metadata['puzzle_buffer'][-1]) > 0:
                if metadata['name']:
                    update.effective_message.reply_text(
                        text="Name: " + " ".join(metadata['name'].split('_')))

                ReadWrite.send(metadata['puzzle_buffer'][-1], context.bot,
                               update.effective_message.chat_id)

            else:
                update.effective_message.reply_text(text="Nothing in buffer")
            if metadata['action'] == 'answer' or metadata['action'] is None:
                answs = "Answers: "
                sep_a = ''
                guess = "Guess: "
                sep_g = ''
                hint = "Hint: "
                sep_h = ''
                for answ in metadata['answer_buffer'][-1]:
                    if answ.startswith('?') and len(answ[1:].split('?')) == 2:
                        temp = answ[1:].split('?')
                        guess += sep_g + temp[0] + ' "' + temp[1] + '"'
                        sep_g = ', '
                    elif answ.startswith("<") and answ.endswith(">"):
                        hint += sep_h + answ[1:-1]
                        sep_h = ', '
                    else:
                        answs += sep_a + answ
                        sep_a = ', '
                update.effective_message.reply_text(text=answs + "\n" + guess +
                                                    "\n" + hint)
        else:
            update.effective_message.reply_text(text="Nothing in buffer")
 def __get_question(self):
     levels = self.__list_levels()
     self.puzzle_dir = os.path.join(self.working_dir,
                                    levels[self._last_question_num])
     self.question = ReadWrite.read_from_file(
         os.path.join(self.puzzle_dir, 'question.pickle'))
     pre_answer = ReadWrite.read_from_file(
         os.path.join(self.puzzle_dir, 'answer.pickle'))
     self.answer.clear()
     self.hint.clear()
     self.guess.clear()
     for answ in pre_answer:
         if answ.startswith('?') and len(answ[1:].split('?')) == 2:
             temp = answ[1:].split('?')
             self.guess.append([
                 temp[0].strip().lower().replace('ё', 'е'), temp[1].strip()
             ])
         elif answ.startswith("<") and answ.endswith(">"):
             self.hint.append(answ[1:-1].lower().strip())
         else:
             self.answer.append(answ.lower().strip().replace('ё', 'е'))
     if not len(self.answer):
         self.answer.append("")
     if not len(self.hint):
         self.hint.append("")
     if not len(self.guess):
         self.guess.append(["", ""])
Beispiel #3
0
    def __settings_game_button(self, update, context):
        query = update.callback_query
        metadata = self.__check_meta(self.__get_chat_meta(update, context),
                                     update)
        chat_id = update.effective_message.chat_id
        if not metadata:
            return
        button = query.data.split('-')[-1]
        if button in metadata['quiz'].keys():
            metadata['game_type'] = button
            old_data = self.__get_game_meta(
                metadata['quiz'][metadata['game_type']])
            metadata['quiz'][metadata['game_type']] = QuizKernel(*old_data)
        else:
            metadata['game_type'] = button
            path_dir = os.path.join(self.config.games_db_path,
                                    metadata['game_type'], 'master')
            metadata['quiz'][metadata['game_type']] = QuizKernel(
                path_dir, 0, context.bot, update.effective_message.chat_id)
        self.logger.info('User %s set new game type %s', update.effective_user,
                         metadata['game_type'])
        question, path = metadata['quiz'][
            metadata['game_type']].get_new_question()
        metadata['message_stack'] += ReadWrite.send(question, context.bot,
                                                    chat_id, path)

        query.answer(text='Теперь играем в ' + button)
        update.effective_message.delete()
Beispiel #4
0
 def __data_getter(self, update, context):
     metadata = self.__get_chat_meta(update, context)
     if not update.message:
         update.effective_message.reply_text(
             text=
             "Editing is not allowed in puzzle writer. Please use /dellastupd "
             "to change previous sentence.")
         return
     if metadata['action'] == 'question':
         ReadWrite.push_puzzle(update.message,
                               metadata['puzzle_buffer'][-1])
     elif metadata['action'] == 'answer':
         if update.message.text:
             ReadWrite.push_answer(update.message,
                                   metadata['answer_buffer'][-1])
         else:
             update.message.reply_text(
                 text="In current version answer can be only a text")
Beispiel #5
0
    def __answer(self, update, context):
        metadata = self.__check_meta(self.__get_chat_meta(update, context),
                                     update)
        if not metadata:
            return

        chat_id = update.effective_message.chat_id
        metadata['message_stack'].append(update.effective_message)

        if update.effective_message.text.startswith('/'):
            answer = ' '.join(context.args).lower()
        else:
            answer = update.effective_message.text
            if not metadata['answer_from_text']:
                return
        if not answer:
            metadata['message_stack'].append(
                update.effective_message.reply_text(
                    text=
                    "Укажи ответ аргументом после команды /answer, например: "
                    "/answer 1984.\nЛайфхак: чтобы каждый раз не печатать слово "
                    "answer, можно воспользоваться комбинацией /+tab ответ"))
            return

        self.logger.info(
            'User %s answered %s in game %s on question %s',
            update.effective_user, answer, metadata['game_type'],
            metadata['quiz'][metadata['game_type']].last_question_num)
        correctness = metadata['quiz'][metadata['game_type']].check_answer(
            answer)
        if correctness == AnswerCorrectness.CORRECT:
            self.logger.info(
                'User %s solved puzzle %s from %s', update.effective_user,
                metadata['quiz'][metadata['game_type']].last_question_num,
                metadata['game_type'])
            if metadata['no_spoiler']:
                for msg in metadata['message_stack']:
                    try:
                        context.bot.deleteMessage(msg.chat_id, msg.message_id)
                    except:
                        self.logger.warning('No message "%s"', msg)
            metadata['message_stack'].clear()

            metadata['quiz'][metadata['game_type']].next()
            question, path = metadata['quiz'][
                metadata['game_type']].get_new_question()
            metadata['message_stack'] += ReadWrite.send(
                question, context.bot, chat_id, path)

        elif type(correctness) == str:
            metadata['message_stack'].append(
                update.effective_message.reply_text(text=correctness))
            # context.bot.sendMessage(chat_id=chat_id, text=correctness))
        else:
            self.logger.warning('Wrong answer type "%s"', correctness)
Beispiel #6
0
 def __settings_game(self, update, context):
     query = update.callback_query
     metadata = self.__check_meta(self.__get_chat_meta(update, context),
                                  update)
     if not metadata:
         return
     reply_markup = ReadWrite.parse_game_folders_markup(
         self.config.games_db_path)
     query.edit_message_text(text=self.__settings_game_text(
         metadata['game_type']),
                             reply_markup=reply_markup)
Beispiel #7
0
 def __set_game(self, update, context):
     metadata = self.__check_meta(self.__get_chat_meta(update, context),
                                  update)
     chat_id = update.effective_message.chat_id
     if not metadata:
         return
     reply_markup = ReadWrite.parse_game_folders_markup(
         self.config.games_db_path)
     context.bot.sendMessage(text=self.__settings_game_text(
         metadata['game_type'], False),
                             chat_id=chat_id,
                             reply_markup=reply_markup)
Beispiel #8
0
    def __question(self, update, context):
        metadata = self.__check_meta(self.__get_chat_meta(update, context),
                                     update)
        if not metadata:
            return
        chat_id = update.effective_message.chat_id
        metadata['message_stack'].append(update.effective_message)
        question, path = metadata['quiz'][
            metadata['game_type']].get_new_question()

        metadata['message_stack'] += ReadWrite.send(question, context.bot,
                                                    chat_id, path)
Beispiel #9
0
 def __repeat_goth(self, update, context):
     chat_id = update.effective_message.chat_id
     keyboard = [[
         InlineKeyboardButton("Посмотреть ответ",
                              callback_data='gotd_answ'),
         InlineKeyboardButton("Скрыть", callback_data='done')
     ]]
     reply_markup = InlineKeyboardMarkup(keyboard)
     question, path = self.game_of_day.get_new_question()
     self.gotd_prev_message += ReadWrite.send(question,
                                              self.updater.bot,
                                              chat_id,
                                              path,
                                              reply_markup=reply_markup,
                                              game_of_day=True)
Beispiel #10
0
    def __start(self, update, context):
        metadata = self.__get_chat_meta(update, context)
        chat_id = update.effective_message.chat_id

        if not metadata:
            metadata['game_type'] = self.config.default_game
            metadata['quiz'] = defaultdict(QuizKernel)
            path_dir = os.path.join(self.config.games_db_path,
                                    metadata['game_type'], 'master')
            metadata['quiz'][metadata['game_type']] = QuizKernel(
                path_dir, last_question=0)
            metadata['quiz_data'] = (path_dir, 0)
            metadata['no_spoiler'] = self.config.no_spoilers_default \
                if update.effective_message.chat.type != 'private' else False
            metadata['message_stack'] = []
            metadata['game_of_day'] = True
            metadata['answer_from_text'] = True
            metadata['version'] = self.__version__
            reply_text = (
                "	Привет! Добро пожаловать в игру!\n"
                "\n"
                '/answer [ans] - Дать ответ на вопрос (/+tab ответ)\n'
                '/hint - Вызвать подсказку\n'
                '/repeat - Повторить последний вопрос\n'
                '/getanswer - Получить ответ\n'
                '/setlevel - Выбрать уровень\n'
                '/settings - Настройки игры (режим и no spoilers)\n'
                '/start - Начать игру\n'
                '/help - Вызвать подробную инструкцию\n'
                '/credits - Авторам\n'
                '/reset - Сброс прогресса игры \n'
                "\n"
                "	Удачи!\n")

            metadata['message_stack'].append(
                context.bot.sendMessage(chat_id=chat_id, text=reply_text))
            self.__set_game(update, context)
            self.logger.info('New user added %s', update.effective_user)
        else:
            # этот странный трюк нужен в случае, если мы что-то обновили в игровом движке
            old_data = self.__get_game_meta(
                metadata['quiz'][metadata['game_type']])
            metadata['quiz'][metadata['game_type']] = QuizKernel(*old_data)

            question, path = metadata['quiz'][
                metadata['game_type']].get_new_question()
            metadata['message_stack'] += ReadWrite.send(
                question, context.bot, chat_id, path)
Beispiel #11
0
 def __levels_button(self, update, context):
     query = update.callback_query
     metadata = self.__check_meta(self.__get_chat_meta(update, context),
                                  update)
     chat_id = update.effective_message.chat_id
     if not metadata:
         return
     button = '-'.join(query.data.split('-')[1:])
     metadata['quiz'][metadata['game_type']].set_level_by_name(button)
     question, path = metadata['quiz'][
         metadata['game_type']].get_new_question()
     metadata['message_stack'] += ReadWrite.send(question, context.bot,
                                                 chat_id, path)
     update.effective_message.delete()
     self.logger.info('User %s changed level to %s', update.effective_user,
                      button)
Beispiel #12
0
 def __reset_button(self, update, context):
     query = update.callback_query
     metadata = self.__check_meta(self.__get_chat_meta(update, context),
                                  update)
     chat_id = update.effective_message.chat_id
     if not metadata:
         return
     button = bool(int(query.data.split('-')[-1]))
     if bool(button):
         update.effective_message.delete()
         metadata['quiz'][metadata['game_type']].reset()
         question, path = metadata['quiz'][
             metadata['game_type']].get_new_question()
         metadata['message_stack'] += ReadWrite.send(
             question, context.bot, chat_id, path)
         self.logger.info('User %s reset %s', update.effective_user,
                          metadata['game_type'])
     else:
         update.effective_message.delete()
Beispiel #13
0
 def __end(self, update, context):
     metadata = self.__get_chat_meta(update, context)
     if metadata['action'] != 'answer' or len(
             metadata['answer_buffer'][-1]) < 1:
         update.effective_message.reply_text(
             text=
             "Please specify answer first /setanswer or start new question /new"
         )
         return
     metadata['action'] = None
     update.effective_message.reply_text(text='Thanx!')
     filename = ReadWrite.save_to_file(metadata['puzzle_buffer'][-1],
                                       metadata['answer_buffer'][-1],
                                       update.effective_message.from_user,
                                       metadata,
                                       puzzle_dir=self.config.working_path,
                                       bot=context.bot,
                                       save_media=self.config.save_media)
     self.logger.info('New puzzle saved from %s, filename %s',
                      update.effective_user, filename)
Beispiel #14
0
    def __game_of_the_day_send(self):
        if self.gotd_prev_message:
            self.game_of_day.next()
            for message in self.gotd_prev_message:
                try:
                    # self.updater.bot.edit_message_text(text=message.text,
                    #                                   chat_id=message.chat_id,
                    #                                   message_id=message.message_id)
                    self.updater.bot.delete_message(message.chat_id,
                                                    message.message_id)
                except:
                    self.logger.warning('No message "%s"', message)
            self.gotd_prev_message.clear()

        keyboard = [[
            InlineKeyboardButton("Посмотреть ответ",
                                 callback_data='gotd_answ'),
            InlineKeyboardButton("Скрыть", callback_data='done')
        ]]
        reply_markup = InlineKeyboardMarkup(keyboard)
        if self.game_of_day:
            question, path = self.game_of_day.get_new_question()
        else:
            return
        user_data = self.updater.dispatcher.user_data
        for user in list(user_data):
            if user_data[user]:
                if 'game_of_day' not in user_data[user]:
                    user_data[user]['game_of_day'] = True
                if user_data[user]['game_of_day']:
                    try:
                        self.gotd_prev_message += ReadWrite.send(
                            question,
                            self.updater.bot,
                            user,
                            path,
                            reply_markup=reply_markup,
                            game_of_day=True)
                    except Unauthorized as ua:
                        del user_data[user]
                        self.logger.warning("User %s is deleted", user)

        chat_data = self.updater.dispatcher.chat_data
        for chat in list(chat_data):
            if chat_data[chat]:
                if 'game_of_day' not in chat_data[chat]:
                    chat_data[chat]['game_of_day'] = True
                if chat_data[chat]['game_of_day']:
                    try:
                        self.gotd_prev_message += ReadWrite.send(
                            question,
                            self.updater.bot,
                            chat,
                            path,
                            reply_markup=reply_markup,
                            game_of_day=True)
                    except Unauthorized as ua:
                        del chat_data[chat]
                        self.logger.warning("Chat %s is deleted", chat)
                    except ChatMigrated as e:
                        chat_data[e.new_chat_id] = deepcopy(chat_data[chat])
                        del chat_data[chat]
                        self.logger.warning("Chat %s is migrated", chat)
                        self.gotd_prev_message += ReadWrite.send(
                            question,
                            self.updater.bot,
                            e.new_chat_id,
                            path,
                            reply_markup=reply_markup,
                            game_of_day=True)
        pickle.dump(
            [self.game_of_day.last_question_num, self.gotd_prev_message],
            open(self.config.game_of_the_day_db_path, 'wb'))
        self.logger.info('Game of the day send')
Beispiel #15
0
 def __set_game_folder(self, update, context):
     update.effective_message.reply_text(
         text='Choose game',
         reply_markup=ReadWrite.parse_game_folders_markup(
             self.config.working_path, True))