Exemplo n.º 1
0
async def product(callback: types.CallbackQuery, state: FSMContext):
    data = await state.get_data()
    if data == {}:
        await callback.message.edit_text('Что вы ищете?', reply_markup=clothes_kb.type_object)
        await callback.answer()
        await state.reset_data()
        return
    await callback.answer()
    await state.update_data(number=None)
    i = 0  # номер страницы товара
    p = False  # маркер выхода из меню товара в категории
    part = 'previous_part'
    if callback.data == 'product':
        callback.data = data['part']
        p = True
    if callback.data == 'next_part':
        part = callback.data
        callback.data = data['sex']
        i = 1
    elif callback.data == 'previous_part':
        part = callback.data
        callback.data = data['sex']
    await state.update_data(sex=callback.data, part=part)
    if p:
        await callback.message.edit_text('Выберите товар:', reply_markup=change[data['type']][callback.data][i])
        await callback.answer()
        return
    else:
        await callback.answer()
        await callback.message.edit_reply_markup(reply_markup=change[data['type']][callback.data][i])
        return
Exemplo n.º 2
0
    async def on_pre_process_callback_query(self, event: CallbackQuery,
                                            data: dict):
        proxy = StorageProxy(
            storage=self.storage,
            user_id=event.from_user.id,
            chat_id=event.message.chat.id,
            state_groups=self.state_groups,
        )
        data[STORAGE_KEY] = proxy

        original_data = event.data
        intent_id, callback_data = remove_indent_id(event.data)
        if intent_id:
            context = await proxy.load_context(intent_id)
            stack = await proxy.load_stack(context.stack_id)
            if stack.last_intent_id() != intent_id:
                logger.warning(
                    f"Outdated intent id ({intent_id}) for stack ({stack.id})")
                raise CancelHandler()
            event.data = callback_data
        else:
            context = None
            stack = await proxy.load_stack()
        data[STACK_KEY] = stack
        data[CONTEXT_KEY] = context
        data[CALLBACK_DATA_KEY] = original_data
Exemplo n.º 3
0
 async def set_default_mode(cls, c: CallbackQuery):
     user_db = ForwardsToTextUser(c.from_user.id)
     user_db.set_default_mode(c.data.split()[-1])
     try:
         c.data = 'fwd_to_text settings default_mode'
         await cls.start_setting_default_mode(c)
     except tg_excs.MessageNotModified:
         await bot.answer_callback_query(c.id, 'Ничего не изменено.')
Exemplo n.º 4
0
    async def query_handler(query: types.CallbackQuery):
        user = await db.users.find_one({'uid': query.from_user.id})
        if user is None:
            return await query.answer()

        if query.data.startswith('CertReg'):
            await db.users.find_one_and_update({'uid': user['uid']}, {'$set': {'stage': Stage.get_certnum}})
            return await query.message.edit_text(t('GET_CERTNUM'))

        elif query.data.startswith('ManualReg'):
            template = (await aq.aapi.get_registration_template())['template']
            num = len(template['tokens'])
            await db.users.find_one_and_update({'uid': user['uid']}, {'$set': {'stage': Stage.template,
                                                                               'template_stage': 0,
                                                                               'tokens_num': num,
                                                                               'template': template}})
            await query.message.answer(template['tokens'][0]['text'])

        elif query.data.startswith('AllQueues'):
            queues = (await aq.aapi.list_queues())['queues']
            num = len(list(filter(lambda x: x['active'], queues)))
            if num > 0:
                await query.message.edit_text(t('ALL_QUEUES', locale=user['lang']),
                                              reply_markup=keyboards.get_queues_kbd(queues, my_queues=False))
            else:
                await query.answer(t('NO_QUEUES', locale=user['lang']))

        elif query.data.startswith('MyQueues'):
            user_data = await aq.aapi.get_user_info(user['uid'])
            queues = user_data['queues']
            num = len(list(filter(lambda x: x['active'], queues)))
            if num > 0:
                await query.message.edit_text(t('MY_QUEUES', locale=user['lang']),
                                              reply_markup=keyboards.get_queues_kbd(queues, my_queues=True))
            else:
                await query.answer(t('NO_MY_QUEUES', locale=user['lang']))

        elif query.data.startswith('GetQueue'):
            user_data = await aq.aapi.get_user_info(user['uid'])
            queues = user_data['queues']
            queue_id = int(query.data.split('GetQueue', 1)[1])
            if any(map(lambda x: queue_id == x['id'], queues)):  # user already in queue
                query.data = f'GetMyQueue{queue_id}'  # edit data to pass query to GetMyQueue handler
                await query_handler(query)  # recursive call modified query
            else:
                await db.users.find_one_and_update({'uid': user['uid']},
                                                   {'$set': {'get_queue': queue_id, 'stage': Stage.geo}})
                return await query.message.answer(t('GEO', locale=user['lang']),
                                                  reply_markup=keyboards.get_geo_kbd(user['lang']))

        elif query.data.startswith('GetMyQueue'):
            user_data = await aq.aapi.get_user_info(user['uid'])
            queues = user_data['queues']
            queue_id = int(query.data.split('GetMyQueue', 1)[1])
            try:
                queue = list(filter(lambda x: queue_id == x['id'], queues))[0]
            except IndexError:
                return await query.answer(t('USER_NO_MORE_IN_QUEUE'), user['lang'])
            try:

                if queue['position']['status'] == 'processing':
                    return await query.message.edit_text(t('USER_QUEUE_PROCESSING', locale=user['lang'],
                                                           queue_name=queue['name']),
                                                         reply_markup=keyboards.get_update_my_queue_kbd(queue_id,
                                                                                                        user['lang']),
                                                         parse_mode=types.ParseMode.HTML)

                elif queue['position']['status'] == 'waiting':
                    return await query.message.edit_text(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)

                else:
                    logger.error('Unknown queue position status', queue['position']['status'])

            except exceptions.MessageNotModified:
                await query.answer(t('NO_UPDATES', locale=user['lang']))

        elif query.data.startswith('LeaveQueue'):
            queue_id = int(query.data.split('LeaveQueue', 1)[1])
            await db.users.find_one_and_update({'uid': user['uid']},
                                               {'$set': {'leave_queue': queue_id, 'stage': Stage.leave_queue}})
            return await query.message.edit_text(t('LEAVE_QUEUE'), reply_markup=keyboards.get_to_menu_kbd(user['lang']))

        elif query.data.startswith('RegInQueue'):
            queue_id = int(query.data.split('RegInQueue', 1)[1])
            await aq.aapi.add_user_to_queue(user['uid'], queue_id)
            await query.message.edit_text(t('REGISTER_IN_QUEUE_SUCCESS', locale=user['lang']),
                                          reply_markup=keyboards.get_menu_kbd(user['lang']))

        elif query.data.startswith('Menu'):
            await db.users.find_one_and_update({'uid': user}, {'$set': {'stage': Stage.menu}})
            await query.message.edit_text(t('MENU', locale=user['lang']),
                                          reply_markup=keyboards.get_menu_kbd(user['lang']),
                                          parse_mode=types.ParseMode.HTML)

        elif query.data.startswith('ChangeData'):
            await db.users.delete_one({'uid': user['uid']})
            await start_handler(query.message)
            await query.message.delete_reply_markup()

        else:
            logger.warning(f'Got invalid command {query.data}')

        await query.answer()
Exemplo n.º 5
0
 async def remove_markers_dict(cls, c: CallbackQuery):
     user_db = ForwardsToTextUser(c.from_user.id)
     user_db.delete_dictionary(int(c.data.split()[-1]))
     c.data = 'fwd_to_text settings dicts'
     await cls.edit_dicts_settings(c=c)
Exemplo n.º 6
0
async def product_show(callback: types.CallbackQuery, state: FSMContext):
    data = await state.get_data()
    if data == {}:
        await callback.message.edit_text('Что вы ищете?', reply_markup=clothes_kb.type_object)
        await callback.answer()
        await state.reset_data()
        return
    notification = False  # уведомление о единственном товаре при листании товаров
    now_state = await state.get_state()
    if not data['number']:  # номер товара в списке пользователя
        number = 0
    else:
        number = data['number']
    if callback.data == 'next_product':
        number += 1
        notification = True
        callback.data = data['product']
    elif callback.data == 'previous_product':
        number -= 1
        notification = True
        callback.data = data['product']
    if ('States:set_category', 'States:sales2cat_add', 'States:sales2cat_end').count(now_state):
        logging.info(f"{data['type']}, {data['sex']}, {callback.data}")
        await callback.message.edit_text(f"Тип: {category[data['type']]} "
                                         f"\nПол: {category[data['sex']]} "
                                         f"\nКатегория: {category[callback.data]}",
                                         reply_markup=accept_kb)
        await state.update_data(product=callback.data)
        await callback.answer()
        # logging.info(f'Получение продукта до запроса в бд - {time()-t}')
        return
    # logging.info(f'Получение продукта до запроса в бд - {time()-t}')
    t = time()
    try:
        res = await get_product(data['sex'], callback.data, number)
    except KeyError:
        await callback.message.edit_text('Что вы ищете?', reply_markup=clothes_kb.type_object)
        await callback.answer()
        await state.reset_data()
        return
    logging.info(f'Запрос в бд {time() - t}')
    if res is False:
        await callback.answer(text='Этого товара еще нет :( ', cache_time=1)
        # logging.info(f'Получение продукта после запроса - {time()-t}')
        return
    elif res[0][9] == -1:
        number = 0
    elif res[0][9] >= 0:
        number = res[0][8]
    elif res[0][9] == -2 and notification is True:
        await callback.answer(text='Других товаров нет', cache_time=1)
        # logging.info(f'Получение продукта после запроса - {time()-t}')
        return
    kb = product_kb
    if now_state == 'States:edit_product':
        kb = edit_product_inline
    elif now_state == 'States:delete_product':
        kb = delete_product_inline
    # logging.info(f'Получение продукта после запроса - {time()-t}')
    await callback.message.edit_text(res[0][4] + str(res[0][2]) + res[0][1], parse_mode='HTML', reply_markup=kb)
    await state.update_data(product=callback.data, number=number)
    await callback.answer()
Exemplo n.º 7
0
    async def on_process_callback_query(update: CallbackQuery, _):

        _, callback_value = factory.parse_callback_data(update.data)
        update.data = callback_value
Exemplo n.º 8
0
async def back(call: CallbackQuery, state: FSMContext):
    data = await state.get_data()
    item_id = data["item_id"]
    call.data = "add_item_" + str(item_id)

    await show_sizes(call, state)
async def back_to_campuses_from_courses(callback_query: CallbackQuery,
                                        user_data: Tuple[Campus, Peer, User]):
    query = callback_query.data
    callback_query.data = query[query.index('.') + 1:]
    await courses(callback_query=callback_query, user_data=user_data)