F
F
FailureBij2021-07-30 14:27:03
Python
FailureBij, 2021-07-30 14:27:03

How to simplify the code of inline buttons?

There is a very huge code with 150 inline telegram bot aiogram buttons
, here is a fragment of one callback (there are 5 of them). How can this be simplified? I didn’t figure out whether it’s possible to somehow make inline buttons in the form of a list, that is, you click on 2/3, it flips to 8 buttons, you press 3/3, it flips to another 8 buttons

@dp.callback_query_handler(text_contains='tr33')
async def ibresp25(call: types.CallbackQuery):

    conn = sqlite3.connect("tred.db")
    cur = conn.cursor()
    cur.execute("SELECT titl FROM bvd")
    s = cur.fetchall()

    tr9 = InlineKeyboardButton(f"{s[9][0]}", callback_data="tr10")
    tr10 = InlineKeyboardButton(f"{s[10][0]}", callback_data="tr11")
    tr11 = InlineKeyboardButton(f"{s[11][0]}", callback_data="tr12")
    tr12 = InlineKeyboardButton(f"{s[12][0]}", callback_data="tr13")
    tr13 = InlineKeyboardButton(f"{s[13][0]}", callback_data="tr14")
    tr14 = InlineKeyboardButton(f"{s[14][0]}", callback_data="tr15")
    tr15 = InlineKeyboardButton(f"{s[15][0]}", callback_data="tr16")
    tr16 = InlineKeyboardButton(f"{s[16][0]}", callback_data="tr17")

    tr1111 = InlineKeyboardButton(f"1/3", callback_data="trr0")
    tr222 = InlineKeyboardButton(f"⬅️ Назад", callback_data="btn9")
    tr3333 = InlineKeyboardButton(f"3/3", callback_data="tr44")

    tradeee = InlineKeyboardMarkup(resize_keyboard=True)
    tradeee.add(tr9 )
    tradeee.add(tr10)
    tradeee.add(tr11)
    tradeee.add(tr12)
    tradeee.add(tr13)
    tradeee.add(tr14)
    tradeee.add(tr15)
    tradeee.add(tr16)
    tradeee.add(tr1111, tr222, tr3333)

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Mikhail Krostelev, 2021-07-30
@twistfire92

initialization and adding buttons tr9 - tr16 can be simplified as follows:

buttons = []
for number in range(9, 17):
    buttons.append(InlineKeyboardButton(f"{s[number][0]}", callback_data=f"tr{number+1}"))

........

tradeee.add(*buttons)

You can think of pagination yourself. I would bring the filling of the button markup into a separate function. As a parameter, you pass the "page number" there, and you dance from this.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question