Removal of the BDE sqlite3 cable button in telegram bot on python
-
pyTelegramBotAPI and sqlite3. Hendler on the team removes all records from the current user base and adds, under each record, an inline button to which the application must be removed from the base. There are no problems, I can't figure out how to correctly handle an inline button under a specific message. In my current code, the DELETE from here comes to the final value of the cycle for, and for some reason, disposal doesn't work or make mistakes. Tell me, what way to think.
@bot.message_handler(commands=['get']) def get_from_my_list(message): keyboard = types.InlineKeyboardMarkup(row_width=1) button = types.InlineKeyboardButton("Удалить", callback_data='del') keyboard.add(button)
with sqlite3.connect('users_data.db',check_same_thread=False) as db: cursor = db.cursor() user_id = message.from_user.id query = """SELECT wish FROM wishes WHERE user_id = {}""".format(user_id) cursor.execute(query) data = cursor.fetchall() for i in data: bot.send_message(message.chat.id, i,reply_markup=keyboard) @bot.callback_query_handler(func=lambda call: True) def answer(call): message = call.message if call.data == 'del': query = """DELETE FROM wishes WHERE wish = ?""" cursor.execute(query,(i[0],)) send = bot.send_message(message.chat.id, 'Удалено')
-
Let's say we have a table in the bd with the fields:
- chat_id
- username
Clavice function:
def kb(chat_id): keyboard = types.InlineKeyboardMarkup(row_width=1) button = types.InlineKeyboardButton("Удалить", callback_data="['del', '" + str(chat_id) + "']") keyboard.add(button) return keyboard
Here we add in
callback_data
additional parameter - argumentchat_id
♪function
start
:@bot.message_handler(commands=['start']) def start(message): with sqlite3.connect('test.db', check_same_thread=False) as db: cursor = db.cursor() cursor.execute("SELECT * FROM users") data = cursor.fetchall() for i in data: bot.send_message(message.chat.id, i[0], reply_markup=kb(i[0]))
and Handler
callback
:@bot.callback_query_handler(func=lambda call: True) def callback_inline(call): if call.data.startswith("['del'"): print(ast.literal_eval(call.data)[1]) with sqlite3.connect('test.db', check_same_thread=False) as db: cursor = db.cursor() cursor.execute("DELETE FROM users WHERE chat_id = ?", (ast.literal_eval(call.data)[1],)) bot.send_message(call.message.chat.id, 'Удалено')
to
call.data
addedstartswith
- Stroke prefix (or line corrigeration) which must be verified.Thus, if
call.data
startingdel
The condition will be met.using
ast.literal_eval
We can get additional parameters transferred tocall.data
:['del', '12**11']
- it's a regular list, second element.chat_id
transferred tocallback_data
functionkb()
♪We can now submit to the request for OBD the necessary condition for disposal.