def start(message): dict_of_user = message.from_user user_id = models.User.objects(id_user=str(dict_of_user.id)).first() print(user_id) print(dict_of_user.id) if not models.User.objects(id_user=str(dict_of_user.id)): data_of_user = models.User( **{ 'id_user': str(dict_of_user.id), 'first_name': dict_of_user.first_name, 'username': dict_of_user.username, 'last_name': dict_of_user.last_name }).save() greeting_str = f'Hello {dict_of_user.first_name} {dict_of_user.last_name}' keyboard = ReplyKB().generate_kb(*keyboards.beginning_kb.values()) bot.send_message(message.chat.id, greeting_str, reply_markup=keyboard) real_user_id = models.User.objects(id_user=str(dict_of_user.id)).first() print(real_user_id) if not models.Cart.objects(user=user_id, active=True): cart_user = models.Cart(**{'user': real_user_id}).save() else: pass
def add_to_cart(call): if call.from_user.id not in models.User.objects.distinct("user_id"): user_obj = models.User(**{"user_id" : call.from_user.id}).save() else: user_obj = models.User.objects.get(user_id=call.from_user.id) product_obj = models.Product.objects.get(id=call.data.split('_')[1]) models.Cart(**{"user" : user_obj, "product": product_obj}).save() bot.send_message(call.message.chat.id, "Товар " + product_obj.title + " добавлен в корзину")
def look_my_cart(call): user_id = models.User.objects(id_user=str(call.from_user.id)).first() print(f'user_id {user_id.id}') if not models.Cart.objects(user=user_id, active=True): cart_user = models.Cart(**{'user': user_id.id}).save() else: cart_user = models.Cart.objects(user=user_id.id, active=True).first() print(f'cart_user {cart_user}') print(20000000) try: num1 = models.Product.objects(id=call.data.split('_')[2]).first() num = cart_user.products.index(num1) print(num) cart_user.products[0], cart_user.products[num] = cart_user.products[ num], cart_user.products[0] cart_user.save() delete_product = cart_user.update(pop__products=-1) cart_user = models.Cart.objects(user=user_id.id, active=True).first() print('deleted') except (ValueError, IndexError): #, AttributeError): pass print('get') # list_of_price = [i.products.get_price for i in cart_user] # amount = (models.get_suum_of_prices(list_of_price)) / 100 print('end') keyboard = InlineKeyboardMarkup(row_width=2) back = InlineKeyboardButton( text='<< back', callback_data=f'category_{call.data.split("_")[1]}_{None}') buy = InlineKeyboardButton(text=f'buy {"amount"} USD', callback_data=f'buy_{call.data.split("_")[1]}') print([i for i in cart_user.products]) prod_from_cart = [ InlineKeyboardButton( text=f'{i.title} delete', callback_data=f'look my cart_{call.data.split("_")[1]}_{i.id}') for i in cart_user.products ] if len(prod_from_cart) == 0: text = 'You don`t have any products \n but you can buy something' keyboard.add(back) else: text = 'My cart' keyboard.add(*prod_from_cart) keyboard.add(back, buy) bot.delete_message(chat_id=call.message.chat.id, message_id=call.message.message_id) bot.send_message(text=text, chat_id=call.message.chat.id, reply_markup=keyboard)
def add_to_cart(call): # user_last_name = call.from_user.last_name # user_first_name = call.from_user.first_name if call.from_user.id not in models.User.objects.distinct("user_id"): user_obj = models.User(**{"user_id": call.from_user.id}).save() else: user_obj = models.User.objects.get(user_id=call.from_user.id) product_obj = models.Product.objects.get(id=call.data.split('_')[1]) models.Cart(**{"user": user_obj, "product": product_obj}).save() print( str("Пользователь: " + str(call.from_user.id) + " добавил в корзину товар: " + call.data.split('_')[1]))
def main_text_handler(message): if message.text.lower() == 'информация о магазине': about_str = models.Texts.objects(title='About').get().body bot.send_message(message.chat.id, about_str) main_menu(message) return elif message.text.lower() == 'последние новости': about_str = models.Texts.objects(title='Last news').get().body bot.send_message(message.chat.id, about_str) main_menu(message) return elif message.text.lower() == 'продукты': keyboard = keyboards.ReplyIKB(key='root', lookup_field='id', named_arg='category') bot.send_message(message.chat.id, "Категории" , reply_markup=keyboard.generate_ikb()) elif message.text.lower() == 'продукты со скидкой': product_objects = models.Product.objects(is_discount=True) for i in product_objects: photo = i.photo.read() markup = telebot.types.InlineKeyboardMarkup() button = telebot.types.InlineKeyboardButton(text='Добавить в корзину', callback_data='add-to-cart_' + str(i.id)) markup.add(button) bot.send_message(message.chat.id, text=f"<b>{i.title}</b>", parse_mode='HTML') bot.send_photo(message.chat.id, photo, parse_mode='HTML', caption=f"Старая цена: " + str(i.price/100) + "\n<b>Новая цена:" + str(i.new_price/100) + "</b>" + f"\n{i.description}", reply_markup=markup) elif message.text.lower() == 'корзина': if message.from_user.id in models.User.objects.distinct("user_id"): user_obj = models.User.objects.get(user_id=message.from_user.id) user_cart = models.Cart.objects(user=user_obj, active=True) if not user_cart: bot.send_message(message.chat.id, "Корзина пуста") return cart_text = "" for i in user_cart: cart_text = cart_text + i.product.title + " " + str(i.product.get_price) + " грн.\n" cart_summ = models.Cart().get_catr_summ(user_obj) cart_text = cart_text + "Общая сумма покупок: " + str(cart_summ) + " грн." markup = telebot.types.InlineKeyboardMarkup() by_button = telebot.types.InlineKeyboardButton(text='Купить', callback_data='by-cart_' + str(i.user.id)) clear_button = telebot.types.InlineKeyboardButton(text='Очистить корзину', callback_data='clear-cart_' + str(i.user.id)) markup.add(by_button, clear_button) bot.send_message(message.chat.id, cart_text, reply_markup=markup) else: bot.send_message(message.chat.id, "Корзина пуста") else: pass
def add_to_cart(call): dict_of_user = call.from_user user_id = models.User.objects(id_user=str(dict_of_user.id)).first() print(user_id) if not models.Cart.objects(user=user_id, active=True): cart_user = models.Cart(**{'user': user_id}).save() else: pass cart_user = models.Cart.objects(user=user_id, active=True).first() ref_prod = models.Product.objects(id=call.data[12:]).first() cart_user.update(push__products=ref_prod) print(ref_prod.title) bot.answer_callback_query(callback_query_id=call.id, show_alert=False, text=f'You added {ref_prod.title}')
def add_product_to_cart(call): product = models.Product.objects(id=call.data.split('_')[1]).get() if not models.User.objects(user_id=str(call.from_user.id)): models.User(user_id=str(call.from_user.id), user_name=call.from_user.username).save() user = models.User.objects(user_id=str(call.from_user.id)).get() if not user.show_cart: models.Cart(user=user).save() cart = models.Cart.objects(user=user.id, active=True).get() cart.add_to_cart(product) cart.save() bot.send_message(call.message.chat.id, f'{product.title} добавлен в корзину')
def insert_cart(cart: schema.Cart): """ Create a new cart """ cart_obj = models.Cart() for line in cart.cart_order_lines: cart_obj.lines.append( models.CartLine(cart=cart_obj, product_id=line.product_id, quantity=line.quantity)) db_session.add(cart_obj) db_session.commit() carts = db_session.query(models.Cart).all() return { "msg": "Cart created successfully!", "carts": carts, }
def main_text_handler(message): if message.text.lower() == 'информация о магазине': # Так же как и в "start" about = models.Texts.objects(title='About').get().info bot.send_message(message.chat.id, about) return elif message.text.lower() == 'последние новости': # Так же как и в "start" news = models.Texts.objects(title='Last news').get().info bot.send_message(message.chat.id, news) return elif message.text.lower() == 'продукты': keyboard = InlineKeyboardMarkup(row_width=1) # Получаем объекты класса "Category" с БД, записываем их "title" в кнопки keyboard.add(*[ InlineKeyboardButton(i.title, callback_data='category_' + str(i.id)) for i in models.Category.get_root_categories() ]) bot.send_message(message.chat.id, "Выберите категорию", reply_markup=keyboard) elif message.text.lower() == 'продукты со скидкой': # Получаем объекты класса "Product" с установленным параметром "is_discount" в "True" product = models.Product.objects(is_discount=True) for i in product: photo = i.photo.read() keyboard = InlineKeyboardMarkup() keyboard.add( InlineKeyboardButton(text='Добавить в корзину', callback_data='add-to-cart_' + str(i.id))) bot.send_photo(message.chat.id, photo, parse_mode='HTML', caption=f"<b>{i.title}</b>\nСтарая цена: " + str(i.price) + 'грн.' + "\n<b>Новая цена:" + str(i.new_price) + 'грн.' + "</b>" + f"\n{i.description}", reply_markup=keyboard) elif message.text.lower() == 'корзина': # Проверяем на соответствие "user_id" с id чата if message.chat.id in models.User.objects.distinct("user_id"): # Получаем объект класса "User" с БД, по id в телеграме user = models.User.objects.get(user_id=message.from_user.id) # Получаем объект класса "Cart" с БД, по заданым параметрам user_cart = models.Cart.objects(user=user, active=True) if not user_cart: bot.send_message(message.chat.id, "Корзина пуста") return cart_sum_now = 0 cart_text = "" for i in user_cart: cart_text = cart_text + i.product.title + " " + str( i.product.get_price) + " грн.\n" cart_sum_now += i.product.get_price cart_sum = models.Cart().get_cart_sum(user) cart_text = "Сума товаров в корзине: " + str( cart_sum_now ) + " грн." + "\n" + cart_text + "Общая сумма покупок: " + str( cart_sum) + " грн." keyboard = InlineKeyboardMarkup() keyboard.add(*[ InlineKeyboardButton( text='Купить', callback_data='by-cart_' + str(i.user.id)), InlineKeyboardButton(text='Очистить корзину', callback_data='clear-cart_' + str(i.user.id)) ]) bot.send_message(message.chat.id, cart_text, reply_markup=keyboard) else: bot.send_message(message.chat.id, 'Корзина пуста') else: pass