Exemplo n.º 1
0
 def diet(self):
     kb = InlineKeyboardMarkup(row_width=2)
     calories_btn = InlineKeyboardButton(text=' Калории',
                                         callback_data='calories')
     kb.row(calories_btn)
     kb.add(self.back_btn)
     return kb
Exemplo n.º 2
0
async def items_keyboard(category: str, level: int = 2):
    CURRENT_LEVEL = level

    # Set row_width = 1 to show one button per row per item
    markup = InlineKeyboardMarkup(row_width=1)

    # Take a list of goods from the database
    items = await get_items(category)
    for item in items:
        # Form the button text
        button_text = f"{item.name} {item.emodji}"

        # Form a button callback data
        callback_data = make_callback_data(level=CURRENT_LEVEL + 1,
                                           category=category,
                                           item_id=item.id)
        markup.insert(
            InlineKeyboardButton(text=button_text,
                                 callback_data=callback_data))

    # Create a Back button
    markup.row(
        InlineKeyboardButton(text='Назад 🔙',
                             callback_data=make_callback_data(
                                 level=CURRENT_LEVEL - 1, category=category)))
    return markup
Exemplo n.º 3
0
async def handle_start_command(message: types.Message, state: FSMContext):
    """Handle /start.

    Ask for language if user is new or show menu.
    """
    user = {"id": message.from_user.id, "chat": message.chat.id}
    result = await database.users.update_one(user, {"$setOnInsert": user}, upsert=True)

    if not result.matched_count:
        keyboard = InlineKeyboardMarkup()
        for language in i18n.available_locales:
            keyboard.row(
                InlineKeyboardButton(
                    Locale(language).display_name,
                    callback_data="locale {}".format(language),
                )
            )
        await tg.send_message(
            message.chat.id, i18n("choose_language"), reply_markup=keyboard
        )
        return

    await state.finish()
    await tg.send_message(
        message.chat.id, i18n("help_message"), reply_markup=start_keyboard()
    )
Exemplo n.º 4
0
async def adminMessageAll(message: types.Message):
    '''
    Admin messages
    :param message:
    :return:
    '''

    adm_user = privelege_user(message)
    if adm_user != []:
        if str(message.chat.id) == str(adm_user[2]):
            answer_adm = all_messages_from_base(adm_user[3])
            if answer_adm != []:
                for i in range(len(answer_adm)):
                    #btn_yes = InlineKeyboardButton('Одобрить',  callback_data="Y|"+str(answer_adm[i][0]))
                    btn_no = InlineKeyboardButton('Удалить',
                                                  callback_data="D|" +
                                                  str(answer_adm[i][0]))
                    inline_kb_full = InlineKeyboardMarkup(row_width=2)
                    inline_kb_full.row(btn_no)
                    #if i % 10 == 0:
                    #    time.sleep(3)
                    await message.answer(answer_adm[i][1],
                                         reply_markup=inline_kb_full)

            else:
                await message.answer("Новых сообщений в предложку нет")
        else:
            await message.reply("Для этой комманды перейдите в ЛС бота")
 def managing_courses_additionaly(user:User) -> InlineKeyboardMarkup():
     """Клавиатура для подтверждния или отмены созданного курса"""
     keyboard = InlineKeyboardMarkup()
     butt_complete = InlineKeyboardButton(get_text_but(user, 'managing_courses_add_additionaly_complete'), callback_data="managing_courses_add_additionaly_complete")
     butt_cancel = InlineKeyboardButton(get_text_but(user, 'managing_courses_add_additionaly_cancel'), callback_data="managing_courses_add_additionaly_cancel")
     keyboard.row(butt_complete, butt_cancel)
     return keyboard
Exemplo n.º 6
0
def search_results_keyboard(results, page, per_page=5):
    kb = InlineKeyboardMarkup(2)
    total_pages = ceil(len(results) / per_page)
    start = (page - 1) * per_page
    stop = start + per_page
    last_page = page == total_pages
    for i, result in enumerate(results[start:stop], start=start):
        kb.insert(
            InlineKeyboardButton(
                f'{i+1}. {result.artist.name} - {result.title}',
                callback_data=new_callback('track_deezer', result.id, 'send')))
        kb.row()
    if page != 1:
        kb.insert(
            InlineKeyboardButton('◀️',
                                 callback_data=new_callback('page', page - 1)))
    if not last_page:
        kb.insert(
            InlineKeyboardButton('️️▶️',
                                 callback_data=new_callback('page', page + 1)))
    kb.row(
        InlineKeyboardButton(text='Deezer ✅',
                             callback_data=new_callback('page', 1)),
        InlineKeyboardButton(text='SoundCloud ☑️',
                             callback_data=new_callback('sc_page', 1)))
    return kb
Exemplo n.º 7
0
async def allAdmins(message: types.Message):
    """
    adm_user[2] - id tgm_user_id (Admin  user)
    adm_user[3] - id tgm_chat_id
    :param message:
    :return:
    """

    adm_user = privelege_user(message)
    if adm_user != []:

        if str(message.chat.id) == str(adm_user[2]):
            # print(adm_user)

            all_admins = get_all_admins(adm_user[3])

            for i in range(len(all_admins)):

                btn_del = InlineKeyboardButton('Удалить',
                                               callback_data="FDA|" +
                                               str(all_admins[i][2]) + '|' +
                                               str(all_admins[i][3]))
                inline_kb_full = InlineKeyboardMarkup()
                inline_kb_full.row(btn_del)
                await message.answer("[" + all_admins[i][1] + "](tg://user?=" +
                                     all_admins[i][3] + ")",
                                     reply_markup=inline_kb_full,
                                     parse_mode='markdown')
        else:
            await message.reply(
                "Для этой комманды перейдите в личный чат с ботом")
Exemplo n.º 8
0
async def replier_actions_markup(user_id, account, replier):
    current_level = 2

    markup = InlineKeyboardMarkup(row_width=2)
    callback_data = make_callback_data(level=current_level + 1,
                                       account=account,
                                       replier=replier,
                                       action='delete')
    markup.insert(
        InlineKeyboardButton(text='🗑 Удалить', callback_data=callback_data))
    callback_data = make_callback_data(level=current_level + 1,
                                       account=account,
                                       replier=replier,
                                       action='turn_status')
    if await replier_is_working(user_id=user_id, name=replier,
                                account=account):
        markup.insert(
            InlineKeyboardButton(text='🔴 Выключить',
                                 callback_data=callback_data))
    else:
        markup.insert(
            InlineKeyboardButton(text='🟢 Включить',
                                 callback_data=callback_data))
    markup.row(
        InlineKeyboardButton(text="↩️ Назад",
                             callback_data=menu_cd.new(level=1,
                                                       category="replier",
                                                       subcategory="0",
                                                       action="0")))
    return markup
Exemplo n.º 9
0
async def get_car_image_and_mrakup(images, page, car_pk, img_idx=0):
    image = None
    markup = InlineKeyboardMarkup()
    if images:
        if img_idx:
            markup.insert(
                InlineKeyboardButton(text='⬅️',
                                     callback_data=ImageArrowsCallback.new(
                                         img_idx - 1, )))
        markup.insert(
            InlineKeyboardButton(text='Назад',
                                 callback_data=f'back_to_car_update'))
        if img_idx < len(images) - 1:
            markup.insert(
                InlineKeyboardButton(text='➡️',
                                     callback_data=ImageArrowsCallback.new(
                                         img_idx + 1, )))
        image = images[img_idx]
        markup.row(
            InlineKeyboardButton('Удалить', callback_data='delete_car_img'))
    else:
        markup.insert(
            InlineKeyboardButton(text='Назад',
                                 callback_data=f'back_to_car_update'))
    markup.row(
        InlineKeyboardButton(text="Добавить фото",
                             callback_data='add_car_img'))
    return image, markup
Exemplo n.º 10
0
async def update_chapters(query: types.CallbackQuery):
    """Returns chapters for book `book_id` in range [ (page-1)*page_size; page*page_size ]."""
    # Parse query
    request = query.data.split('_')
    book_id = int(request[1])
    page = int(request[2])
    respond = True if request[-1] == 'respond' else False

    message = get_chapters(book_id, page)
    inline_keyboard = InlineKeyboardMarkup()
    inline_keyboard.row(
        InlineKeyboardButton('<',
                             callback_data=f'/chapters_{book_id}_{page-1}'),
        InlineKeyboardButton('>',
                             callback_data=f'/chapters_{book_id}_{page+1}'))

    await query.answer('')
    if not message:
        return
    if respond:
        await bot.send_message(query.from_user.id,
                               text=message,
                               reply_markup=back_menu)
    else:
        bot.edit_message_text(text=message,
                              inline_message_id=query.inline_message_id)
Exemplo n.º 11
0
async def see_reviews_channel_keyboard(**kwargs):
    markup = InlineKeyboardMarkup()
    markup.row(
        InlineKeyboardButton(
            'Посмотреть отзывы',
            url=f'http://t.me/{REVIEWS_CHANNEL.replace("@", "")}'))
    return markup
async def items_keyboard(category, subcategory):
    CURRENT_LEVEL = 2

    # Устанавливаю row_width = 1, чтобы показывалась одна кнопка в строке на товар
    markup = InlineKeyboardMarkup(row_width=1)

    # Забираем список товаров из базы данных с выбранной категорией и подкатегорией, и проходим по нему
    items = await get_items(category, subcategory)
    for item in items:
        # Сформируем текст, который будет на кнопке
        button_text = f"{item.name} - ${item.price}"

        # Сформируем колбек дату, которая будет на кнопке
        callback_data = make_callback_data(level=CURRENT_LEVEL + 1,
                                           category=category,
                                           subcategory=subcategory,
                                           item_id=item.id)
        markup.insert(
            InlineKeyboardButton(text=button_text,
                                 callback_data=callback_data))

    # Создаем Кнопку "Назад", в которой прописываем колбек дату такую, которая возвращает
    # пользователя на уровень назад - на уровень 1 - на выбор подкатегории
    markup.row(
        InlineKeyboardButton(text="Назад",
                             callback_data=make_callback_data(
                                 level=CURRENT_LEVEL - 1, category=category)))
    return markup
async def subcategories_keyboard(category):
    # Текущий уровень - 1
    CURRENT_LEVEL = 1
    markup = InlineKeyboardMarkup()

    # Забираем список товаров с РАЗНЫМИ подкатегориями из базы данных с учетом выбранной категории и проходим по ним
    subcategories = await get_subcategories(category)
    for subcategory in subcategories:
        # Чекаем в базе сколько товаров существует под данной подкатегорией
        number_of_items = await count_items(
            category_code=category,
            subcategory_code=subcategory.subcategory_code)

        # Сформируем текст, который будет на кнопке
        button_text = f"{subcategory.subcategory_name} ({number_of_items} шт)"

        # Сформируем колбек дату, которая будет на кнопке
        callback_data = make_callback_data(
            level=CURRENT_LEVEL + 1,
            category=category,
            subcategory=subcategory.subcategory_code)
        markup.insert(
            InlineKeyboardButton(text=button_text,
                                 callback_data=callback_data))

    # Создаем Кнопку "Назад", в которой прописываем колбек дату такую, которая возвращает
    # пользователя на уровень назад - на уровень 0.
    markup.row(
        InlineKeyboardButton(
            text="Назад",
            callback_data=make_callback_data(level=CURRENT_LEVEL - 1)))
    return markup
Exemplo n.º 14
0
async def notify_waiting_for_ticker(message: types.Message, state: FSMContext):
    logging.debug(f'Log from {notify_waiting_for_ticker} {message.text}')
    if not message.text.lower():
        msg_body = "Введите TICKER акции (" + MarkdownFormatter.italic("например, SBER") + "):"
        await message.reply(full_message(1, msg_body))
        return

    try:
        stocks = await StockService().find_stock_by_ticker(ticker=message.text.upper())
        if stocks and len(stocks) > 0:
            current_stock = stocks.pop()
            logger.debug(f'Current stock: {current_stock}')
            msg_body = MarkdownMessageBuilder(current_stock).build_stock_find_message()
            logger.debug(f'Msg body: {msg_body}')
            await state.update_data(rest_stocks=stocks, ticker=message.text.upper(), current_stock=current_stock)
            await OrderNotification.waiting_for_approve_stock.set()
            approve_keyboard = InlineKeyboardMarkup(row_width=3)
            approve_keyboard.row(*[InlineKeyboardButton(i, callback_data=i) for i in approve_options])
            await message.answer(full_message(2, msg_body), parse_mode="Markdown",
                                 reply_markup=approve_keyboard)
        else:
            await message.reply(f'По тикеру {message.text} ничего не найдено. Пожалуйста, поверьте привильность тикера.')
    except HTTPStatusError as err:
        logger.error(f'Error trying to find stock with: {err.response.status_code}')
        await message.reply(f'Ошибка при поиске по тикеру {message.text}. Пожалуйста, попробуйте позднее.')
Exemplo n.º 15
0
 async def get_kbd(self, current_state: str, current_step: Step,
                   current_data: Dict, args, kwargs):
     kbd = await current_step.render_kbd(current_data, *args, **kwargs)
     if not kbd:
         kbd = InlineKeyboardMarkup()
     steps_row = []
     if self.can_back(current_state, current_step):
         steps_row.append(
             InlineKeyboardButton(text="< Назад",
                                  callback_data=self.back_cd))
     if self.can_skip(current_step):
         steps_row.append(
             InlineKeyboardButton(text="Пропустить >",
                                  callback_data=self.skip_cd))
     if steps_row:
         kbd.row(*steps_row)
     finish_row = []
     if self.can_cancel(current_step):
         finish_row.append(
             InlineKeyboardButton(text="Отмена",
                                  callback_data=self.cancel_cd))
     if self.can_done(current_step):
         finish_row.append(
             InlineKeyboardButton(text="✓ Готово",
                                  callback_data=self.done_cd))
     if finish_row:
         kbd.row(*finish_row)
     return kbd
Exemplo n.º 16
0
async def send_find(message: types.Message):
    file_name = message.text.split(" ", 1)[-1]
    #print(file_name)
    if file_name != "/find":
        if len(file_name) >= 3:
            files = await loop.create_task(db.find_file_by_name(file_name))
            if len(files) > 0:
                files_kb = InlineKeyboardMarkup()
                for n, i in enumerate(files):
                    if n < 5:
                        files_kb.add(
                            InlineKeyboardButton(i['file_name'],
                                                 callback_data="file=" +
                                                 i['file_id']))
                if len(files) > 5:
                    files_kb.row(
                        InlineKeyboardButton("1", callback_data="page=1"),
                        InlineKeyboardButton(_("Дальше >>"),
                                             callback_data="next_all=" +
                                             file_name + "=" + str(5)))
                await message.reply(_("Документы"), reply_markup=files_kb)
            else:
                await message.reply(_("Ничего не нашел :("))
        else:
            await message.reply(_("Минимум 3 буквы для поиска"))
    else:
        await message.reply(
            _("Чтобы воспользоваться командой напиши /find имя_файла"))
Exemplo n.º 17
0
async def sum_handler(call: types.CallbackQuery):
    """Ask for sum currency."""
    order = await database.creation.find_one_and_update(
        {"user_id": call.from_user.id}, {"$unset": {
            "price_currency": True
        }})

    if not order:
        await call.answer(i18n("no_creation"))
        return True

    keyboard = InlineKeyboardMarkup()
    keyboard.add(
        InlineKeyboardButton(order["buy"], callback_data="sum buy"),
        InlineKeyboardButton(order["sell"], callback_data="sum sell"),
    )
    for row in await inline_control_buttons():
        keyboard.row(*row)

    await tg.edit_message_text(
        i18n("ask_sum_currency"),
        call.message.chat.id,
        call.message.message_id,
        reply_markup=keyboard,
    )
Exemplo n.º 18
0
async def process_file_name(message: types.Message, state: FSMContext):
    """
    Process file name
    """
    if message.text != "/cancel":
        files = await loop.create_task(db.find_file_by_name(message.text))
        #print(files)
        if len(files) > 0:
            files_kb = InlineKeyboardMarkup()
            for n, i in enumerate(files):
                if n < 5:
                    files_kb.add(
                        InlineKeyboardButton(i['file_name'],
                                             callback_data="file=" +
                                             i['file_id']))
            if len(files) > 5:
                files_kb.row(
                    InlineKeyboardButton("1", callback_data="page=1"),
                    InlineKeyboardButton("Дальше >>",
                                         callback_data="next_all=" +
                                         message.text + "=" + str(5)))
            await message.reply(_("Документы"), reply_markup=files_kb)
        else:
            await message.reply(_("Ничего не нашел :("))
        await state.finish()
    else:
        await message.reply(_("Отмена поиска."))
        await state.finish()
Exemplo n.º 19
0
def search_keyboard(page=1):
    """Строит клавиатуру для начала поиска"""
    keyboard = InlineKeyboardMarkup()
    keyboard.row(
        InlineKeyboardButton('Начать поиск', callback_data=f'search:{page}'))
    keyboard.row(InlineKeyboardButton('Вернуться назад', callback_data='back'))
    return keyboard
Exemplo n.º 20
0
def web():
    keyboard = InlineKeyboardMarkup()
    keyboard.row(InlineKeyboardButton("🔥 Дешёвые 🔥", callback_data='sms-hub'))
    keyboard.row(
        InlineKeyboardButton("✅ Проверенные ✅", callback_data='sms-activate'))
    #keyboard.row(InlineKeyboardButton("sms-online", callback_data='sms-online'))
    return keyboard
Exemplo n.º 21
0
async def adminMessage(message: types.Message):
    '''
    I don't know WTF function
    :param message:
    :return:
    '''
    adm_user = privelege_user(message)

    if adm_user != []:
        if str(message.chat.id) == str(adm_user[2]):
            cursor.execute(
                "SELECT * FROM messages WHERE tgm_chat_id=? AND status='N' LIMIT 10",
                [adm_user[3]])
            conn.commit()
            answer_adm = cursor.fetchall()

            if answer_adm != []:
                for i in range(len(answer_adm)):
                    btn_yes = InlineKeyboardButton('Одобрить',
                                                   callback_data="Y|" +
                                                   str(answer_adm[i][0]))
                    btn_no = InlineKeyboardButton('Удалить',
                                                  callback_data="N|" +
                                                  str(answer_adm[i][0]))
                    inline_kb_full = InlineKeyboardMarkup(row_width=2)
                    inline_kb_full.row(btn_yes, btn_no)
                    await message.answer(answer_adm[i][1],
                                         reply_markup=inline_kb_full)

            else:
                await message.answer("Новых сообщений в предложку нет")
        else:
            await message.reply("Для этой комманды перейдите в ЛС бота")
    out_base("messages")
Exemplo n.º 22
0
Arquivo: ui.py Projeto: ne-bknn/CSSH
async def kb_images_picker(page: int) -> Optional[InlineKeyboardMarkup]:
    keyboard = InlineKeyboardMarkup(row_width=1)
    db = await InterfaceDB.create_tmp(DB_CONN)

    images = await db.get_images()
    images_to_add = images[page * 5:page * 5 + 5]

    if page == 0 and len(images_to_add) == 0:
        await db.close()
        return None

    for image in images_to_add:
        keyboard.add(
            InlineKeyboardButton(image, callback_data=f"picked_image:{image}"))

    none_button = InlineKeyboardButton(" ", callback_data=" ")

    row = [none_button, none_button]

    if page != 0:
        row[0] = InlineKeyboardButton(
            "<", callback_data=f"next_image_list:{page-1}")

    if not (len(images_to_add) < 5
            or len(images[(page + 1) * 5:(page + 1) * 5 + 5]) == 0):
        row[1] = InlineKeyboardButton(
            ">", callback_data=f"next_image_list:{page+1}")

    if any(button != none_button for button in row):
        keyboard.row(*row)

    await db.close()
    return keyboard
Exemplo n.º 23
0
async def rootAdmins(message: types.Message):
    adm_user = privelege_user(message)
    if adm_user != []:
        if str(message.chat.id) == str(adm_user[2]):
            tgm_chat_id_user = adm_user[3]
            candidate = get_new_admins(adm_user[3])
            if candidate != []:
                #print("Candidate found: ", candidate)
                for i in range(len(candidate)):
                    candidate_string = "[" + candidate[i][
                        1] + "](tg://user?id='" + candidate[i][
                            2] + "') кандидат в Админы"
                    btn_yes = InlineKeyboardButton(
                        "Одобрить",
                        callback_data='YA|' +
                        str(candidate[i][2] + '|' + candidate[i][3]))
                    btn_no = InlineKeyboardButton(
                        "Отклонить",
                        callback_data='YA|' +
                        str(candidate[i][2] + '|' + candidate[i][3]))

                    kb_lay = InlineKeyboardMarkup(row_width=2)
                    kb_lay.row(btn_yes, btn_no)
                    await message.answer(candidate_string,
                                         reply_markup=kb_lay,
                                         parse_mode="markdown")
            else:
                await message.answer("Новых заявок на Админа нет",
                                     parse_mode="markdown")
        else:
            await message.reply("Для этой комманды перейдите в ЛС бота")

    else:
        await message.answer("Доступ запрещен")
Exemplo n.º 24
0
async def preview_keyboard(section_name, dater):
    CURRENT_LEVEL = 2

    markup = InlineKeyboardMarkup(row_width=1)

    markup.insert(
        InlineKeyboardButton(text="Заголовок и превью",
                             callback_data=make_callback_data(
                                 level=CURRENT_LEVEL + 1,
                                 section_name=section_name,
                                 dater=dater,
                                 preview=False)))
    markup.insert(
        InlineKeyboardButton(text="Только заголовок",
                             callback_data=make_callback_data(
                                 level=CURRENT_LEVEL + 1,
                                 section_name=section_name,
                                 dater=dater,
                                 preview=True)))
    markup.row(
        InlineKeyboardButton(text="Назад",
                             callback_data=make_callback_data(
                                 level=CURRENT_LEVEL - 1,
                                 section_name=section_name)))

    markup.row(InlineKeyboardButton(text="Отмена", callback_data="cancel"))

    return markup
Exemplo n.º 25
0
async def get_keyboard(page: int, pages_count: int,
                       keyboard_type: str) -> Optional[InlineKeyboardMarkup]:
    if pages_count == 1:
        return None
    keyboard = InlineKeyboardMarkup()

    first_row = []
    second_row = []

    if page > 1:
        prev_page = max(1, page - BOOKS_CHANGER)
        if prev_page != page - 1:
            second_row.append(
                InlineKeyboardButton(
                    f'<< {prev_page}',
                    callback_data=f'{keyboard_type}_{prev_page}'))
        first_row.append(
            InlineKeyboardButton('<',
                                 callback_data=f'{keyboard_type}_{page - 1}'))

    if page != pages_count:
        next_page = min(pages_count, page + BOOKS_CHANGER)
        if next_page != page + 1:
            second_row.append(
                InlineKeyboardButton(
                    f'>> {next_page}',
                    callback_data=f'{keyboard_type}_{next_page}'))
        first_row.append(
            InlineKeyboardButton('>',
                                 callback_data=f'{keyboard_type}_{page + 1}'))

    keyboard.row(*first_row)
    keyboard.row(*second_row)

    return keyboard
Exemplo n.º 26
0
def profile_keyboard(tracks, profile_id, page, per_page=7):
    kb = InlineKeyboardMarkup(2)
    total_pages = ceil(len(tracks) / per_page)
    start = (page - 1) * per_page
    stop = start + per_page
    last_page = page == total_pages

    for i, track in enumerate(tracks[start:stop], start=start):
        kb.row(
            InlineKeyboardButton(f'{i+1}. {track.artist} - {track.title}',
                                 callback_data=new_callback(
                                     'vk_track', track.full_id, 'send')))
    kb.row()
    if page != 1:
        kb.insert(
            InlineKeyboardButton('◀️',
                                 callback_data=new_callback(
                                     'vk_profile_audio_page', profile_id,
                                     page - 1)))
    if not last_page:
        kb.insert(
            InlineKeyboardButton('️️▶️',
                                 callback_data=new_callback(
                                     'vk_profile_audio_page', profile_id,
                                     page + 1)))
    return kb
async def items_keyboard(category):
    CURRENT_LEVEL = 1

    markup = InlineKeyboardMarkup(row_width=1)

    items = await get_items(category)
    for item in items:

        button_text = f"{item.name}"

        callback_data = make_callback_data(
            level=CURRENT_LEVEL + 1,
            category=category,
            item_id=item.id,
        )
        markup.insert(
            InlineKeyboardButton(text=button_text,
                                 callback_data=callback_data))

    markup.row(
        InlineKeyboardButton(text="← Назад",
                             callback_data=make_callback_data(
                                 level=CURRENT_LEVEL - 1,
                                 category=category,
                             )))
    return markup
Exemplo n.º 28
0
    async def execute(cls, c: CallbackQuery):
        offset = int(c.data.split()[-2])

        player = Player(tg_id=c.from_user.id)
        items = list(player.backpack.items())
        kb = InlineKeyboardMarkup(row_width=2)
        n = 0
        for item_id, item_quantity in items[offset:]:
            if item_quantity <= 0:
                continue
            item = Item(id=ObjectId(item_id))
            item.update_from_db()
            button = InlineKeyboardButton(f'{item.emoji or ""} {item.name} {item_quantity}',
                                          callback_data=f'item observe backpack {item_id} {c.from_user.id}')
            kb.add(button)
            n += 1
            if n == PAGE_OFFSET:
                break
        close = InlineKeyboardButton('✖', callback_data=f"close_menu {c.from_user.id}")
        backward = InlineKeyboardButton('<-', callback_data=f"backpack offset {offset - PAGE_OFFSET} {c.from_user.id}")
        forward = InlineKeyboardButton('->', callback_data=f"backpack offset {offset + PAGE_OFFSET} {c.from_user.id}")
        buttons = [close]
        if offset > 0:
            buttons.insert(0, backward)
        if len(items) > offset + PAGE_OFFSET:
            buttons.append(forward)
        kb.row(*buttons)

        await c.message.edit_reply_markup(reply_markup=kb)
Exemplo n.º 29
0
def profile_main() -> InlineKeyboardMarkup:
    keyboard = InlineKeyboardMarkup(resize_keyboard=True)
    change_button = InlineKeyboardButton(
        'Сменить имя',
        callback_data=change_name_callback.new(action='change_name'))
    keyboard.row(change_button)
    return keyboard
Exemplo n.º 30
0
def catalogueList(array: list,
                  confirmButtonCallbackType: str,
                  rowCount: int = 5) -> InlineKeyboardMarkup:
    catalogue = InlineKeyboardMarkup(row_width=rowCount)

    for row in range(0, int(math.ceil(len(array))), rowCount):
        rowList: list = []

        for item in range(0, rowCount):
            try:
                currentItem: FormItem = array[row + item]
            except IndexError:
                break

            itemText = currentItem.data['title']

            itemButton = InlineKeyboardButton(
                text=f'☑️{itemText}' if currentItem.isSelected else itemText,
                callback_data=currentItem.data['id'])

            rowList.append(itemButton)

        catalogue.row(*rowList)

    catalogue.add(confirmInlineButton(confirmButtonCallbackType))

    return catalogue