Exemple #1
0
async def process_region(message: types.Message, state: FSMContext):
	async with state.proxy() as data:
		data['casenum'] = message.text

	c.execute("SELECT * FROM rega ORDER BY did DESC LIMIT 0,1")
	fetch = c.fetchall()

	next_did = fetch[0][0] + 1
	reger = message.chat.first_name
	region = data['region']
	agency = data['agency']
	content = data['content']
	casenum = data['casenum']

	await bot.send_message(message.chat.id, md.text(
		md.text('Сонымен, ', md.bold(data['regdoc']), " әрекеті таңдалды"),
		md.text('Құжаттың шығыс тіркеу номері: ', next_did),
		md.text('Құжатты тіркеген: ', reger),
		md.text('Құжат жолданатын аймақ: ', region),
		md.text('Құжат жолданатын мекеме: ', agency),
		md.text('Құжаттың қысқаша мазмұны: ', content),
		md.text('Құжат қатысты істің номері: ', casenum),
		sep='\n\n'), parse_mode=ParseMode.MARKDOWN)

	c.execute("INSERT INTO rega(did,reger,region,agency,content,casenum) VALUES(?,?,?,?,?,?)", (next_did, reger, region, agency, content, casenum))
	conn.commit()

	# Finish conversation
	data.state = None
	await state.finish()
Exemple #2
0
async def save_car_image(message: Message, state: FSMContext):
    async with state.proxy() as data:
        file_id = message.photo[-1].file_id
        car = data.get('car')
        await db.add_new_img(file_id, car)
        data['images'] = list(car.images)
        call = data.pop('call')
        await call.answer('Фото добавлено!')
    await back_to_car_update({}, state, message)
Exemple #3
0
async def questions_step_by_step(message: types.Message, state: FSMContext):
    """
    Функция квиза
    :param state:
    :param message: сообщение пользователя
    :return: отправляем следующий вопрос
    """
    user_id: int = message.from_user.id
    current_question: int = db.get_current_question(user_id)

    async with state.proxy() as data:
        data[current_question] = message.text

    right_answer = False
    if current_question > 30:
        text = MESSAGES['you are finished']
        markup = ReplyKeyboardRemove()
    else:
        question = questions[current_question]
        markup = ReplyKeyboardMarkup(resize_keyboard=True,
                                     one_time_keyboard=True)
        user_answer = message.text.lower()
        true_answer = questions[current_question]['Answer'].lower()

        if user_answer == true_answer:
            right_answer = True
            db.set_point(user_id, current_question)

        have_hint = db.have_hints(user_id)
        if current_question + 1 > 20:
            markup = ReplyKeyboardRemove()
            #  here open questions
            if not right_answer and not have_hint:
                # даем подсказку
                text = MESSAGES['hint'] + question['Choices'][0]
                db.set_hint(user_id)
            else:
                # он дал верный ответ или уже была одна подсказка
                db.delete_hint(user_id)
                db.increment_current_question(user_id, current_question)
                if current_question == 30:
                    text = MESSAGES['the_end']
                    await state.finish()
                else:
                    question = questions[current_question + 1]
                    text = question['Question']
                    await Quiz.next()
        else:
            #  here quiz questions
            db.increment_current_question(user_id, current_question)
            question = questions[current_question + 1]
            text = question['Question']
            for choice in question['Choices']:
                choice_btn = KeyboardButton(choice)
                markup.add(choice_btn)
            await Quiz.next()
    await message.reply(text, reply_markup=markup, reply=False)
async def process_save(message: types.Message, state: FSMContext):
    if not message.photo:
        await message.answer('Отправьте валидное фото')
    async with state.proxy() as data:
        db.add_fake(random_id(), data['name'], data['age'], data['gender'],
                    data['city'], data['occupation'], data['about'],
                    message.photo[-1].file_id)
        await state.finish()
        await message.answer('Фейк добавлен. Нажмите /fake чтобы добавить ещё')
Exemple #5
0
async def process_name(message: types.Message, state: FSMContext):
    """
    Process user name
    """
    async with state.proxy() as data:
        data['name'] = message.text

    await Form.next()
    await message.reply("How old are you?")
async def answer_state_api_hash(msg: Message, state: FSMContext):
    logger.info(
        f'[{msg.from_user.id}] [{await state.get_state()}] > {msg.text}')

    async with state.proxy() as data:
        data['api_hash'] = msg.text
        await msg.answer(text=f'{gen_text(data)}\nEnter phone_number:')

    await AccountAuthStates.next()
Exemple #7
0
async def VKf(message: types.Message, state: FSMContext):
    async with state.proxy() as data:
        message.text = str(message.text).lower().title()
        if message.text == "0":
            data['vk'] = ""
        else:
            data['vk'] = message.text
        await bot.send_message(message.from_user.id, about_you)
        await Register.next()
Exemple #8
0
async def process_gender(message: types.Message, state: FSMContext):
    async with state.proxy() as data:
        data['gender'] = message.text

        # Remove keyboard
        markup = types.ReplyKeyboardRemove()

    await Form.next()
    await message.reply("What is your height?", reply_markup=markup)
Exemple #9
0
async def enter_schedule_faculty(msg: types.Message, state: FSMContext):
    async with state.proxy() as data:
        if msg.text not in get_faculties():
            return await msg.answer("Выберите факультет с клавиатуры!",
                                    reply_markup=faculty_kb)
        data["schedule_faculty"] = msg.text
        await NewSchedule.next()
        return await msg.answer("Выберите направление: ",
                                reply_markup=get_direction_kb(msg.text))
Exemple #10
0
async def enter_schedule_time(msg: types.Message, state: FSMContext):
    async with state.proxy() as data:
        if msg.text not in times:
            return await msg.answer("Выберите время с клавиатуры!",
                                    reply_markup=times_kb)
        data["schedule_time"] = msg.text
        await NewSchedule.next()
        return await msg.answer("Введите дату начала действия расписания: ",
                                reply_markup=ReplyKeyboardRemove())
Exemple #11
0
async def enter_schedule_name(msg: types.Message, state: FSMContext):
    async with state.proxy() as data:
        if not msg:
            return await msg.answer(
                "Название не может быть пустым! Попробуйте ввести снова или нажмите /cancel"
            )
        data["schedule_name"] = msg.text
        await NewSchedule.next()
        return await msg.answer("Введите кабинет: ")
Exemple #12
0
async def enter_group_name(msg: types.Message, state: FSMContext):
    async with state.proxy() as data:
        if msg.text:
            data["group_name"] = msg.text
            await NewGroup.next()
            return msg.answer("Выберите факультет: ", reply_markup=faculty_kb)
        return await msg.answer(
            "Название не может быть пустым! Попробуйте ввести снова или нажмите /cancel"
        )
Exemple #13
0
async def select_style(call: CallbackQuery, callback_data: dict, state: FSMContext):
    '''
    Navigates the 21 style options
    '''
    name = callback_data.get('name')
    await call.message.edit_media(InputMediaPhoto(open(f'stylization_mode/style_images/{name}.jpg', 'rb')),
                                  reply_markup=style_menu[name])
    async with state.proxy() as data:
        data['style_path'] = f'stylization_mode/style_images/{name}.jpg'
Exemple #14
0
 async def _get_date(message: types.Message, state: FSMContext):
     logger.info('User %s has train code: %s', message.from_user.username,
                 message.text)
     async with state.proxy() as data:
         data['train_code'] = message.text
         logger.info('Current state: %s', data)
     await TicketOrderState.next()
     await message.reply(
         "Введите тип вагона (одной буквой, пример: К -- купе).")
Exemple #15
0
async def process_name(message: types.Message, state: FSMContext):
    """
    Process user name
    """
    async with state.proxy() as data:
        data['name'] = message.text

    await Form.next()
    await message.reply("How old are you?")
Exemple #16
0
async def process_name(message: types.Message, state: FSMContext):
    """
    Process user name
    """
    async with state.proxy() as data:
        data['firstname'] = message.text

    await Form.next()
    await message.reply("What's your surname?")
Exemple #17
0
async def send_info_to_doctor(state: FSMContext) -> str:
    async with state.proxy() as data:
        text_to_chat = compose_summary(data)

    await bot.send_message(config.DOCTORS_GROUP,
                           text_to_chat,
                           parse_mode='HTML')

    return text_to_chat
async def delete_position(message: types.Message, state: FSMContext):
    user_id: int = message.from_user.id
    await get_user_data(message=message,
                        main_state=state,
                        data_name='goods_position',
                        update_db=False)

    async with state.proxy() as data:
        is_valid: bool = data['goods_position'].isdigit()

        if is_valid:
            basket_count: list[int] = await get_user_database_data(
                user_id=user_id, data_name='basket_count')
            basket_name: list[str] = await get_user_database_data(
                user_id=user_id, data_name='basket_name')
            basket_item_price: list[int] = await get_user_database_data(
                user_id=user_id, data_name='basket_item_price')
            total_price: int = await get_user_database_data(
                user_id=user_id, data_name='total_price')

            new_basket_name: list[str] = []
            new_basket_count: list[int] = []
            new_basket_item_price: list[int] = []

            for i, basket_elm in enumerate(zip(basket_name, basket_count,
                                               basket_item_price),
                                           start=1):
                basket_name_elm = basket_elm[0]
                basket_count_elm = basket_elm[1]
                basket_item_price_elm = basket_elm[2]
                if i != int(data['goods_position']):
                    new_basket_name.append(basket_name_elm)
                    new_basket_count.append(basket_count_elm)
                    new_basket_item_price.append(basket_item_price_elm)
                    logging.info('ffffffffffffffffffffffff', basket_name_elm,
                                 basket_count_elm, basket_item_price_elm)
                else:
                    total_price -= basket_item_price_elm * basket_count_elm

            logging.info('iiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii',
                         new_basket_item_price)
            await update_user_data(user_id,
                                   basket_name=new_basket_name,
                                   basket_count=new_basket_count,
                                   basket_item_price=new_basket_item_price,
                                   total_price=total_price)

            await state.finish()
            if total_price == 0:
                await show_goods_basket(message)
            else:
                await show_goods_basket(message, mode='edit')
        else:
            await EditBasketDeletePos.previous()
            await message.answer(text=f'Упс( Похоже вы ввели не число.')
            await ask_position(message)
Exemple #19
0
async def process_L1(message: types.Message, state: FSMContext):
    """
    Process user language
    """

    async with state.proxy() as data:
        data['L1'] = message.text.lower()

    await Form.next()
    await message.reply(_("What language do you want to study?"))
Exemple #20
0
async def save_progress(message: Message, state: FSMContext):
    async with state.proxy() as data:
        if 'id' not in data:
            await message.reply("Не выбран id задачи. Пришлите его в ответ")
            return

        print(data.__dict__['_copy'])
        with open(os.path.join(BASEDIR, data['id'], 'data.json'), 'w') as f:
            json.dump(data.__dict__['_copy'], f)
    await message.reply('Прогресс сохранен')
Exemple #21
0
async def start(message: Message, state: FSMContext):

    async with state.proxy() as data:
        if 'id' not in data:
            await message.reply("Не выбран id задачи. Пришлите его в ответ")
            return
        data['path'] = '/'

    await message.reply("Введите адрес объекта", reply_markup=keyboard['/'])
    await message.reply("init", reply_markup=ReplyKeyboardMarkup([['/start'], ['Назад'], ['Не заполнено'], ['Сохранить'], ['Выход']]))
Exemple #22
0
async def answer_categoty(message: types.Message, state: FSMContext):
    async with state.proxy() as data:
        data['Описание'] = message.text

    await message.answer(
        "Хотите ли Вы подписаться под сообщением? Это поможет связаться с Вами при необходимости\n\n"
        "Если Вы хотите изменить сообщение, нажмите отмена и начните заново",
        reply_markup=keyboards.anonymous_button)

    await FeedbackInfo.next()
Exemple #23
0
async def backtrack(message: Message, state: FSMContext):
    path = ''
    async with state.proxy() as data:
        if 'id' not in data:
            await message.reply("Не выбран id задачи. Пришлите его в ответ")
            return

        path = prev_path(data['path'])
        data['path'] = path
    await message.reply(data['path'], reply_markup=keyboard[path])
async def answer_q1(message: Message, state: FSMContext):
    answer = message.text
    logging.info(f"total_area: {answer}")

    async with state.proxy() as data:
        data['total_area'] = answer
    await message.answer(
        'Сколько комнат в квартире?\n'
        'Введите число от 1-5 или 6, если в квартире больше 5 комнат')
    await Test.next()
async def answer_q4(message: Message, state: FSMContext):
    answer = message.text
    logging.info(f"constryear: {answer}")

    async with state.proxy() as data:
        data['constryear'] = answer
    await message.answer('Сейчас нужно определиться с типом жилья',
                         reply_markup=btn.q5_choice)

    await Test.next()
Exemple #26
0
async def delete_paper(message: types.Message, state: FSMContext):
    async with state.proxy() as data:
        data['command'] = message.text
        if not stock.get_paper(data['ticker'], data['port_id'], message.from_user.id):
            return
    await DeletePaperFSM.confirm.set()
    answer_message = 'Delete paper from portfolio. All records will be deleted. \n Use this command only if paper was' \
                     'added by mistake. Confirm your decision'
    await bot.send_message(message.chat.id, answer_message,
                           reply_markup=types.ReplyKeyboardMarkup([['Delete paper', 'Cancel']], resize_keyboard=True))
Exemple #27
0
async def find_by_id(message: types.Message, state: FSMContext):
    _id = re.match("^[i|I][d|D]\s*:?\s*([0-9a-z]{24})", message.text).group(1)
    res = botutils.get_from_wiki(id=_id, ret_fields=["name"])["_id"]
    if res:
        async with state.proxy() as idp:
            idp["_id"] = res["_id"]
        await EditProcess._id.set()
        await message.answer(f"Found : {res['name']}")
        await message.answer("Are you sure want to edit this one?",
                             reply_markup=botutils.get_replymarkup_yesno())
Exemple #28
0
async def process_field(message: types.Message, state: FSMContext):
    global MEDIA_CONTENT_FIELDS
    async with state.proxy() as data:
        data["old_field"] = message.text
        old_value = data["word_info"].get(message.text, "None")
        if old_value == "" or old_value == "None":
            old_value = "Field is empty"
    repl = botutils.get_replymarkup_cancel()
    await message.answer(f"Old value of '{message.text}' : ")
    if message.text in MEDIA_CONTENT_FIELDS:
        await botutils.reply_attachments(message, old_value)
        await EditProcess.new_field_media.set()
        async with state.proxy() as data:
            data["new_field_media"] = []
        repl = botutils.get_replymarkup_finish()
    else:
        await message.answer(old_value)
        await EditProcess.new_field_text.set()
    await message.answer(f"Send new value for this field.", reply_markup=repl)
Exemple #29
0
async def find_by_name(message: types.Message, state: FSMContext):
    name = re.match("^/?[n|N]ame\s*:?\s*(.+)", message.text).group(1)
    res = botutils.get_from_wiki(name=name, ret_fields=["name"])["name"]
    if len(res) == 0:
        await message.answer(f"Nothing found for {name}")
        return
    await EditProcess.name.set()
    async with state.proxy() as data:
        data['names'] = {word['_id'] : word['name'] for word in res}
    await message.answer("Which word do you want to change? There are last 5 symbols of id in brackets.", reply_markup=botutils.get_replymarkup_names(res))
Exemple #30
0
async def process_description(message: types.Message, state: FSMContext):
    """
    Process user description
    """
    async with state.proxy() as data:
        data['description'] = message.text

    await Form.next()

    await message.reply("Ingrese las categorias separadas por coma")
Exemple #31
0
async def process_spreraders(message: Message, state: FSMContext):
    spreraders = int(message.text)
    async with state.proxy() as data:
        data['spreraders_leng'] = spreraders
    await PersonalTuning.next()
    markup = ReplyKeyboardMarkup(resize_keyboard=True, selective=True)
    markup.add('1', '2', '3', '4', '5')
    await message.reply(
        'Укажите качетсво завала: 1 - очень плохой, 5 - отличный.',
        reply_markup=markup)
async def answer_q1(message: Message, state: FSMContext):
    answer = message.text
    logging.info(f"address: {answer}")

    async with state.proxy() as data:
        data['address'] = answer
    await message.answer(
        'Теперь необходимо ввести площадь квартиры в квадратных метрах. \n'
        'Пример: 56,3')
    await Test.next()
Exemple #33
0
async def process_gender(message: types.Message, state: FSMContext):
    async with state.proxy() as data:
        data['gender'] = message.text

        # Remove keyboard
        markup = types.ReplyKeyboardRemove()

        # And send message
        await bot.send_message(message.chat.id, md.text(
            md.text('Hi! Nice to meet you,', md.bold(data['name'])),
            md.text('Age:', data['age']),
            md.text('Gender:', data['gender']),
            sep='\n'), reply_markup=markup, parse_mode=ParseMode.MARKDOWN)

        # Finish conversation
        data.state = None
Exemple #34
0
async def process_region(message: types.Message, state: FSMContext):
	async with state.proxy() as data:
		data['content'] = message.text

	await Form.next()
	await message.reply("Құжаттың қысқаша мазмұны алынды. Енді құжат қатысты істің номерін жазыңыз:")
Exemple #35
0
async def process_region(message: types.Message, state: FSMContext):
	async with state.proxy() as data:
		data['region'] = message.text

	await Form.next()
	await message.reply("Құжат " + data['region'] + " аймағына жолданады. Енді мекемені жазыңыз:")
Exemple #36
0
async def process_region(message: types.Message, state: FSMContext):
	async with state.proxy() as data:
		data['agency'] = message.text

	await Form.next()
	await message.reply("Құжат " + data['agency'] + " мекемесіне жолданады. Енді құжаттың қысқаша мазмұнын жазыңыз:")
Exemple #37
-1
async def process_act(message: types.Message, state: FSMContext):
	async with state.proxy() as data:
		data['regdoc'] = message.text

	markup = types.ReplyKeyboardRemove()
	await Form.next()
	await message.reply("Сіз құжатты тіркеу әрекетін таңдадыңыз. Ең алдымен құжаттың қай аймаққа жолданатынын жазыңыз:", reply_markup=markup)