R
R
RulesOfNature2022-03-21 13:27:24
Python
RulesOfNature, 2022-03-21 13:27:24

How to add buttons to keyboard depending on data from database in Telebot?

Hello. I want to implement the deletion of data from the Sqlite database using Inline or Reply buttons. How can this be implemented?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander, 2022-03-21
@RulesOfNature

Suppose you know how to fetch data from sqlite, usually when fetchall() we get a list of tuples, for example this: some_data_from_sqlite = [('one',), ('two',), ('ten',)] .
and the keyboard is easy to make:

import telebot
from telebot import types


API_TOKEN = ""
bot = telebot.TeleBot(API_TOKEN)


@bot.message_handler(commands=['start'])
def start(message):
    some_data_from_sqlite = [('one',), ('two',), ('ten',)]  # список кортежей из БД
    buttons_dict = {i: x[0] for i, x in enumerate(some_data_from_sqlite)}
    keyboard = types.InlineKeyboardMarkup()
    back_button = types.InlineKeyboardButton(text="Back", callback_data="MainMenu")
    button_list = [types.InlineKeyboardButton(text=x, callback_data=x) for x in buttons_dict.values()] # callback дата понадобится при обработке нажатий на кнопку, но это уже совсем другая история :)
    keyboard.add(*button_list, back_button)
    bot.send_message(chat_id=message.chat.id, text=message.text, reply_markup=keyboard)


if __name__ == "__main__":
    try:
        bot.polling(none_stop=True)
    except Exception as e:
        print(e)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question