Ejemplo n.º 1
0
async def register_answer_callback_handler(query: types.CallbackQuery):
    registered: User = await is_registered(query.from_user.id)
    if registered.ok:
        return await query.message.reply(
            f"Hello {query.from_user.first_name} "
            f"anda sudah terdaftar sebelumnya",
            reply_markup=types.ReplyKeyboardRemove())
    answer_data = query.data
    await query.answer(f'You answered with {answer_data!r}')
    if answer_data == 'daftar':
        await query.message.answer(
            "untuk daftar balas pesan ini data dengan format seperti berikut",
            reply_markup=types.ReplyKeyboardRemove())
        await query.message.answer("#DAFTAR\n"
                                   "\nKabupaten : kabupaten kamu"
                                   "\nKecamatan :  kecamatan kamu"
                                   "\nNama Outlet :  nama outlet kamu"
                                   "\nNomor MKios : nomor mkios kamu")
        await query.message.answer("Contohnya : ")
        await query.message.answer("#DAFTAR\n"
                                   "\nKabupaten : Cilacap"
                                   "\nKecamatan : Cilacap Tengah"
                                   "\nNama Outlet : Yahya Cell"
                                   "\nNomor MKios : 081234567890")
    elif answer_data == 'tolak_daftar':
        keyboard_markup = types.ReplyKeyboardRemove()
        await bot.send_message(query.from_user.id,
                               text=":( ",
                               reply_markup=keyboard_markup)
        text = 'jika anda berubah fikiran silahkan daftar dengan perintah /daftar atau /help'
        await bot.send_message(query.from_user.id, text)
    else:
        text = f'Unexpected callback data {answer_data!r}!'
        await bot.send_message(query.from_user.id, text)
Ejemplo n.º 2
0
async def quiz_process2(obj, state: FSMContext, callback_data: dict = None):
    async with state.proxy() as storage:
        current_question = questions[storage["current_question"]]
        if isinstance(obj, types.Message):
            if obj.text not in current_question.answers:
                await obj.answer("Выберите один из предложенных ответов")
                return
            chat_id = obj.chat.id
            if not current_question.is_right(obj.text):
                await obj.answer("Неправильный ответ, попробуйте еще раз")
                return
        else:
            await obj.answer(text="Ответ принят!")
            chat_id = obj.message.chat.id
            if not current_question.is_right_by_index(int(callback_data["number"])):
                await bot.send_message(
                    chat_id, text="Неправильный ответ, попробуйте еще раз"
                )
                return
        await bot.send_message(
            chat_id,
            text="Верно! Ответишь на следующий?",
            reply_markup=types.ReplyKeyboardRemove(),
        )
        storage["current_question"] += 1
        if storage["current_question"] >= len(questions):
            await bot.send_message(
                chat_id,
                "Ой, вопросы для вас закончились, приходите завтра или пройдите заново, нажав /start",
                reply_markup=types.ReplyKeyboardRemove(),
            )
            await MainDialog.win.set()
            return
        await send_question(bot, chat_id, questions[storage["current_question"]])
Ejemplo n.º 3
0
async def kategori_handler(query: types.CallbackQuery, state: user_form):
    if query.message.chat.type == 'group':
        return await query.message.answer(
            f"Perintah ini tidak berlaku disini, jika anda perlu bantuan saya, "
            f"Private Message ☺️")
    registered: User = await is_registered(query.from_user.id)
    if not registered.ok:
        await query.message.reply("Sorry, Kamu Belum Terdaftar 😝",
                                  reply_markup=types.ReplyKeyboardRemove())
    else:
        answer_data = query.data
        async with state.proxy(
        ) as proxy:  # proxy = FSMContextProxy(state); await proxy.load()
            if proxy['buy'] not in semua_produk_yg_ada_kategorinya():
                return await query.message.answer(
                    f"Perintah anda salah",
                    reply_markup=types.ReplyKeyboardRemove())
            proxy['kategori'] = answer_data
            proxy['proses_beli'] = True
            kategori_name: str = temukan_nama_kategori_berdasarkan_kode_kat(
                proxy['buy'], answer_data)
            await query.message.answer(
                f"{goods[proxy['buy']]['nama']} | {kategori_name} \n"
                f"Masukkan jumlahnya barang dalam bentuk angka",
                reply_markup=types.ReplyKeyboardRemove())
Ejemplo n.º 4
0
async def response_upload_bukti(message,
                                proxy,
                                proxy_complain_photo_name=None,
                                after=None,
                                if_wrong=None):
    if not message.photo:
        if if_wrong:
            await if_wrong()
        else:
            return await message.answer(
                "Upload Foto, bukan text",
                reply_markup=types.ReplyKeyboardRemove())
    if not proxy_complain_photo_name:
        if not proxy['complain_photo']:
            proxy['complain_photo'] = [message.photo[-1].file_id]
        else:
            proxy['complain_photo'].append(message.photo[-1].file_id)
        await message.answer(
            "Dengan bukti yang kamu kirim ini akan membuat kirana mudah dalam proses peninjauan",
            reply_markup=types.ReplyKeyboardRemove())
        # sleep(2)
        proxy['complain_photo_require'] = False
        await send_complain_or_not(message, proxy)
    else:
        proxy[proxy_complain_photo_name] = message.photo[-1].file_id
    if after:
        await after()
Ejemplo n.º 5
0
async def start_rig(message: types.Message, state: FSMContext):
    name = message.text
    names = get_coins_names_from_config(config)
    if name not in names:
        await message.answer("Use keyboard.")
        return

    del names
    if '1' == config[name]['active_miner']:
        await message.answer(
            "You need to stop this rig before launch new one.",
            reply_markup=types.ReplyKeyboardRemove())
        await state.finish()
    else:
        run_rig(name)

        await message.answer("Mining is running.",
                             reply_markup=types.ReplyKeyboardRemove())

        last_message = await message.answer(
            "Mining statistic will automaticaly updated here.")

        config['CLIENT']['last_message'] = str(last_message['message_id'])
        save_config(config)

        await state.finish()
Ejemplo n.º 6
0
async def switch_active(message: types.Message, state: FSMContext):
    pfl = await PG.user_info(message.chat.id)

    if message.text == 'Да':
        if dict(pfl)['active'] is False:
            await PG.add_user_info(message.chat.id, 'active', True)
            await Profile.active.set()
            await message.answer('С возвращением! Вот твоя анкета:',
                                 reply_markup=types.ReplyKeyboardRemove())
            await asyncio.sleep(1)
            await profile(message)

        else:
            await message.answer('Что ж, до скорого времени! Заходи если что.',
                                 reply_markup=types.ReplyKeyboardRemove())
            await PG.add_user_info(message.chat.id, 'active', False)
            await state.finish()
            await state.reset_data()
            await MongoDB.set_bucket(chat=message.chat.id, bucket={})

    elif message.text == 'Нет':
        if dict(pfl)['active'] is False:
            await message.answer('Мы тебе всегда здесь рады!',
                                 reply_markup=types.ReplyKeyboardRemove())
            await state.finish()
        else:
            await Profile.active.set()
            await profile(message)
Ejemplo n.º 7
0
async def all_message_handler(message: types.Message, state: user_form):
    async with state.proxy() as proxy:
        await default_proxy(proxy)
        # complain proses 4
        if proxy.get('complain_name'):
            registered: User = await is_registered(message.from_user.id)
            if not registered.ok:
                return await message.reply(
                    "Sorry, Kamu Belum Terdaftar 😝",
                    reply_markup=types.ReplyKeyboardRemove())
            return await complain.handle_message_complain(
                message, state, reset_proxy, default_proxy)
        if proxy['buy']:
            registered: User = await is_registered(message.from_user.id)
            if not registered.ok:
                return await message.reply(
                    "Sorry, Kamu Belum Terdaftar 😝",
                    reply_markup=types.ReplyKeyboardRemove())
            elif proxy['harus_ada_kategori']:
                if proxy['kategori']:
                    return await do_buy(proxy['buy'], message, state)
                await reset_proxy(proxy)
            else:
                if type(proxy['buy']) != str:
                    await reset_proxy(proxy)
                    return await message.answer(
                        "Maaf, Terjadi kesalahan, Ulangi pembelian di perintah /menu",
                        reply_markup=types.ReplyKeyboardRemove())
                return await do_buy(proxy['buy'], message, state)
        else:
            async with state.proxy() as proxy:
                proxy.setdefault('buy', 0)
        if message.chat.type == 'group':
            return await message.answer(
                f"Perintah ini tidak berlaku disini, jika anda perlu bantuan saya, "
                f"Private Message ☺️")
        if '#DAFTAR\n' and 'Kabupaten' and 'Kecamatan' and 'Nama Outlet' and 'Nomor MKios' in message.text:
            return await formulir_daftar(message)
        if message.text == "(_Belanja_)":
            async with state.proxy() as proxy:
                await default_proxy(proxy)
                await reset_proxy(proxy)
            return await select_product(message)
        if message.text == "(_Komplain_)":
            async with state.proxy() as proxy:
                await default_proxy(proxy)
                await reset_proxy(proxy)
            registered: User = await is_registered(message.from_user.id)
            if not registered.ok:
                return await message.reply(
                    "Sorry, Kamu Belum Terdaftar 😝",
                    reply_markup=types.ReplyKeyboardRemove())
            # complain proses 1
            return await complain.choose_complain_menu(message)
        return await message.answer(
            f"Ada yang bisa dibantu {message.from_user.first_name}? Ketik ini ya /help",
            reply_markup=types.ReplyKeyboardRemove())
Ejemplo n.º 8
0
async def cmd_short_step_2(message: types.Message, state: FSMContext):
    if message.text.lower() == "yes":
        await message.answer("Send your custom shortcode",
                             reply_markup=types.ReplyKeyboardRemove())
        await ShortenURLStates.waiting_for_custom_shortcode.set()
    else:
        await message.answer("Send your long URL",
                             reply_markup=types.ReplyKeyboardRemove())
        await ShortenURLStates.waiting_for_URL.set()
Ejemplo n.º 9
0
async def process_name(message: types.Message, state: FSMContext):
    async with state.proxy() as data:
        data['select'] = message.text
    if message.text == BUTTON1_NAME:
        await Form.ST1.set()
        await message.reply("Load style image",
                            reply_markup=types.ReplyKeyboardRemove())
    else:
        await Form.GAN.set()
        await message.reply("Load guitar scetch",
                            reply_markup=types.ReplyKeyboardRemove())
Ejemplo n.º 10
0
async def delete_obj(message: types.Message, state: FSMContext):
    if message.text == 'Yes':
        async with state.proxy() as data:
            _id = data["word_info"]["_id"]
            access_token = data.get("access_token", "")
        res = botutils.delete_wiki_obj(_id, access_token)
        await message.answer(f'{res} objects were deleted.', reply_markup=types.ReplyKeyboardRemove())
        await state.finish()
    elif message.text == 'No':
        await state.finish()
        await message.answer('Ok', reply_markup=types.ReplyKeyboardRemove())
Ejemplo n.º 11
0
async def process_spend(message: types.Message, state: FSMContext):
    try:
        async with state.proxy() as data:
            markup = types.ReplyKeyboardRemove()
            spent_response = message.text.lower().strip()
            if spent_response == "100%":
                spend = float(data['balance']) * 0.999
            elif spent_response == "75%":
                spend = float(data['balance']) * 0.75
            elif spent_response == "50%":
                spend = float(data['balance']) * 0.50
            elif spent_response == "25%":
                spend = float(data['balance']) * 0.25
            elif spent_response == "cancel":
                markup = types.ReplyKeyboardRemove()
                await state.finish()
                return await message.reply("Cancelled.", reply_markup=markup)
            else:
                spend = float(message.text)
            if spend <= 0:
                await state.finish()
                return await message.reply("Coin error, <= 0.")

            received, sale_type, symbol, buy_coin, sell_coin = bn_order.create_market_conversion(
                message.chat.id, data['selling_coin'], spend,
                data['buying_coin'])
            if data["oco"] == True:
                bn_order.create_oco_conversion(message.chat.id,
                                               data['selling_coin'], received,
                                               data['buying_coin'])
            elif data["tsl"] == True:
                limit_type = "sell" if sale_type.upper() == "BUY" else "buy"
                await message.reply("Creating Trailing Stop Loss...",
                                    reply_markup=markup)
                bn_order.create_trailing_stop_limit(market=symbol,
                                                    buy_coin=buy_coin,
                                                    sell_coin=sell_coin,
                                                    type=limit_type,
                                                    stop_percentage=0.03,
                                                    interval=10)

            bn_order.get_wallet(message.chat.id)

        await state.finish()
        return await message.reply("Done.", reply_markup=markup)
    except Exception as e:
        logging.error("Process Spend - MARKET BUY OR SELL ERROR:" + str(e))
        markup = types.ReplyKeyboardRemove()
        await message.reply(
            f'{message.from_user.first_name} Fail. Market Buy Or Sell Failed. /market buy btc... '
            + str(e),
            reply_markup=markup)
        await state.finish()
Ejemplo n.º 12
0
 async def get_exchange(message: types.Message):
     data = (json.loads(requests.get(URL).text))
     for exc in data:
         if message.text == exc['ccy'] and message.text != 'BTC':
             await message.answer(f"***{datetime.datetime.now().strftime('%Y-%m-%d %H:%M')}***\n"
                                  f'\U0001F4B0{message.text}\nПродажа : {exc["buy"]}₴\n'
                                  f'Покупка : {exc["sale"]}₴\n ', reply_markup=types.ReplyKeyboardRemove())
         elif message.text == exc['ccy']:
             await message.answer(f"***{datetime.datetime.now().strftime('%Y-%m-%d %H:%M')}***\n"
                                  f'\U0001F4B0{message.text}\nПродажа : {exc["buy"]}$\n'
                                  f'Покупка : {exc["sale"]}$', reply_markup=types.ReplyKeyboardRemove())
             pass
Ejemplo n.º 13
0
async def process_rate_start(message: types.Message):
    await message.answer('Отлично, приступим!',
                         reply_markup=types.ReplyKeyboardRemove())
    user_id = message.chat['id']
    user_info = get_user_info(user_id=user_id)
    if user_info['is_authorised']:
        await message.answer(bot_messages.process_rate_start,
                             reply_markup=types.ReplyKeyboardRemove())
        await rateMentor.S1_check_mentor.set()
    else:
        await message.answer(bot_messages.raise_error_rate_start,
                             reply_markup=markup_main_menu)
        await state.finish()
Ejemplo n.º 14
0
async def text_the_end(message: types.Message):
    telegram_id = message.from_user.id
    try:
        data = get_data_from_json_file(telegram_id)
    except FileNotFoundError:
        await message.answer(
            'Что то пошло не так. Попробуйте заново: /new_request',
            reply_markup=types.ReplyKeyboardRemove())
        return
    if data["orders"]:
        request_number = get_last_number_in_requests() + 1
        datetime_now = time_in_uralsk()
        request_data = get_product_name_and_count_from_data(data)
        employee_name = data['employee']['Сокращенное имя']
        request = [[
            request_number, datetime_now,
            data['shop'].get('Название', 'Неизвестно'),
            data['shop'].get('ИП/ТОО', 'Неизвестно'),
            data['shop'].get('Адрес',
                             'Неизвестно'), request_data, data['total_sum'],
            data['shop'].get('Кассовый аппарат',
                             'Неизвестно'), employee_name, 'Принят'
        ]]
        append_data_in_table(config.REQUESTS,
                             list_name='Все',
                             user_value=request)
        lists_in_table = get_lists_names_in_table(config.REQUESTS)
        if employee_name not in lists_in_table:
            create_new_list_in_table(config.REQUESTS, employee_name)
            add_base_titles_from_the_first_page_in_list(
                config.REQUESTS, employee_name)
        append_data_in_table(config.REQUESTS,
                             list_name=employee_name,
                             user_value=request)
        add_link_to_request_status(employee_name)
        uralsk_date = time_in_uralsk_date()
        new_doc(data, request_number, uralsk_date)
        file_name = f'Счет-фактура {request_number}.xlsx'
        try:
            with open(r'./docs/' + file_name, 'rb') as document:
                await message.answer_document(document)
                delete_file(file_name)
        except:
            pass
        finally:
            delete_json_file(telegram_id)
        await message.answer('Заявка была принята!',
                             reply_markup=types.ReplyKeyboardRemove())
    else:
        await message.answer('Не могу добавить заявку. Она пустая!')
Ejemplo n.º 15
0
async def first_enter(message: types.Message, state: FSMContext):
    """
    The function is called when special commands (start, help) are writen by user
    """
    await Form.free.set()
    print("Message: ", message.text)
    # await state.update_data(last_movie=None)
    if message.text == '/help':
        await bot.send_message(message.chat.id,
                               sentences.HELP_SEN,
                               reply_markup=types.ReplyKeyboardRemove())
    else:
        await bot.send_message(message.chat.id,
                               "Hi there!!! Lets try to find your movie!\n",
                               reply_markup=types.ReplyKeyboardRemove())
Ejemplo n.º 16
0
async def stage_active(message: types.Message, state: FSMContext):
    if message.text.lower() == "оплата произведена ✅":
        await message.answer(
            "Мы обработаем платеж в течение суток, с новой недели ты будешь получать три новых контакта для знакомства!",
            reply_markup=types.ReplyKeyboardRemove(),
        )
    elif message.text.lower() == "все понятно!":
        await message.answer("Супер!", reply_markup=types.ReplyKeyboardRemove())
    await AirtableAPI.update_user(message.from_user.id, state=UserState.active)
    await message.answer("Записал тебя. В понедельник пришлю контакты для встреч!")
    await message.answer(
        "Ты сможешь изменить свои настройки через команду /settings. Связаться с нами можно через команду /contact.\n\nНадеемся, что ты найдешь отличные знакомства через MeetPeer!",
        reply_markup=types.ReplyKeyboardRemove(),
    )
    await state.finish()
Ejemplo n.º 17
0
async def share_to_location(message: types.Message, state: FSMContext):
    print(message.location)
    # async with state.proxy() as state:
    #     state['order']['to_location'] = message.get('location')

    await message.answer('Геолокация получена',
                         reply_markup=types.ReplyKeyboardRemove())
Ejemplo n.º 18
0
async def cmd_cancel(
        message: types.Message,
        state: FSMContext):  # обратите внимание на второй аргумент
    # Сбрасываем текущее состояние пользователя и сохранённые о нём данные
    await state.finish()
    await message.answer("Действие отменено",
                         reply_markup=types.ReplyKeyboardRemove())
Ejemplo n.º 19
0
async def process_chest_pain(message: types.Message, state: FSMContext):
    async with state.proxy() as data:
        data['symptoms']['chest pain or pressure'] = (message.text == questions[lang]["q26"])
        markup = types.ReplyKeyboardRemove()

    await Form.next()
    await message.reply(questions[lang]["q34"], reply_markup=markup)
Ejemplo n.º 20
0
async def stop_handler(message: types.Message, state: FSMContext):
    """
    Allow user to stop the questions. Still saves everything answered. For test purposes.
    """
    current_state = await state.get_state()
    if current_state is None:
        return

    async with state.proxy() as data:

        await bot.send_message(
            message.chat.id,
            questions[lang]["q3"]
        )
        #save_features(data.as_dict())

        '''
        Insertamos los datos con formato diccionario. No hace falta
        convertirlos a JSON ya que la propia BBDD de MongoDB los convierte
        a BSON al insertar el documento

        Un hecho relevante es que la propia Colección le agrega un ID único
        a cada Documento (a cada paciente)
        '''
        database.collection.insert_one(data.as_dict())

        await bot.send_message(
            message.chat.id,
            questions[lang]["q4"]
        )
    await state.finish()
    await message.reply(questions[lang]["q5"], reply_markup=types.ReplyKeyboardRemove())
Ejemplo n.º 21
0
async def portfolio_setcurrency_finishmachine(message: types.Message, state: FSMContext):
    commands = {
        'Add shares': '',
        'Sell shares': '',
        'Sell all': ''
    }
    async with state.proxy() as data:
        data['price'] = int(message.text)
        paper = stock.get_paper(data['ticker'], data['port_id'], message.from_user.id)

        if data['command'] == 'Add shares':
            paper.add_shares(data['amount'], data['price'])
            answer_message = f'Bought {data["amount"]} at price {data["price"]}\n'
            answer_message += messages.paper(data['ticker'], data['port_id'], message.from_user)
        elif data['command'] == 'Sell shares':
            paper.sell_shares(data['amount'], data['price'])
            answer_message = f'Sold {data["amount"]} at price {data["price"]}\n'
            answer_message += messages.paper(data['ticker'], data['port_id'], message.from_user)
        elif data['command'] == 'Sell all':
            paper.sell_all(data['price'])
            paper.delete()
            answer_message = f'Sold all shares at price {data["price"]}\n'
            answer_message += messages.portfolio(data['port_id'])

        await state.finish()
        await bot.send_message(message.chat.id, answer_message, reply_markup=types.ReplyKeyboardRemove())
Ejemplo n.º 22
0
async def hide_keyboard(message: types.Message):
    chat_id = message.chat.id

    state = dp.current_state(chat=chat_id, user=message.from_user.id)
    await reset_state(state)

    await bot.send_message(chat_id, get_commands_list_msg(), reply_markup=types.ReplyKeyboardRemove())
Ejemplo n.º 23
0
async def select_product(message):
    if message.chat.type == 'group':
        return await message.answer(
            f"Perintah ini tidak berlaku disini, jika anda perlu bantuan saya, "
            f"Private Message ☺️")
    registered: User = await is_registered(message.from_user.id)
    if not registered.ok:
        return await message.reply("Kamu Belum Terdaftar 😝",
                                   reply_markup=types.ReplyKeyboardRemove())
    else:
        keyboard_markup = types.InlineKeyboardMarkup(row_width=3)
        text_and_data = (
            (goods['buy_sp_reg']['nama'], 'buy_sp_reg'),
            (goods['buy_sp_data']['nama'], 'buy_sp_data'),
        )
        row_btns = (types.InlineKeyboardButton(text, callback_data=data)
                    for text, data in text_and_data)
        keyboard_markup.row(*row_btns)
        text_and_data = (
            (goods['voucher_fisik']['nama'], 'voucher_fisik'),
            (goods['linkaja']['nama'], 'linkaja'),
        )
        row_btns = (types.InlineKeyboardButton(text, callback_data=data)
                    for text, data in text_and_data)
        keyboard_markup.row(*row_btns)
        text_and_data = (
            (goods['mkios']['nama'], 'mkios'),
            (goods['bulk']['nama'], 'bulk'),
        )
        row_btns = (types.InlineKeyboardButton(text, callback_data=data)
                    for text, data in text_and_data)
        keyboard_markup.row(*row_btns)
        return await message.reply("Silahkan Dipilih Productnya",
                                   reply_markup=keyboard_markup)
Ejemplo n.º 24
0
async def showCardItem(message: types.Message, state: FSMContext):
    if 'Назад' in message.text:
        await deleteMessages(message.message_id, message.chat.id, state)
        await message.answer('Выберите категорию',
                             reply_markup=mainYapMarkup(),
                             disable_notification=True)
        await Yap.yapMainMenu.set()
        return
    txt = message.text.split('|')[0].lower().strip()
    data = await state.get_data('card')
    card: Card = data['card']
    numb = card.isInCard(txt)
    if numb != -1:
        result = yap_db.getFromDB('items',
                                  f'name, weight, price, position',
                                  where=f"id='{card.items[numb].sqlId}'",
                                  orderBy='ORDER BY POSITION')
        if result.__len__() == 1:
            await sendNewPhoto(message, state, result[0][3], True)
            await message.answer(
                'Дли изменения количества нажмите + или - на клавиатуре выше',
                reply_markup=types.ReplyKeyboardRemove())
            await Yap.showPhotos.set()
    else:
        await message.answer('Выберите блюдо из корзины')
Ejemplo n.º 25
0
async def start_message(message: types.Message):
    user = user_db.sql_init_user(message.from_user.id)
    username = message.from_user.username
    user_id = message.from_user.id
    keyboard = types.ReplyKeyboardMarkup(resize_keyboard=True)
    if user:
        check_name = user_db.sql_show_users()
        if check_name[0][1] == 'None':
            user_db.sql_update_name(username, user_id)
        if user['admin']:
            message_text = 'Ты являешься администратором'
            await message.answer(message_text, reply_markup=keyboard)
            await main_menu(message)
        else:
            message_text = 'Привет, ' + username + '!\n\n' \
                           + 'Набери " / " для отображения списка доступных команд или выбери из меню ⤵️'
            await message.answer_sticker(
                'CAACAgIAAxkBAAECBF1gS6rbgBgyt_5c6ytFs8rjLhNQ3QACKAMAArVx2gaQekqHXpVKbh4E'
            )
            await message.answer(message_text, reply_markup=keyboard)
            await main_menu(message)
    else:
        message_text = 'Извини, я закрытый бот. Пока работаю для одной компании, но я еще выйду в свет!' \
                       '\nЕсть вопросы? Обратись к @janki_wtf'
        await message.answer(message_text,
                             reply_markup=types.ReplyKeyboardRemove())
Ejemplo n.º 26
0
async def cancel_handler(message: types.Message, state: FSMContext):
    current_state = await state.get_state()
    if current_state is None:
        return

    await state.finish()
    await message.answer("Отменено", reply_markup=types.ReplyKeyboardRemove())
Ejemplo n.º 27
0
async def process_model(message: types.Message, state: FSMContext):
    logger.info(f'chat id in process_model: {message.chat.id}')

    async with state.proxy() as datavideo:
        datavideo['model'] = message.text
        logger.info(f'model: {message.text}......')
    # Remove keyboard
    markup = types.ReplyKeyboardRemove()
    logger.info(markup)

    logger.info(f'state:{await state.get_state()}')
    # And send message
    await bot.send_message(
        message.chat.id,
        md.text(
            md.text(
                'Please upload your video(mp4) for detecting (limited 20M), thanks!'
            ),
            sep='\n',
        ),
        reply_markup=markup,
        parse_mode=ParseMode.MARKDOWN,
    )
    await VideoForm.next()
    logger.info(f'state next:{await state.get_state()}')
Ejemplo n.º 28
0
async def create_request(message:types.Message, state:FSMContext):
    await message.delete()
    await message.answer (
        '===========\nСоздание новой заявки',
        reply_markup=types.ReplyKeyboardRemove()
    )

    await state.update_data(applicant='changer') 
    await state.update_data(operation_type='')
    await state.update_data(type_of_card='')

    await state.update_data(sum_RUB__how_much='')
    await state.update_data(sum_USD__how_much='')
    await state.update_data(sum_EUR__how_much='')

    await state.update_data(sum_recive_RUB='')
    await state.update_data(sum_recive_USD='')
    await state.update_data(sum_recive_EUR='')
    await state.update_data(sum_give_RUB='')
    await state.update_data(sum_give_USD='')
    await state.update_data(sum_give_EUR='')

    await state.update_data(comment='')
    await state.update_data(permit='данных нет...')
    await state.update_data(data_request=datetime.datetime.today().strftime('%d.%m'))

    result = await message.answer('Введите номер заявки')
    await Request.request_numb.set()
    await state.update_data(_del_message=result.message_id)

    return
Ejemplo n.º 29
0
async def process_start_command(message: types.Message):
    '''
         Функция обработки команды /request {param}
    :param message: сообщение от пользователя
    '''
    params = message.get_args()
    # Если у сообщения есть параметр, то считаем его запросом
    markup=types.ReplyKeyboardRemove()
    if params:
        if current_telbot.get(message.from_user.id):
            current_telbot[message.from_user.id][1] = params
        else:
            current_telbot[message.from_user.id] = [None, params]
        await message.reply("Запрос установлен.")
    else:
        # Если у сообщения параметра нет, то выводим текущее значение запроса
        if current_telbot.get(message.from_user.id):
            if current_telbot[message.from_user.id][1]:
                await bot.send_message(message.chat.id,
                                       md.text("Текущий запрос: ",
                                               md.bold(current_telbot[message.from_user.id][1])),
                                       reply_markup=markup,
                                       parse_mode=ParseMode.MARKDOWN,)
            else:
                await message.reply("Запрос не был установлен.")
        else:
            await message.reply("Запрос не был установлен.")
Ejemplo n.º 30
0
    async def location_handler(message: types.Message):
        lat = message.location.latitude
        lon = message.location.longitude
        user = await db.users.find_one({'uid': message.from_user.id})

        if user is None:
            return await start_handler(message)

        if user['stage'] != Stage.geo:
            return  # ignore

        if (get_spherical_distance(lat, lon, config.LAT, config.LON) > config.RADIUS) or \
                (message.forward_from is not None):
            return await message.reply(t('GEO_FAILED', locale=user['lang']), reply_markup=keyboards.get_geo_kbd())
        else:
            await db.users.find_one_and_update({'uid': message.from_user.id}, {'$set': {'stage': Stage.menu}})
            await message.reply(t('GEO_SUCCESS', locale=user['lang']),
                                reply_markup=types.ReplyKeyboardRemove())
            await aq.aapi.add_user_to_queue(user['get_queue'], user['uid'])

            user_data = await aq.aapi.get_user_info(user['uid'])
            queues = user_data['queues']
            queue_id = user['get_queue']
            queue = list(filter(lambda x: queue_id == x['id'], queues))[0]

            await message.answer(t('USER_QUEUE_INFO', locale=user['lang'], queue_name=queue['name'],
                                   pos=queue['position']['relativePosition']),
                                 reply_markup=keyboards.get_update_my_queue_kbd(queue_id,
                                                                                user['lang']),
                                 parse_mode=types.ParseMode.HTML)