def answer_more_questions(): global status, additional_info if message.content_type == 'text' and utils.text_lower_wo_command( message) in ('да', 'нет'): if utils.text_lower_wo_command(message) == 'да': ask_question_desk() elif utils.text_lower_wo_command(message) == 'нет': finish() else: ask_more_questions()
def add_quest_flow(bot_in, message_in): """Основной поток маршрутизации для квестовой части бота. @Можно добавить в словарь проверку на типы ответа. Или вынести в функции Принимает объекты bot, message Если это первый вызов, то выдаст список квестов, """ status_dic = { 'need_quest_name': take_quest_name, 'need_quest_desc': take_quest_desc, 'need_quest_photo': take_quest_photo, 'need_question_desc': take_question_desc, 'need_question_photo': take_question_photo, 'need_question_type': take_question_type, 'need_question_answer': ask_take_question_answer, 'need_more_questions': answer_more_questions, } global operation, status, additional_info, bot, message bot = bot_in message = message_in (operation, status, additional_info) = db_connector.get_user_operation(message.from_user.id) if additional_info: additional_info = json.loads(additional_info) else: additional_info = dict() if not operation or operation != opAddQest: ask_quest_name() elif utils.text_lower_wo_command(message) in ('cancel', 'отмена'): cancel_adding() else: status_dic[status]()
def quest_flow(bot_in, message_in): """Основной поток маршрутизации для квестовой части бота. @Можно добавить в словарь проверку на типы ответа. Или вынести в функции Принимает объекты bot, message Если это первый вызов, то выдаст список квестов, """ status_dic = { 'neead_quest_choice': give_quest, 'need_question': give_question, 'need_answer': check_answer, } global operation, status, additional_info, bot, message bot = bot_in message = message_in (operation, status, additional_info) = db_connector.get_user_operation(message.from_user.id) if additional_info: additional_info = json.loads(additional_info) else: additional_info = dict() if not operation or operation != opDoQest: show_quest_list() elif utils.text_lower_wo_command(message) in ('cancel', 'отмена'): cancel_quest() else: status_dic[status]()
def route_flow(bot_in, message_in, session_in): """Основной поток маршрутизации. """ global bot, message, session, user, group flow_list = [ 'ask_name', 'ask_password', 'ask_date', 'done', ] status_dic = { 'ask_name': ask_name, 'ask_password': ask_password, 'ask_date': ask_date, 'done': finish } bot = bot_in message = message_in session = session_in user = session.query(User).filter_by( telegramid=message.from_user.id).first() user.operation.decode_additional() if not user.operation.current_operation or user.operation.current_operation != opGroup: user.operation.current_operation = opGroup user.operation.additional_info = {} current_step = 0 else: if user.operation.operation_status in flow_list: current_step = flow_list.index(user.operation.operation_status) else: current_step = 0 group = user.operation.additional_info.get('group_id') if group: group = session.query(Group).filter(Group.id == group, Group.owner == user).first() if not group: group = Group(owner=user) session.add(group) user.operation.code_additional() session.commit() user.operation.decode_additional( ) # @Разобраться. Без этого после отмены в additional итогда что-то левое после commit образуется user.operation.additional_info['group_id'] = group.id current_step = 0 if utils.text_lower_wo_command(message) in standard.cancel_commands: cancel_all() user.operation.code_additional() return user.operation.operation_status = flow_list[current_step] while status_dic[flow_list[current_step]](): current_step += 1 user.operation.operation_status = flow_list[current_step] user.operation.code_additional()
def route_flow(bot_in, message_in, session_in): """Основной поток маршрутизации. """ global bot, message, session, user, group flow_list = [ 'find_group', 'ask_password', 'ask_suggestion', 'done', ] status_dic = { 'find_group': find_group, 'ask_password': ask_password, 'ask_suggestion': ask_suggestion, 'done': finish, } bot = bot_in message = message_in session = session_in user = session.query(User).filter_by(telegramid=message.from_user.id).first() user.operation.decode_additional() if not user.operation.current_operation or user.operation.current_operation != opGroup: user.operation.current_operation = opGroup user.operation.additional_info = {} current_step = 0 else: if user.operation.operation_status in flow_list: current_step = flow_list.index(user.operation.operation_status) else: current_step = 0 group = user.operation.additional_info.get('group_id') if group: group = session.query(Group).filter(Group.id == group).first() if not group: current_step = 0 if utils.text_lower_wo_command(message) in standard.cancel_commands: cancel_all() user.operation.code_additional() return user.operation.operation_status = flow_list[current_step] while status_dic[flow_list[current_step]](): current_step += 1 user.operation.operation_status = flow_list[current_step] user.operation.code_additional()
def take_question_photo(): global status, additional_info if not (message.content_type in ['photo', ] \ or ( message.content_type == 'text' and utils.text_lower_wo_command(message) in ('skip', 'пропустить'))): bot.send_message( message.chat.id, 'Приложите фото к заданию или нажмите /skip - задание без фото.', reply_markup=types.ReplyKeyboardHide()) return file_id = None if message.content_type == 'photo': file_id = message.photo[-1].file_id additional_info['question_photo_id'] = file_id put_operations() ask_question_type()
def routing(message): session = DBSession() try: user = session.query(User).filter_by( telegramid=message.from_user.id).first() if not user: user = User(telegramid=message.from_user.id) session.add(user) user.operation = Operation() session.commit() if user.operation is None: user.operation = Operation() session.commit() db_connector.save_to_log( from_who='user', message=message) # Сохранение входящего сообщения в БД. text = utils.text_lower_wo_command(message) if not user.active: bot.send_message(message.chat.id, 'Вы заблокированы.') elif text in ('start', 'help'): handle_start_help(message, session, user) elif not user.registrationDone or user.operation.current_operation == opRegister: register_flow(bot, message, session) elif text in admin_functions.admin_commands: #Для правильной работы необходим заполненный admin_id в config admin_functions.admin_flow(bot, message, session) elif text in standard.create_group or user.operation.current_operation == create_group.opGroup: create_group.route_flow(bot, message, session) elif text in standard.find_group or user.operation.current_operation == join_group.opGroup: join_group.route_flow(bot, message, session) else: not_found(message) session.commit() except Exception as e: session.rollback() raise e finally: session.close()
def take_quest_photo(): global status, additional_info if not (message.content_type in ['photo', ] \ or (message.content_type == 'text' and utils.text_lower_wo_command(message) in ('skip', 'пропустить'))): bot.send_message( message.chat.id, 'Приложите фото квеста или нажмите /skip - квест без фото.', reply_markup=types.ReplyKeyboardHide()) return file_id = None if message.content_type == 'photo': file_id = message.photo[-1].file_id #additional_info['photo_id'] = file_id name = additional_info.pop('quest_name', None) desc = additional_info.pop('quest_desc', None) quest_id = db_connector.add_new_quest(name=name, user_id=message.from_user.id, description=desc, photo_id=file_id) additional_info['quest_id'] = quest_id put_operations() ask_question_desk()
def ask_take_question_answer(): global status, additional_info quest_type = additional_info.get('quest_type') step = additional_info.get('answer_step') def ask_text(): additional_info['answer_step'] = 'take_text' put_operations() bot.send_message(message.chat.id, 'Введите текст правильного ответа', reply_markup=types.ReplyKeyboardHide()) def ask_digit(): additional_info['answer_step'] = 'take_dig' put_operations() bot.send_message(message.chat.id, 'Введите правльный ответ (число)', reply_markup=types.ReplyKeyboardHide()) def ask_coords(): additional_info['answer_step'] = 'take_gps' put_operations() markup = types.ReplyKeyboardMarkup(resize_keyboard=True, one_time_keyboard=True) markup.add( types.KeyboardButton( text=r'Отправить текущее местоположениею. Я тут.', request_location=True)) bot.send_message( message.chat.id, 'Пришлите геолокацию правильного ответа. Либо точкой на карте, либо 2 числа через проел координаты широта, долгота в формате как в примере 55.809913 37.462587', reply_markup=markup) def ask_geo_help(): additional_info['answer_step'] = 'take_geo_help' put_operations() markup = types.ReplyKeyboardMarkup(resize_keyboard=True, one_time_keyboard=True) markup.row('Да') markup.row('Нет') bot.send_message( message.chat.id, 'При неверном ответе показывать расстояние до цели? Выберите ответ кнопкой.', reply_markup=markup) def save_question(): additional_info.pop('answer_step', None) quest_id = additional_info.get('quest_id') description = additional_info.pop('question_desc', None) photo = additional_info.pop('question_photo_id', None) answer_type = additional_info.pop('quest_type', None) correct_answer = additional_info.pop('answer', None) db_connector.add_new_question(quest_id, description, photo, answer_type, correct_answer) ask_more_questions() error_flag = False if step == 'start': if quest_type == 'text': ask_text() elif quest_type == 'dig': ask_digit() elif quest_type == 'geo': ask_coords() elif step in ('take_text', 'take_dig'): if message.content_type != 'text': error_flag = True else: additional_info['answer'] = message.text.lower() save_question() elif step == 'take_gps': if message.content_type == 'location': additional_info['lat'] = message.location.latitude additional_info['long'] = message.location.longitude ask_geo_help() elif message.content_type == 'text': coords = message.text.split() if len(coords) == 2 and coords[0].replace( '.', '', 1).isdigit() and coords[1].replace('.', '', 1).isdigit(): additional_info['lat'] = float(coords[0]) additional_info['long'] = float(coords[1]) ask_geo_help() else: error_flag = True else: error_flag = True elif step == 'take_geo_help': if message.content_type == 'text' and utils.text_lower_wo_command( message) in ('да', 'нет'): answer = {} answer['lat'] = additional_info.pop('lat', 0) answer['long'] = additional_info.pop('long', 0) answer['accur'] = 50 answer['hint_meters'] = utils.text_lower_wo_command( message) == 'да' additional_info['answer'] = json.dumps(answer) save_question() else: ask_geo_help() if error_flag: additional_info['answer_step'] = 'start' put_operations() bot.send_message(message.chat.id, 'Неверный формат.', reply_markup=types.ReplyKeyboardHide()) ask_take_question_answer()
"""Функции админской "панели управления". Детали смотри в admin_functions.py Для правильной работы необходим заполненный admin_id в config По умолчанию менть не надо. """ db_connector.save_to_log('user', message) admin_functions.admin_flow(bot, message) @bot.message_handler(content_types=['text', 'photo', 'document', 'location'], func=lambda message: db_connector.get_user_operation( message.from_user.id)[0] in (do_quest.opDoQest, )) @bot.message_handler( content_types=['text'], func=lambda message: utils.text_lower_wo_command(message) in (standard.start_quest_command.lower(), )) def handle_do_quest(message): #Тут перенаправление на корневую функцию файла do_quest.py db_connector.save_to_log('user', message) do_quest.quest_flow(bot, message) @bot.message_handler(content_types=['text'], func=lambda message: utils.text_lower_wo_command(message) in standard.add_quest_command) @bot.message_handler(content_types=['text', 'photo', 'document', 'location'], func=lambda message: db_connector.get_user_operation( message.from_user.id)[0] in (add_quest.opAddQest, )) def handle_add_quest(message): #Тут перенаправление на корневую функцию файла add_quest.py