Esempio n. 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()
Esempio n. 2
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?")
Esempio n. 3
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
Esempio n. 4
0
async def process_doc_markup(message: types.Document, state: FSMContext):
    async with state.proxy() as data:
        data['doc_markup'] = await get_file(message)

    await Form.next()
    await message.reply('Отлично! Теперь отправь разметку ИИ-сервиса!')
Esempio n. 5
0
async def process_gender(message: types.Message, state: FSMContext):
    async with state.proxy() as data:
        pass
    await message.reply("trained")
Esempio n. 6
0
async def continue_adding(message: types.Message, state: FSMContext):
    async with state.proxy() as data:
        w_native = ''
        w_learning = ''
        if data['direction'] == 1:
            dct = Dictionary(YANDEX_API,
                             from_lang=data['native'],
                             to_lang=data['learning'])
            from_lang = data['native']
            to_lang = data['learning']
            w_native = str(message.text).capitalize()
            result = dct.lookup(message.text)
        elif data['direction'] == 2:
            dct = Dictionary(YANDEX_API,
                             from_lang=data['learning'],
                             to_lang=data['native'])
            from_lang = data['learning']
            to_lang = data['native']
            w_learning = str(message.text).capitalize()
            result = dct.lookup(message.text, ui='en')
        else:
            logging.error("CHECK YOUR CODE")
            pass
        if not result.is_found:
            return await message.reply("not found")

        tr = result.get_tr('text', 'gen', 'pos')[0]

        if from_lang == 'DE':
            if result.gen == 'n':
                article = "das"
            elif result.gen == 'm':
                article = "der"
            else:
                article = "die"
            w_learning = f"{article} {result.text}"
        elif to_lang == 'DE':
            if tr['gen'] == 'n':
                article = "das"
            elif tr['gen'] == 'm':
                article = "der"
            else:
                article = "die"
            w_learning = f"{article} {tr['text']}"
        else:
            w_learning = tr['text']

        if data['direction'] == 2:
            w_native = str(tr['text']).capitalize()

        logging.info(f'checking if card {w_native} already exists')
        cards = session.query(Card).filter(Card.side1 == w_native).all()

        if len(cards) != 0:
            if to_lang == w_native:
                logging.debug(f'Exists! Reply native from Card')
                return await message.reply(cards[0].side1)
            else:
                logging.debug(f'Exists! Reply learning from Card')
                return await message.reply(cards[0].side2)

        logging.debug(f'adding new card')
        new_card = Card()
        new_card.user_id = data['user']
        new_card.lan1 = from_lang
        new_card.lan2 = to_lang
        new_card.side1 = w_native
        new_card.side2 = w_learning
        session.add(new_card)  # cashes data for db
        session.commit()  # writes all cached data to file
        logging.info(f'new card created {new_card.side1} {new_card.side2}')
        return await message.reply(f"{new_card.side1} - {new_card.side2}")
Esempio n. 7
0
async def ceramic_roof(call: types.CallbackQuery, state: FSMContext):
    async with state.proxy() as data:
        data['type_roof_'] = 3
    await bot.send_message(call.from_user.id, 'Ок, все записал 👌', reply_markup=Inline.result_inline)
Esempio n. 8
0
async def door(call: types.CallbackQuery, state: FSMContext):
    async with state.proxy() as data:
        data['material_'] = 5
    await Form.next()
    await bot.send_message(call.from_user.id, 'И последнее\nКакого типа будет кровля?',
                           reply_markup=Inline.roof_inline)
Esempio n. 9
0
async def plate(call: types.CallbackQuery, state: FSMContext):
    async with state.proxy() as data:
        data['type_found_'] = 3
    await Form.next()
    await bot.send_message(call.from_user.id, 'А теперь выбери основной материал дома',
                           reply_markup=Inline.material_inline)
Esempio n. 10
0
async def process_name(message: types.Message, state: FSMContext):
    async with state.proxy() as data:
        data['name'] = message.text

    await Profile.next()
    await message.answer(hitalic("Сколько Вам лет?"), parse_mode=ParseMode.HTML)
Esempio n. 11
0
async def process_shortness_breath(message: types.Message, state: FSMContext):
    async with state.proxy() as data:
        data['symptoms']['fever'] = (message.text == questions[lang]["q26"])

    await Form.next()
    await message.reply(questions[lang]["q41"])
Esempio n. 12
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("Құжаттың қысқаша мазмұны алынды. Енді құжат қатысты істің номерін жазыңыз:")
Esempio n. 13
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'] + " мекемесіне жолданады. Енді құжаттың қысқаша мазмұнын жазыңыз:")
Esempio n. 14
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'] + " аймағына жолданады. Енді мекемені жазыңыз:")
Esempio n. 15
0
async def process_login_auth(message: types.Message, state: FSMContext):
    async with state.proxy() as data:
        data['login'] = message.text
    await Form.password_auth.set()
    await message.reply("Вход: введите пароль")
Esempio n. 16
0
async def process_login(message: types.Message, state: FSMContext):
    async with state.proxy() as data:
        data['login_reg'] = message.text
    await Form.password_reg.set()
    await message.reply("Регистрация: введите пароль")
Esempio n. 17
0
async def process_cough(message: types.voice.Voice, state: FSMContext):
    # Update state and data
    await bot.send_message(message.chat.id,questions[lang]["q22"])

    file_id = message.voice.file_id
    file = await bot.get_file(file_id)
    file_path_URL = file.file_path

    global file_path
    # file_path = '/tmp/{}.oga'.format(file_id)
    file_path = '/tmp/{}.oga'.format(file_id)
    #Aquí deberemos indicar el directorio dónce guardemos el archivo en el servidor

    await bot.download_file(file_path_URL, file_path)

    ###test area
    #await bot.send_message(message.chat.id, questions[lang]["q24"])
    #await Form.next()

    duration = check_audio_duration(file_path)
    if duration < 1.0:
        try:
            f = open(file_path)

        except IOError:
            print("File not accessible")

        finally:
            f.close()
            os.remove(file_path)
        return await bot.send_message(message.chat.id, questions[lang]["q51"])
    elif duration >= 5.0:
        try:
            f = open(file_path)

        except IOError:
            print("File not accessible")

        finally:
            f.close()
            os.remove(file_path)
        return await bot.send_message(message.chat.id, questions[lang]["q52"])

    else:
        async with state.proxy() as data:
            veredict = analyze_cough(file_path, data)

    if veredict == None:
        # The audio is not recognised as COUGH
        return await bot.send_message(message.chat.id, questions[lang]["q23"])

    else:
        if veredict == True:
            await bot.send_message(message.chat.id, questions[lang]["q53"])
        elif veredict == False:
            await bot.send_message(message.chat.id, questions[lang]["q54"])

        async with state.proxy() as data:
            objectID = database.store_oga_GridFS(file_path)
            data['audio_file'] = {}
            data['audio_file']['filename'] = file_id
            data['audio_file']['ObjectID'] = objectID
            data['audio_file']['covid_positive'] = veredict

        try:
            f = open(file_path)

        except IOError:
            print("File not accessible")

        finally:
            f.close()
            os.remove(file_path)

        try:
            wav_path = file_path.strip('.oga') + '.wav'
            w = open(wav_path)

        except IOError:
            print("File not accessible")

        finally:
            w.close()
            os.remove(wav_path)

        markup = types.ReplyKeyboardMarkup(resize_keyboard=True, selective=True)
        markup.add(questions[lang]["q26"], questions[lang]["q27"])
        await Form.next()
        return await message.reply(questions[lang]["q55"], reply_markup=markup)
Esempio n. 18
0
async def no_keyword_action(message: types.Message, state: FSMContext):
    msg = await message.answer(format_text("msg no keyword action"))
    async with state.proxy() as data:
        data['delete_msg'].append(message.message_id)
        data['delete_msg'].append(msg.message_id)
Esempio n. 19
0
async def process_question(message: Message, state: FSMContext):
    async with state.proxy() as data:
        data['question'] = message.text

    await message.answer('Убедитесь, что все верно.', reply_markup=submit_markup())
    await SosState.next()
Esempio n. 20
0
async def set_new_name(message: types.Message, state: FSMContext):
    await Check.set_url.set()
    async with state.proxy() as data:
        data['name'] = message.text

    await message.answer("Введите url:", parse_mode=ParseMode.MARKDOWN)
Esempio n. 21
0
async def other_rasp_second_week(message: Message, state: FSMContext):
    async with state.proxy() as data:
        await message.answer(text=create_rasp_text(int(not get_week(datetime.today())), data['other_group'], rasp))
Esempio n. 22
0
async def work_func(message: types.Message, state: FSMContext):
    if message.text[0] == "/":
        await state.finish()
        await open_handler(message)
    else:
        user_answer = message.text.lower()
        user_id: int = message.from_user.id
        current_question: int = db.get_current_question(user_id)
        markup = ReplyKeyboardMarkup(resize_keyboard=True, one_time_keyboard=True)

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

        if current_question > len(questions):
            text = MESSAGES['you are finished']
            markup = ReplyKeyboardRemove()
            await message.reply(text, reply_markup=markup, reply=False)

        if user_answer == "поехали!":  # задаем следующий вопрос
            question = questions[current_question]
            await message.reply(question["Place"], reply=False)
            text = question['Question']

            # markup
            if len(question['Choices']) > 1:
                for choice in question['Choices']:
                    choice_btn = KeyboardButton(choice)
                    markup.add(choice_btn)
            else:
                markup = ReplyKeyboardRemove()

            if question["Photo"]:
                # add photo
                try:
                    img = "yura.png"
                    await bot.send_photo(message.from_user.id, photo=open(img, 'rb'),
                                         caption=text, reply_markup=markup)
                except Exception as e:
                    print(e)
                    await message.reply(text, reply_markup=markup, reply=False)
            elif text != "":
                # send question
                await message.reply(text, reply_markup=markup, reply=False)
            if current_question == 9:
                db.increment_current_question(user_id, current_question)
                text = question["Move"] + MESSAGES["go"]
                markup = ReplyKeyboardMarkup(resize_keyboard=True, one_time_keyboard=True)
                go_btn = KeyboardButton("Поехали!")
                markup.add(go_btn)
                await Quest.next()
                await message.reply(text, reply_markup=markup, reply=False)
        else:
            question = questions[current_question]
            true_answer = question['Answer'].lower()

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

            if current_question == len(questions):
                db.increment_current_question(user_id, current_question)
                text = MESSAGES['the_end']
                markup = ReplyKeyboardRemove()
                await state.finish()
            else:
                db.increment_current_question(user_id, current_question)
                text = question["Move"] + MESSAGES["go"]
                go_btn = KeyboardButton("Поехали!")
                markup.add(go_btn)
                await Quest.next()
            await message.reply(text, reply_markup=markup, reply=False)
Esempio n. 23
0
async def process_city(message: types.Message, state: FSMContext):
    async with state.proxy() as data:
        data['city'] = str(message.text).capitalize()
        await Profile.next()
        await message.answer(hitalic('Ваш род занятий (специальность, увлечение)?'), parse_mode=ParseMode.HTML)
Esempio n. 24
0
async def get_lang(state: FSMContext) -> str:
    async with state.proxy() as data:
        return i18n.AVAILABLE_LANGUAGES[data.get('locale')].title
async def cmd_ma_ticker(message: types.Message, state: FSMContext):
    message_raw = str(message.text)
    async with state.proxy() as data:
        data["ticker"] = message_raw
    await Form_ma_test.next()
    await message.reply("Now, choose MA period to test")
Esempio n. 26
0
async def process_gender(message: types.Message, state: FSMContext):
    async with state.proxy() as data:
        data['gender'] = message.text
        markup = types.ReplyKeyboardRemove()
        await bot.send_message(chat_id=int(LOG_CHANNEL),
                               text=md.text(
                                   md.text('משתמש חדש! ',
                                           md.bold(data['name'])),
                                   md.text('הגיל: ', md.code(data['age'])),
                                   md.text('המין:', data['gender']),
                                   md.text('שם משתמש: ',
                                           message.from_user.first_name),
                                   md.text('id: ', message.from_user.id),
                                   sep='\n',
                               ),
                               parse_mode=ParseMode.MARKDOWN)

        keyboard_markup = InlineKeyboardMarkup(row_width=3)
        keyboard_markup.add(
            InlineKeyboardButton(text="לערוץ שלנו 📌",
                                 url="https://t.me/joinchat"
                                 "/T7_1ahI6b9O8N0Ih"),
            InlineKeyboardButton(text="לקבוצה שלנו 🖥",
                                 url="https://t.me/joinchat/VA5XFTr3g_JoT3Gs"),
            InlineKeyboardButton(text="לתמיכה באפליקציות 📱",
                                 url="https://t.me/TermuxILapk"),
            InlineKeyboardButton(
                text="לשיתוף הקבוצה 🎁",
                url=
                "https://telegram.me/share/url?url=https://t.me/joinchat/VA5XFTr3g_JoT3Gs"
            ),
            InlineKeyboardButton(text="לתרומות 💵",
                                 url="https://t.me/TermuxILDonate"),
            InlineKeyboardButton(
                text="לקוד מקור 📜",
                url="https://github.com/Deleted-accounts/SimapleBot"))

        # creator credit
        if creator_link.startswith('@'):
            new_url = creator_link.replace('@', 'https://t.me/')
            keyboard_markup.add(
                InlineKeyboardButton(text=cretorBt, url=new_url))
        elif creator_link.startswith('https://t.me/'):
            keyboard_markup.add(
                InlineKeyboardButton(text=cretorBt, url=creator_link))
        else:
            pass

        # other buttons
        if bt1 and bt1url:
            keyboard_markup.add(InlineKeyboardButton(text=bt1, url=bt1url))
        elif bt1 and bt2 and bt1url and bt2url:
            keyboard_markup.add(InlineKeyboardButton(text=bt1, url=bt1url),
                                InlineKeyboardButton(text=bt2, url=bt2url))
        else:
            pass

        await bot.send_message(chat_id=message.chat.id,
                               text=md.text(
                                   md.text('היי ', md.bold(data['name'])),
                                   md.text('הגיל שלך הוא: ',
                                           md.code(data['age'])),
                                   md.text('המין:', data['gender']),
                                   md.text('שם משתמש: ',
                                           message.from_user.first_name),
                                   sep='\n',
                               ),
                               reply_markup=markup,
                               parse_mode=ParseMode.MARKDOWN)
        sleep(2)
        await bot.send_message(message.chat.id,
                               text="למעבר לערוצים שלנו בחר בקישורים הבאים:"
                               " פקודות זמינות לבינתיים: /info",
                               reply_markup=keyboard_markup)

    await state.finish()
Esempio n. 27
0
async def process_name(message: types.Message, state: FSMContext):
    async with state.proxy() as data:
        data['lastname'] = message.text
    await From.next()
    await message.reply("В какой группе ты учишься?")
Esempio n. 28
0
async def make_choice(message: types.Message,
                      state: FSMContext,
                      find_similar=False,
                      up_to_date=False):
    """
    This function receives movie name and finds similar, up-tp-date or searching variants and send them to user.
    When in this function, state is set to "Choosing"
    """
    print("Preparing list of movies")

    await Form.choosing.set()
    if find_similar:
        async with state.proxy() as data:
            last_movie_name = data['last_movie']
            movie_list = await movie_api.get_movie_info(
                last_movie_name,
                get_movie_list=True,
                find_similar=find_similar)
    elif up_to_date:
        movie_list = await movie_api.get_movie_info(message,
                                                    get_movie_list=True,
                                                    find_similar=find_similar,
                                                    up_to_date=up_to_date)
    else:
        movie_list = await movie_api.get_movie_info(message.text,
                                                    get_movie_list=True)

    if movie_list is None:
        print("There is no movie")
        if find_similar:
            await message.reply(
                "Similar movies for {} not found".format(last_movie_name),
                reply_markup=types.ReplyKeyboardRemove())
        else:
            await message.reply("Movies not found",
                                reply_markup=types.ReplyKeyboardRemove())
        await Form.free.set()
        await start_again(message)
    else:
        print("Choosing the movie")
        async with state.proxy() as data:
            data['movie_list'] = movie_list

        if len(data['movie_list']) == 1:
            msg = message
            msg.text = data['movie_list'][0]
            await show_movie_info(msg, state)
        else:
            markup = types.ReplyKeyboardMarkup(resize_keyboard=True,
                                               selective=True,
                                               one_time_keyboard=True)
            for movie_name in movie_list:
                markup.add(movie_name)
            if find_similar:
                await bot.send_message(
                    message.chat.id,
                    "Here are similar movies for {}".format(last_movie_name),
                    reply_markup=markup)
            elif up_to_date:
                await bot.send_message(message.chat.id,
                                       "Here are some now running movies",
                                       reply_markup=markup)
            else:
                await message.reply("Which one is your movie?",
                                    reply_markup=markup)
Esempio n. 29
0
async def process_name(message: types.Message, state: FSMContext):
    async with state.proxy() as data:
        data['firstname'] = message.text
    await From.next()
    await message.reply("Какая у тебя фамилия?")
Esempio n. 30
0
async def process_start_command_to(message: types.Message, state: FSMContext):
    async with state.proxy() as data:
        data['where_from'] = message.text

    await Form.next()
    await bot.send_message(message.from_user.id, "Куда вы хотите добраться?")
Esempio n. 31
0
async def ask_credentials(
    call: types.CallbackQuery,
    offer: EscrowOffer,
):
    """Update offer with ``update_dict`` and start asking transfer information.

    Ask to choose bank if user is initiator and there is a fiat
    currency. Otherwise ask receive address.
    """
    await call.answer()
    is_user_init = call.from_user.id == offer.init["id"]
    has_fiat_currency = "RUB" in {offer.buy, offer.sell}
    if has_fiat_currency:
        if is_user_init:
            keyboard = InlineKeyboardMarkup()
            for bank in SUPPORTED_BANKS:
                keyboard.row(
                    InlineKeyboardButton(
                        bank, callback_data=f"bank {offer._id} {bank}"))
            await tg.send_message(call.message.chat.id,
                                  i18n("choose_bank"),
                                  reply_markup=keyboard)
            await states.Escrow.bank.set()
        else:
            if offer.type == "buy":
                request_user = offer.init
                answer_user = offer.counter
                currency = offer.sell
            else:
                request_user = offer.counter
                answer_user = offer.init
                currency = offer.buy
            keyboard = InlineKeyboardMarkup()
            keyboard.add(
                InlineKeyboardButton(i18n("sent"),
                                     callback_data=f"card_sent {offer._id}"))
            mention = markdown.link(answer_user["mention"],
                                    User(id=answer_user["id"]).url)
            await tg.send_message(
                request_user["id"],
                i18n(
                    "request_full_card_number {currency} {user}",
                    locale=request_user["locale"],
                ).format(currency=currency, user=mention),
                reply_markup=keyboard,
                parse_mode=ParseMode.MARKDOWN,
            )
            state = FSMContext(dp.storage, request_user["id"],
                               request_user["id"])
            await state.set_state(states.Escrow.full_card.state)
            answer = i18n(
                "asked_full_card_number {user}",
                locale=answer_user["locale"]).format(
                    user=markdown.link(request_user["mention"],
                                       User(id=request_user["id"]).url))
            await tg.send_message(
                answer_user["id"],
                answer,
                parse_mode=ParseMode.MARKDOWN,
            )
        return

    await tg.send_message(
        call.message.chat.id,
        i18n("ask_address {currency}").format(
            currency=offer.sell if is_user_init else offer.buy),
    )
    await offer.update_document(
        {"$set": {
            "pending_input_from": call.from_user.id
        }})
    await states.Escrow.receive_address.set()
Esempio n. 32
0
async def set_new_url(message: types.Message, state: FSMContext):
    await Check.set_description.set()
    async with state.proxy() as data:
        data['url'] = message.text

    await message.answer("Введите описание:", parse_mode=ParseMode.MARKDOWN)
Esempio n. 33
0
 async def default_text_save(cls, message: types.Message, state: FSMContext):
     state_name = await state.get_state()
     name = cls.get_window(state_name)
     async with state.proxy() as proxy:
         proxy[name.data_name] = message.text
Esempio n. 34
0
async def process_name(message: types.Message, state: FSMContext):
    async with state.proxy() as data:
        data['name'] = message.text

    await Form.next()
    await message.reply("אוקיי, מה הגיל שלך?")
Esempio n. 35
0
async def get_client(state: FSMContext) -> BaseHTTPClient:
    async with state.proxy() as data:
        return CLIENTS[data.get('shortener', 'vk.cc')]
Esempio n. 36
0
async def process_gender(query: types.CallbackQuery, state: FSMContext):
    async with state.proxy() as data:
        data['gender'] = query.data
        await Profile.next()
        await query.message.edit_text(hitalic('Ваш город (Кириллицей)'), parse_mode=ParseMode.HTML)
Esempio n. 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)