# Импортируем необходимые модули
import logging
from telegram import Update, InlineKeyboardButton, InlineKeyboardMarkup
from telegram.ext import ApplicationBuilder, ContextTypes, CommandHandler, CallbackQueryHandler
# Настраиваем логирование
logging.basicConfig(
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
level=logging.INFO
)
# Задаем список товаров
products = [
{'name': 'Товар 1', 'description': '---'},
{'name': 'Товар 2', 'description': '---'},
{'name': 'Товар 3', 'description': '---'},
{'name': 'Товар 4', 'description': '---'},
{'name': 'Товар 5', 'description': '---'},
{'name': 'Товар 6', 'description': '---'},
{'name': 'Товар 7', 'description': '---'},
{'name': 'Товар 8', 'description': '---'},
{'name': 'Товар 9', 'description': '---'},
{'name': 'Товар 10', 'description': '---'},
{'name': 'Товар 11', 'description': '---'},
{'name': 'Товар 12', 'description': '---'},
{'name': 'Товар 13', 'description': '---'},
]
# Обработчик команды /start
async def start(update: Update, context: ContextTypes.DEFAULT_TYPE):
# Приветственное сообщение
greeting_text = "Привет! Добро пожаловать в наш магазин игровых товаров."
# Под сообщением появляется кнопка "Товары"
keyboard = [
[InlineKeyboardButton("Товары", callback_data='show_products')]
]
reply_markup = InlineKeyboardMarkup(keyboard)
await update.message.reply_text(greeting_text, reply_markup=reply_markup)
# Обработчик для показа списка товаров
async def show_products(update: Update, context: ContextTypes.DEFAULT_TYPE):
query = update.callback_query
await query.answer()
data = query.data
page = 1
if '_' in data:
_, page = data.split('_')
page = int(page)
await send_product_list(query, page)
# Функция для отправки списка товаров с учетом пагинации
async def send_product_list(query, page):
products_per_page = 4 # Количество товаров на странице
start_index = (page - 1) * products_per_page
end_index = start_index + products_per_page
page_products = products[start_index:end_index]
keyboard = []
# Добавляем кнопки товаров
for product in page_products:
button = InlineKeyboardButton(
product['name'],
callback_data=f'product_{product["name"]}_{page}'
)
keyboard.append([button])
# Кнопки навигации
nav_buttons = []
if page > 1:
nav_buttons.append(InlineKeyboardButton(
"Назад", callback_data=f'show_products_{page - 1}'
))
if end_index < len(products):
nav_buttons.append(InlineKeyboardButton(
"Вперед", callback_data=f'show_products_{page + 1}'
))
else:
nav_buttons.append(InlineKeyboardButton(
"В начало", callback_data='show_products_1'
))
nav_buttons.append(InlineKeyboardButton(
"В главное меню", callback_data='main_menu'
))
keyboard.append(nav_buttons)
reply_markup = InlineKeyboardMarkup(keyboard)
await query.edit_message_text(
text="Наши товары:",
reply_markup=reply_markup
)
# Обработчик для показа деталей товара
async def show_product_detail(update: Update, context: ContextTypes.DEFAULT_TYPE):
query = update.callback_query
await query.answer()
data = query.data
_, product_name, page = data.split('_', 2)
page = int(page)
# Находим товар по имени
product = next((p for p in products if p['name'] == product_name), None)
if not product:
await query.edit_message_text(text="Товар не найден.")
return
# Кнопки "Купить" и "Назад"
keyboard = [
[
InlineKeyboardButton("Купить", callback_data='buy_product'),
InlineKeyboardButton("Назад", callback_data=f'back_to_products_{page}')
]
]
reply_markup = InlineKeyboardMarkup(keyboard)
# Отправляем информацию о товаре
message_text = f"{product['name']}\n{product['description']}"
await query.edit_message_text(text=message_text, reply_markup=reply_markup)
# Обработчик кнопки "Купить"
async def buy_product(update: Update, context: ContextTypes.DEFAULT_TYPE):
query = update.callback_query
# При нажатии выводим уведомление "Недоступно"
await query.answer(text="Недоступно", show_alert=True)
# Обработчик кнопки "Назад" в деталях товара
async def back_to_products(update: Update, context: ContextTypes.DEFAULT_TYPE):
query = update.callback_query
await query.answer()
data = query.data
_, _, page = data.split('_')
page = int(page)
await send_product_list(query, page)
# Обработчик кнопки "В главное меню"
async def main_menu(update: Update, context: ContextTypes.DEFAULT_TYPE):
query = update.callback_query
await query.answer()
# Возвращаемся к приветственному сообщению
await start(update, context)
def main():
# Создаем приложение
application = ApplicationBuilder().token('YOUR_BOT_TOKEN').build()
# Регистрируем обработчики
application.add_handler(CommandHandler('start', start))
application.add_handler(CallbackQueryHandler(show_products, pattern='^show_products'))
application.add_handler(CallbackQueryHandler(show_product_detail, pattern='^product_'))
application.add_handler(CallbackQueryHandler(buy_product, pattern='^buy_product$'))
application.add_handler(CallbackQueryHandler(back_to_products, pattern='^back_to_products_'))
application.add_handler(CallbackQueryHandler(main_menu, pattern='^main_menu$'))
# Запускаем бота
application.run_polling()
if __name__ == '__main__':
main()