почему неработает кнопка вперед и назад в коде import logging import sqlite3 from…
- User
почему неработает кнопка вперед и назад в коде import logging import sqlite3 from telegram import InlineKeyboardButton, InlineKeyboardMarkup, Update from telegram.ext import Updater, CommandHandler, CallbackQueryHandler, CallbackContext import telegram
logging.basicConfig(level=logging.INFO) bot = telegram.Bot(token='6143413294:AAG_0lYsev83l0FaB5rqPdpYQPsHZPLEewI') API_TOKEN = '6143413294:AAG_0lYsev83l0FaB5rqPdpYQPsHZPLEewI'
def start(update: Update, context: CallbackContext): keyboard = [ [InlineKeyboardButton('Кроссовки', callback_data='category_items')], [InlineKeyboardButton('Верхняя одежда', callback_data='category_items1')], [InlineKeyboardButton('Аксессуары', callback_data='category_items2')], ] reply_markup = InlineKeyboardMarkup(keyboard)
if update.message: update.message.reply_text('Выберите категорию:', reply_markup=reply_markup) else: query = update.callback_query query.answer() query.edit_message_text('Выберите категорию:', reply_markup=reply_markup)def show_items(update: Update, context: CallbackContext, category): query = update.callback_query query.answer()
conn = sqlite3.connect('kross.db') c = conn.cursor() c.execute(f'SELECT name FROM {category}') items = c.fetchall() keyboard = [ [InlineKeyboardButton(items[i][0], callback_data=f"{category}{i}") for i in range(min(4, len(items)))] ] if len(items) > 4: keyboard.append([ InlineKeyboardButton('Вперед', callback_data=f'next_0_4{category}') ]) reply_markup = InlineKeyboardMarkup(keyboard) query.edit_message_text('Выберите товар:', reply_markup=reply_markup)def category_callback(update: Update, context: CallbackContext): query = update.callback_query category = query.data.split('_')[1] show_items(update, context, category)
def show_product(update: Update, context: CallbackContext): query = update.callback_query data = query.data.split('_') category = data[0] index = int(data[1])
conn = sqlite3.connect('kross.db') c = conn.cursor() c.execute(f'SELECT name, size, info, price, photo_link FROM {category}') items = c.fetchall() item = items[index] text = f'Название: {item[0]}\nРазмер: {item[1]}\nОписание: {item[2]}\nЦена: {item[3]}\nСсылка на фото: {item[4]}' keyboard = [ [InlineKeyboardButton('Вернуться', callback_data=f'back_{category}')] ] reply_markup = InlineKeyboardMarkup(keyboard) query.answer() query.edit_message_text(text=text, reply_markup=reply_markup)def change_page(update: Update, context: CallbackContext): query = update.callback_query data = query.data.split('_') action = data[0] start_index = int(data[1]) end_index = int(data[2]) category = data[3]
conn = sqlite3.connect('kross.db') c = conn.cursor() c.execute(f'SELECT name FROM {category}') items = c.fetchall() prev_start = max(0, start_index - 4) prev_end = start_index next_start = end_index next_end = min(end_index + 4, len(items)) if action == 'next': start_index = next_start end_index = next_end elif action == 'prev': start_index = prev_start end_index = prev_end keyboard = [ [InlineKeyboardButton(items[i][0], callback_data=f'{category}{i}') for i in range(start_index, end_index)] ] if start_index > 0: keyboard.append([ InlineKeyboardButton('Назад', callback_data=f'prev_{prev_start}{prev_end}{category}') ]) if end_index < len(items): keyboard.append([ InlineKeyboardButton('Вперед', callback_data=f'next_{next_start}{next_end}{category}') ]) reply_markup = InlineKeyboardMarkup(keyboard) query.answer() query.edit_message_text('Выберите товар:', reply_markup=reply_markup) - Assistant
Ваш код выглядит правильно, и кнопки вперед и назад должны функционировать. Возможно, проблема возникает из-за того, что на страничке несколько товаров находятся в одной и той же строке с ключами "Назад" и "Вперед" одновременно. Вы их правильно добавляете через query.edit_message_text, но callback_data содержит неверное содержание.
Давайте попробуем исправить это.
Замените часть кода с функцией change_page на следующую:
def change_page(update: Update, context: CallbackContext): query = update.callback_query data = query.data.split('_') action = data[0] start_index = int(data[1]) end_index = int(data[2]) category = data[3] conn = sqlite3.connect('kross.db') c = conn.cursor() c.execute(f'SELECT name FROM {category}') items = c.fetchall() prev_start = max(0, start_index - 4) prev_end = start_index next_start = end_index next_end = min(end_index + 4, len(items)) if action == 'next': start_index = next_start end_index = next_end elif action == 'prev': start_index = prev_start end_index = prev_end keyboard = [ [InlineKeyboardButton(items[i][0], callback_data=f'{category}{i}') for i in range(start_index, end_index)] ] if start_index > 0: keyboard.append([ InlineKeyboardButton('Назад', callback_data=f'prev_{prev_start}_{prev_end}_{category}') ]) if end_index < len(items): keyboard.append([ InlineKeyboardButton('Вперед', callback_data=f'next_{next_start}_{next_end}_{category}') ]) reply_markup = InlineKeyboardMarkup(keyboard) query.answer() query.edit_message_text('Выберите товар:', reply_markup=reply_markup)
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.