0

Создаю телеграм бота и столкнулся с проблемой подсчета количества значений что бы вывести Inline клавиатуру. У меня есть list и данными которые могут меняться и мне нужно вывести в Inline клавиатуру все имена и адреса, вот только я хотел бы что бы эта клавиатура подстраивалась под количество значения(Я знаю как создать что бы просто выводились все имена и адреса. Но мне надо что бы у каждой кнопки был свой callback)

    text={'id': 'fd65865b-0f43-468b-80a5-04d5c9f90086', 'vendorId': '232231', 'name': 'магазин-кафетерій', 'location': {'settlement': 'Київ', 'addressLine': 'м.Київ вул.А.Ахматової 35'}, 'freeVisit': False}, {'id': '2a2d898c-853c-453b-a8c3-0acd0e1ebc8a', 'vendorId': '232830', 'name': 'магазин', 'location': {'settlement': 'Київ', 'addressLine': 'м.Київ вул.Радунська,13-А'}, 'freeVisit': False}, {'id': 'c1f3d061-6d8b-44c0-a0e7-0fbf52131a7a', 'vendorId': '231046', 'name': 'магазин', 'location': {'settlement': 'Гнідин', 'addressLine': 'м.Київ вул.садова,4'}, 'freeVisit': False}, {'id': '3afbf5d0-7dd5-4c15-b516-10fd96fa3c35', 'vendorId': '230917', 'name': 'магазин', 'location': {'settlement': 'Київ', 'addressLine': 'Бориспільський р-н, с.Гнідин, івул.Центральна 98'}, 'freeVisit': False},...]
lenname=[i.split("name")[0] for i in text]
    print(lenname)



        #bot.send_message(message.chat.id, str(i) + ". " + str(name) + ",    " "Адрес торг.точки:  "+str(address))

    selectKeyboard = telebot.types.InlineKeyboardMarkup( row_width=1)

    if 0<lenname<2:
        for i in range(len(text)):
            one=types.InlineKeyboardButton(text=str(text[0]['name'])+"  "+str(text[0]['location']['addressLine']),callback_data="first")

        selectKeyboard.add(one)

    if 2<lenname<3:
        for i in range(len(text)):
            one=types.InlineKeyboardButton(text=str(text[0]['name'])+"  "+str(text[0]['location']['addressLine']),callback_data="first")
            two=types.InlineKeyboardButton(text=str(text[1]['name'])+"  "+str(text[1]['location']['addressLine']),callback_data="second")

        selectKeyboard.add(one,two)

    if 3<lenname<4:
        for i in range(len(text)):
            one=types.InlineKeyboardButton(text=str(text[0]['name'])+"  "+str(text[0]['location']['addressLine']),callback_data="first")
            two=types.InlineKeyboardButton(text=str(text[1]['name'])+"  "+str(text[1]['location']['addressLine']),callback_data="second")
            three = types.InlineKeyboardButton(text=str(text[2]['name']) + "  " + str(text[2]['location']['addressLine']),
                                             callback_data="three")

        selectKeyboard.add(one,two,three)

    if 4<lenname<5:
        for i in range(len(text)):
            one=types.InlineKeyboardButton(text=str(text[0]['name'])+"  "+str(text[0]['location']['addressLine']),callback_data="first")
            two=types.InlineKeyboardButton(text=str(text[1]['name'])+"  "+str(text[1]['location']['addressLine']),callback_data="second")
            three = types.InlineKeyboardButton(text=str(text[2]['name']) + "  " + str(text[2]['location']['addressLine']),
                                             callback_data="three")
            four = types.InlineKeyboardButton(text=str(text[3]['name']) + "  " + str(text[3]['location']['addressLine']),
                                             callback_data="four")

        selectKeyboard.add(one,two,three,four)

    if 5<lenname<6:
        for i in range(len(text)):
            one=types.InlineKeyboardButton(text=str(text[0]['name'])+"  "+str(text[0]['location']['addressLine']),callback_data="first")
            two=types.InlineKeyboardButton(text=str(text[1]['name'])+"  "+str(text[1]['location']['addressLine']),callback_data="second")
            three = types.InlineKeyboardButton(
                text=str(text[2]['name']) + "  " + str(text[2]['location']['addressLine']),
                callback_data="three")
            four = types.InlineKeyboardButton(
                text=str(text[3]['name']) + "  " + str(text[3]['location']['addressLine']),
                callback_data="four")
            five=types.InlineKeyboardButton(
                text=str(text[4]['name']) + "  " + str(text[4]['location']['addressLine']),
                callback_data="five")

        selectKeyboard.add(one, two, three, four,five)



    if 6<lenname<7:
        for i in range(len(text)):
            one=types.InlineKeyboardButton(text=str(text[0]['name'])+"  "+str(text[0]['location']['addressLine']),callback_data="first")
            two=types.InlineKeyboardButton(text=str(text[1]['name'])+"  "+str(text[1]['location']['addressLine']),callback_data="second")
            three = types.InlineKeyboardButton(
                text=str(text[2]['name']) + "  " + str(text[2]['location']['addressLine']),
                callback_data="three")
            four = types.InlineKeyboardButton(
                text=str(text[3]['name']) + "  " + str(text[3]['location']['addressLine']),
                callback_data="four")
            five = types.InlineKeyboardButton(
                text=str(text[4]['name']) + "  " + str(text[4]['location']['addressLine']),
                callback_data="five")
            six=types.InlineKeyboardButton(
                text=str(text[5]['name']) + "  " + str(text[5]['location']['addressLine']),
                callback_data="six")

        selectKeyboard.add(one, two, three, four, five,six)

    if 7<lenname<8:
        for i in range(len(text)):
            one=types.InlineKeyboardButton(text=str(text[0]['name'])+"  "+str(text[0]['location']['addressLine']),callback_data="first")
            two=types.InlineKeyboardButton(text=str(text[1]['name'])+"  "+str(text[1]['location']['addressLine']),callback_data="second")
            three = types.InlineKeyboardButton(
                text=str(text[2]['name']) + "  " + str(text[2]['location']['addressLine']),
                callback_data="three")
            four = types.InlineKeyboardButton(
                text=str(text[3]['name']) + "  " + str(text[3]['location']['addressLine']),
                callback_data="four")
            five = types.InlineKeyboardButton(
                text=str(text[4]['name']) + "  " + str(text[4]['location']['addressLine']),
                callback_data="five")
            six = types.InlineKeyboardButton(
                text=str(text[5]['name']) + "  " + str(text[5]['location']['addressLine']),
                callback_data="six")
            seven=types.InlineKeyboardButton(
                text=str(text[6]['name']) + "  " + str(text[6]['location']['addressLine']),
                callback_data="seven")

        selectKeyboard.add(one, two, three, four, five, six,seven)

    if 8<lenname<9:
        for i in range(len(text)):
            one=types.InlineKeyboardButton(text=str(text[0]['name'])+"  "+str(text[0]['location']['addressLine']),callback_data="first")
            two=types.InlineKeyboardButton(text=str(text[1]['name'])+"  "+str(text[1]['location']['addressLine']),callback_data="second")
            three = types.InlineKeyboardButton(
                text=str(text[2]['name']) + "  " + str(text[2]['location']['addressLine']),
                callback_data="three")
            four = types.InlineKeyboardButton(
                text=str(text[3]['name']) + "  " + str(text[3]['location']['addressLine']),
                callback_data="four")
            five = types.InlineKeyboardButton(
                text=str(text[4]['name']) + "  " + str(text[4]['location']['addressLine']),
                callback_data="five")
            six = types.InlineKeyboardButton(
                text=str(text[5]['name']) + "  " + str(text[5]['location']['addressLine']),
                callback_data="six")
            seven=types.InlineKeyboardButton(
                text=str(text[6]['name']) + "  " + str(text[6]['location']['addressLine']),
                callback_data="seven")
            eight=types.InlineKeyboardButton(
                text=str(text[7]['name']) + "  " + str(text[7]['location']['addressLine']),
                callback_data="seven")

        selectKeyboard.add(one, two, three, four, five, six,seven,eight)
1
  • И уточните, у Вас сложность с подсчетом количества элементов в text или в динамическом создании имени callback_data? Если в динамическом создании имени, то рекомендую переименовать вопрос на Telegram bot: как сделать динамическое имя кнопки (callback_data) ? 22 июл 2019 в 10:13

1 ответ 1

0

Попробуйте по циклу перебирать примерно так:

callback_d = 0
for item in text:
    selectKeyboard.add(types.InlineKeyboardButton(
                text=str(item['name']) + "  " + str(item['location']['addressLine']),
                callback_data=callback_d) )
    callback_d +=1

Если требуется какое-то более осмысленное имя для callback_data, то можно использовать словарь, например, такой callback_data_names = {1: "one", 2: "two", ...}.

И тогда код будет такой:

callback_data_names = {1: "one", 2: "two", ...}
callback_d = 1
for item in text:
    selectKeyboard.add(types.InlineKeyboardButton(
                text=str(item['name']) + "  " + str(item['location']['addressLine']),
                callback_data=callback_data_names[callback_d]) )
    callback_d +=1

Ваш ответ

Нажимая на кнопку «Отправить ответ», вы соглашаетесь с нашими пользовательским соглашением, политикой конфиденциальности и политикой о куки

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.