from telegram import InlineKeyboardButton, InlineKeyboardMarkup, Update
from telegram.ext import Updater, CommandHandler, CallbackQueryHandler, CallbackContext
import logging
# Замени на свой токен бота
TOKEN = "YOUR_BOT_TOKEN"
# Наш пример данных
DATA = [f"Item {i}" for i in range(1, 31)]
ITEMS_PER_PAGE = 5
logging.basicConfig(
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO
)
logger = logging.getLogger(__name__)
def get_page(page_num: int, data: list, items_per_page: int):
start = (page_num - 1) * items_per_page
end = start + items_per_page
return data[start:end]
def create_pagination_keyboard(page_num: int, total_pages: int):
buttons = []
if page_num > 1:
buttons.append(InlineKeyboardButton("⬅️ Назад", callback_data=f"page_{page_num - 1}"))
if page_num < total_pages:
buttons.append(InlineKeyboardButton("Вперед ➡️", callback_data=f"page_{page_num + 1}"))
return InlineKeyboardMarkup([buttons])
def start(update: Update, context: CallbackContext):
page_num = 1
total_pages = (len(DATA) + ITEMS_PER_PAGE - 1) // ITEMS_PER_PAGE # Вычисление общего числа страниц
current_page_items = get_page(page_num, DATA, ITEMS_PER_PAGE)
message = f"Страница {page_num}/{total_pages}:\n" + "\n".join(current_page_items)
keyboard = create_pagination_keyboard(page_num, total_pages)
update.message.reply_text(message, reply_markup=keyboard)
def handle_pagination(update: Update, context: CallbackContext):
query = update.callback_query
query.answer() # Чтобы убрать индикатор загрузки
page_num = int(query.data.split("_")[1])
total_pages = (len(DATA) + ITEMS_PER_PAGE - 1) // ITEMS_PER_PAGE # Вычисление общего числа страниц
current_page_items = get_page(page_num, DATA, ITEMS_PER_PAGE)
message = f"Страница {page_num}/{total_pages}:\n" + "\n".join(current_page_items)
keyboard = create_pagination_keyboard(page_num, total_pages)
query.edit_message_text(text=message, reply_markup=keyboard)
def main():
updater = Updater(TOKEN)
dp = updater.dispatcher
dp.add_handler(CommandHandler("start", start))
dp.add_handler(CallbackQueryHandler(handle_pagination, pattern='^page_'))
updater.start_polling()
updater.idle()
if __name__ == "__main__":
main()