@dp.message_handler()
async def cmd_catalog(message: types.Message, state: FSMContext) -> None:
await send_last_interaction(str(message.from_user.id))
if await check_botuser_activated(str(message.from_user.id)):
if message.text=='Каталог':
a = await bot.send_message(message.from_user.id, "OK", reply_markup=ReplyKeyboardRemove())
await bot.delete_message(message.chat.id, a.message_id)
logging.info(f"Телеграм-пользователь {message.from_user.username} просматривает каталог...")
data = await state.get_data()
child = message.text
new_categories = []
data['ALL_CATEGORIES'] = await get_categories_list()
data['CATEGORIES'] = data['ALL_CATEGORIES'][:]
CATEGORIES = data['CATEGORIES']
catalog_id = [i for i in CATEGORIES if i['parent']==None][0]['id']
new_categories = await find_children(CATEGORIES, child)
data['CATEGORIES'] = new_categories
sent_message = await message.answer("Выберите категорию:", reply_markup=create_category_keyboard_with_menu([i for i in new_categories if i['parent'] == catalog_id]))
await bot.delete_message(message.chat.id, message.message_id)
data['message_id'] = sent_message.message_id
await state.set_data(data)
elif message.text=='О нас':
logging.info(f"Телеграм-пользователь {message.from_user.username} смотрит вкладку 'О нас' ")
MESSAGES = await get_commands_list()
if 'about_us_message' in MESSAGES:
await send_photo_with_url(TOKEN=TOKEN, CHAT_ID=str(message.from_user.id), img_url=MESSAGES['about_us_message'][1], caption=MESSAGES['about_us_message'][0].replace('<br />', ''), parse_mode=types.ParseMode.HTML, message=message)
else:
await create_command(key='about_us_message', text='Мы хорошая компания!')
MESSAGES = await get_commands_list()
await send_photo_with_url(TOKEN=TOKEN, CHAT_ID=str(message.from_user.id), img_url=MESSAGES['about_us_message'][1], caption=MESSAGES['about_us_message'][0].replace('<br />', ''), parse_mode=types.ParseMode.HTML, message=message)
elif message.text=='Новости':
a = await bot.send_message(message.from_user.id, "OK", reply_markup=ReplyKeyboardRemove())
await bot.delete_message(message.chat.id, a.message_id)
logging.info(f"Телеграм-пользователь {message.from_user.username} просматривает новости")
data_list = await get_news_or_stories_list('news')
await bot.delete_message(message.chat.id, message.message_id)
if data_list:
# Сохраняем список продуктов и текущий индекс элемента в FSM
async with state.proxy() as data:
data['items'] = data_list
data['current_index'] = 0
item = data_list[0]
await create_storynews_views(item["id"])
photo = await download_photo(item["photo"])
if not photo:
a = await message.answer(f"{item['name']}:\n{item['description']}", reply_markup=get_items_kb(data_list))
else:
a = await bot.send_photo(message.from_user.id, photo, caption=f'{item["name"]} - {item["description"]}', reply_markup=get_items_kb(data_list))
data['item_message_id'] = a.message_id
data['item_name'] = item['name']
data['item_description'] = item['description']
else:
await bot.send_message(message.from_user.id, f"Список новостей пуст.", reply_markup=get_menu_keyboard())
# Устанавливаем состояние ProductState.current_index для перехода к обработке кнопок навигации
# await ItemState.current_index.set()
elif message.text=='Актуальное':
a = await bot.send_message(message.from_user.id, "OK", reply_markup=ReplyKeyboardRemove())
await bot.delete_message(message.chat.id, a.message_id)
logging.info(f"Телеграм-пользователь {message.from_user.username} просматривает актуальное")
data_list = await get_news_or_stories_list('stories')
await bot.delete_message(message.chat.id, message.message_id)
if data_list:
# Сохраняем список продуктов и текущий индекс элемента в FSM
async with state.proxy() as data:
data['items'] = data_list
data['current_index'] = 0
item = data_list[0]
await create_storynews_views(item["id"])
photo = await download_photo(item["photo"])
if not photo:
a = await message.answer(f"{item['name']}:\n{item['description']}", reply_markup=get_items_kb(data_list))
else:
a = await bot.send_photo(message.from_user.id, photo, caption=f'{item["name"]} - {item["description"]}', reply_markup=get_items_kb(data_list))
data['item_message_id'] = a.message_id
data['item_name'] = item['name']
data['item_description'] = item['description']
else:
await bot.send_message(message.from_user.id, f"Список актуального пуст.", reply_markup=get_menu_keyboard())
elif message.text=='Акции':
data_list = await get_promotions_list()
a = await bot.send_message(message.from_user.id, "OK", reply_markup=ReplyKeyboardRemove())
await bot.delete_message(message.chat.id, a.message_id)
logging.info(f"Телеграм-пользователь {message.from_user.username} просматривает акции")
if data_list:
# Сохраняем список продуктов и текущий индекс элемента в FSM
async with state.proxy() as data:
data['promotions'] = data_list
data['promotion_index'] = 0
promotion = data_list[0]
photo = await download_photo(promotion["photo"])
price = '{:,.0f}'.format(float(promotion['price'])).replace(',', ' ')
media = await get_product_media(str(promotion['id']))
kp = await get_kp_path(str(promotion['id']))
print(kp)
if not photo:
s = f"<b>ID товара</b>: {promotion['id']}\n<b>Название</b>: {promotion['name']}\n<b>Описание</b>: {promotion['promotion_description']}\n<b>Марка</b>: {promotion['brand']}\n<b>Модель</b>: {promotion['product_model']}\n<b>Комплектация</b>: {promotion['equipment']}\n<b>Производитель</b>: {promotion['manufacturer']}\n<b>Год выпуска</b>: {promotion['year']}\n<b>Стоимость</b>: {price} {promotion['currency']}\n<b>Статус</b>: {promotion['status']}"
filtered_lines = [line for line in s.split('\n') if line.split(':')[1] not in (' None', ' ')]
result = '\n'.join(filtered_lines)
a = await message.answer(result.replace('None', '')+'\n\nАкция!', reply_markup=get_promotions_kb(media, data_list, kp), parse_mode=types.ParseMode.HTML)
else:
s = f"<b>ID товара</b>: {promotion['id']}\n<b>Название</b>: {promotion['name']}\n<b>Описание</b>: {promotion['promotion_description']}\n<b>Марка</b>: {promotion['brand']}\n<b>Модель</b>: {promotion['product_model']}\n<b>Комплектация</b>: {promotion['equipment']}\n<b>Производитель</b>: {promotion['manufacturer']}\n<b>Год выпуска</b>: {promotion['year']}\n<b>Стоимость</b>: {price} {promotion['currency']}\n<b>Статус</b>: {promotion['status']}"
filtered_lines = [line for line in s.split('\n') if line.split(':')[1] not in (' None', ' ')]
result = '\n'.join(filtered_lines)
a = await bot.send_photo(message.from_user.id, photo, caption=result.replace('None', '')+'\n\nАкция!', reply_markup=get_promotions_kb(media, data_list, kp), parse_mode=types.ParseMode.HTML)
data['promotion_message_id'] = a.message_id
data['promotion_name'] = promotion['name']
data['promotion_description'] = promotion['promotion_description']
else:
await bot.send_message(message.from_user.id, f"Список акций пуст.", reply_markup=get_menu_keyboard())
else:
MESSAGES = await get_commands_list()
if 'wait_for_approve_message' in MESSAGES:
await bot.send_message(message.from_user.id, MESSAGES['wait_for_approve_message'][0][3:-4].replace('<br />', ''))
else:
await create_command(key='wait_for_approve_message', text='Пользователь не подтверждён')
MESSAGES = await get_commands_list()
await bot.send_message(message.from_user.id, MESSAGES['wait_for_approve_message'][0][3:-4].replace('<br />', ''))
# await send_photo_with_url(TOKEN=TOKEN, CHAT_ID=str(message.from_user.id), img_url=MESSAGES['wait_for_approve_message'][1], caption=MESSAGES['wait_for_approve_message'][0], parse_mode=types.ParseMode.HTML, message=message)