Advertisement
Guest User

Python Aiogram

a guest
Sep 13th, 2022
78
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 32.38 KB | Source Code | 0 0
  1. import random
  2. from datetime import datetime
  3.  
  4. import pymysql.cursors
  5. import openpyxl
  6. from aiogram.contrib.fsm_storage.memory import MemoryStorage
  7. from aiogram.contrib.middlewares.logging import LoggingMiddleware
  8. from aiogram import Bot, Dispatcher, executor, types
  9. from aiogram.dispatcher import FSMContext
  10. from aiogram.dispatcher.filters.state import State, StatesGroup
  11. from aiogram.types import ReplyKeyboardMarkup, KeyboardButton, InlineKeyboardMarkup, InlineKeyboardButton, ContentType
  12. from aiogram.utils.exceptions import MessageTextIsEmpty
  13. from aiogram.utils.markdown import hbold
  14. import zlib
  15.  
  16. import re
  17.  
  18. from config import BOT_TOKEN, HOST, PORT, USER, PASSWORD, DB_NAME, DEFAULT_PARSE_MODE, SUPPORT_USERNAME, SHOP_NAME, \
  19.     ADMIN_ID, CREATION_TIME, CHANNEL_LINK, RULES
  20. from qiwi import QIWIManager
  21.  
  22. bot = Bot(token=BOT_TOKEN)
  23. dp = Dispatcher(bot, storage=MemoryStorage())
  24. dp.middleware.setup(LoggingMiddleware())
  25. QIWI = QIWIManager()
  26.  
  27. CHANNEL_ID = -тутБылИдКанала
  28.  
  29. def connect(db_name=None):
  30.     try:
  31.         connection_ = pymysql.connect(
  32.             host=HOST,
  33.             port=PORT,
  34.             user=USER,
  35.             password=PASSWORD,
  36.             database=db_name,
  37.             cursorclass=pymysql.cursors.DictCursor
  38.         )
  39.  
  40.         print("Connection Successful")
  41.         return connection_
  42.     except Exception as err:
  43.         print("Connection was failed")
  44.         print(err)
  45.  
  46.  
  47. def get_data_from_xlsx(file_path):
  48.     document = openpyxl.load_workbook(file_path).active
  49.     data = []
  50.     for row in document.rows:
  51.         temp = []
  52.         for cell in row:
  53.             temp.append(cell.value)
  54.         data.append(temp)
  55.  
  56.     del data[0]
  57.     return data
  58.  
  59.  
  60. connection = connect(DB_NAME)
  61. cursor = connection.cursor()
  62.  
  63. main_keyboard = ReplyKeyboardMarkup(row_width=2, keyboard=[
  64.     [
  65.         KeyboardButton("Купить товар"),
  66.         KeyboardButton("Наличие товара")
  67.     ],
  68.     [
  69.         KeyboardButton("Профиль"),
  70.         KeyboardButton("О магазине")
  71.     ],
  72.     [
  73.         KeyboardButton("Правила"),
  74.         KeyboardButton("Помощь")
  75.     ]
  76. ], resize_keyboard=True)
  77. admin_inline_keyboard = InlineKeyboardMarkup(row_width=1, inline_keyboard=[
  78.     [InlineKeyboardButton("Добавить товар", callback_data="add_product")],
  79.     [InlineKeyboardButton("Обновить товар", callback_data="update_product")],
  80.     [InlineKeyboardButton("Удалить товар", callback_data="delete_product")],
  81.     [InlineKeyboardButton("Удалить весь товар", callback_data="delete_all_products")]
  82. ])
  83.  
  84.  
  85. class States(StatesGroup):
  86.     add_product = State()
  87.  
  88.     change_category = State()
  89.     change_name = State()
  90.     change_description = State()
  91.     change_price = State()
  92.     change_amount = State()
  93.     change_content = State()
  94.  
  95.     qiwi = State()
  96.  
  97.  
  98. @dp.message_handler(text="Купить товар")
  99. async def buy_product(message: types.Message):
  100.     cursor.execute(f"SELECT category FROM `products`")
  101.     categories = cursor.fetchall()
  102.     keyboard = InlineKeyboardMarkup(row_width=1, inline_keyboard=[
  103.         [InlineKeyboardButton(text=categories[i]["category"], callback_data=f"buy_product_{categories[i]['category']}")]
  104.         for i in range(len(categories))
  105.     ])
  106.     await message.reply(text=f"{hbold('Активные категории в магазине:')}", reply_markup=keyboard,
  107.                         parse_mode=DEFAULT_PARSE_MODE)
  108.  
  109.  
  110. @dp.callback_query_handler(text_startswith='buy_product')
  111. async def but_product(callback_data: types.CallbackQuery):
  112.     _, _, category = callback_data.data.split("_")
  113.     cursor.execute(f"SELECT * from `products` WHERE category='{category}'")
  114.     products_data = cursor.fetchall()
  115.     keyboard = InlineKeyboardMarkup(row_width=1, inline_keyboard=[
  116.         [InlineKeyboardButton(
  117.             text=f"{products_data[i][name]} | {products_data[i][price]} ₽ | Кол-во: {str(products_data[i][amount]) + ' шт' if products_data[i][amount] > 0 else '0 шт'}.",
  118.             callback_data=f"b_{products_data[i][name]}_{products_data[i][category_]}")]
  119.         for i in range(len(products_data)) for _, category_, name, _, price, amount, _ in products_data
  120.     ])
  121.     keyboard.add(InlineKeyboardButton(f"Назад ко всем категориям", callback_data="back_to_all"))
  122.     await callback_data.message.edit_text(text=f"{hbold('Доступные товары в разделе ' + category + ' :')}",
  123.                                           reply_markup=keyboard,
  124.                                           parse_mode=DEFAULT_PARSE_MODE)
  125.  
  126.  
  127. @dp.callback_query_handler(text="back_to_all")
  128. async def back_to_all(callback_query: types.CallbackQuery):
  129.     cursor.execute(f"SELECT category FROM `products`")
  130.     categories = cursor.fetchall()
  131.     keyboard = InlineKeyboardMarkup(row_width=1, inline_keyboard=[
  132.         [InlineKeyboardButton(text=categories[i]["category"], callback_data=f"buy_product_{categories[i]['category']}")]
  133.         for i in range(len(categories))
  134.     ])
  135.     await callback_query.message.edit_text(text=f"{hbold('Активные категории в магазине:')}", reply_markup=keyboard,
  136.                                            parse_mode=DEFAULT_PARSE_MODE)
  137.  
  138. @dp.callback_query_handler(text_startswith="back_")
  139. async def go_back(callback_data: types.CallbackQuery):
  140.     _, category = callback_data.data.split("_")
  141.     cursor.execute(f"SELECT * from `products` WHERE category='{category}'")
  142.     products_data = cursor.fetchall()
  143.     keyboard = InlineKeyboardMarkup(row_width=1, inline_keyboard=[
  144.         [InlineKeyboardButton(
  145.             text=f"{products_data[i][name]} | {products_data[i][price]} ₽ | Кол-во: {str(products_data[i][amount]) + ' шт' if products_data[i][amount] > 0 else '0 шт'}.",
  146.             callback_data=f"b_{products_data[i][name]}_{products_data[i][category_]}")]
  147.         for i in range(len(products_data)) for _, category_, name, _, price, amount, _ in products_data
  148.     ])
  149.     keyboard.add(InlineKeyboardButton(f"Назад ко всем категориям", callback_data="back_to_all"))
  150.     await callback_data.message.edit_text(text=f"{hbold('Доступные товары в разделе ' + category + ' :')}",
  151.                                           reply_markup=keyboard,
  152.                                           parse_mode=DEFAULT_PARSE_MODE)
  153.  
  154. @dp.callback_query_handler(text_startswith='b_')
  155. async def but_product_data(callback_data: types.CallbackQuery):
  156.     _, name, category = callback_data.data.split("_")
  157.     cursor.execute(f"SELECT description from `products` WHERE name='{name}' AND category='{category}' AND id=1")
  158.     descr = dict(cursor.fetchone())["description"]
  159.     cursor.execute(f"SELECT amount from `products` WHERE name='{name}' AND category='{category}' AND id=1")
  160.     amount = dict(cursor.fetchone())["amount"]
  161.     cursor.execute(f"SELECT price from `products` WHERE name='{name}' AND category='{category}' AND id=1")
  162.     price = dict(cursor.fetchone())["price"]
  163.  
  164.     keyboard = [
  165.         [InlineKeyboardButton(str(i + 1), callback_data=f"pc_{category}_{name}_{i + 1}_{price}") for i
  166.          in range(int(amount))],
  167.         [InlineKeyboardButton(f"Назад", callback_data=f"back_{category}")],
  168.         [InlineKeyboardButton(f"Назад ко всем категориям", callback_data=f"back_to_all")]]
  169.  
  170.     text = f"📃 {hbold('Товар')}: {name}\n💰 {hbold('Цена')}: {price} ₽\n📃 {hbold('Описание')}: {descr}"
  171.     await callback_data.message.edit_text(text,
  172.                                           reply_markup=InlineKeyboardMarkup(row_width=5, inline_keyboard=keyboard),
  173.                                           parse_mode=DEFAULT_PARSE_MODE)
  174.  
  175.  
  176. @dp.callback_query_handler(text_startswith='pc_')
  177. async def but_processing(callback_data: types.CallbackQuery):
  178.     _, category, name, amount, price = callback_data.data.split("_")
  179.     cursor.execute(f"SELECT description from `products` WHERE name='{name}' AND category='{category}' AND id=1")
  180.     descr = dict(cursor.fetchone())["description"]
  181.  
  182.     text = f"📃 {hbold('Товар')}: {name}\n💰 {hbold('Цена')}: {price} ₽\n📃 {hbold('Описание')}: {descr}"
  183.  
  184.     await callback_data.message.edit_text(text, reply_markup=InlineKeyboardMarkup(row_width=1, inline_keyboard=[
  185.         [InlineKeyboardButton(f"QIWI", callback_data=f"qw_{amount}_{name}_{category}")],
  186.         [InlineKeyboardButton(f"Назад", callback_data=f"back_{category}")]
  187.     ]), parse_mode=DEFAULT_PARSE_MODE)
  188.  
  189.  
  190. @dp.callback_query_handler(text_startswith='qw_')
  191. async def qiwi(callback_data: types.CallbackQuery):
  192.     _, amount, name, category = callback_data.data.split("_")
  193.     user_id = callback_data.from_user.id
  194.     bill_id = random.randint(1, 9999999)
  195.     cursor.execute(f"SELECT content from `products` WHERE name='{name}' AND category='{category}' AND id=1")
  196.     content = dict(cursor.fetchone())["content"]
  197.     cursor.execute(f"SELECT price from `products` WHERE name='{name}' AND category='{category}' AND id=1")
  198.     price = dict(cursor.fetchone())["price"]
  199.     cursor.execute(
  200.         "INSERT INTO `purchases`(user_id, bill_id, content, product_category, product_name, paid) VALUES (%s, %s, %s ,%s, %s, %s)",
  201.         (user_id, bill_id, content, category, name, False))
  202.     connection.commit()
  203.  
  204.     bill = await QIWI.create_payment(amount=int(amount) * price,
  205.                                      comment=f"{user_id}_{bill_id}")
  206.  
  207.     products_markup = InlineKeyboardMarkup(row_width=3, inline_keyboard=[
  208.         [InlineKeyboardButton(f"Перейти к оплате", url=bill.pay_url)],
  209.         [InlineKeyboardButton(f"Проверить оплату",
  210.                               callback_data=f"check_{bill_id}_{user_id}_{amount}")],
  211.         [InlineKeyboardButton(f"Отменить заказ", callback_data=f"cancelPayment_{bill_id}")],
  212.     ])
  213.     text = f"➖➖➖➖➖➖➖➖➖➖➖➖\n" \
  214.            f"📃 {hbold('Товар')}: {name}\n" \
  215.            f"💰 {hbold('Цена')}: {1} ₽\n" \
  216.            f"📦 {hbold('Кол - во')}: {amount} шт.\n" \
  217.            f"💡 {hbold('Заказ')}: {bill_id}\n" \
  218.            f"🕐 {hbold('Время заказа')}: {datetime.now().strftime('%D %H:%M:%S')}\n" \
  219.            f"🕐 {hbold('Итоговая сумма')}: {int(amount) * price} ₽\n" \
  220.            f"💲 {hbold('Способ оплаты')}: QIWI\n" \
  221.            f"➖➖➖➖➖➖➖➖➖➖➖➖\n" \
  222.            f"{hbold('Перейдите по кнопке для оплаты')}\n" \
  223.            f"➖➖➖➖➖➖➖➖➖➖➖➖"
  224.  
  225.     await callback_data.message.edit_text(text=text, reply_markup=products_markup, parse_mode=DEFAULT_PARSE_MODE)
  226.  
  227. @dp.callback_query_handler(text_startswith='cancelPayment_')
  228. async def cancelPayment(callback_data: types.CallbackQuery):
  229.     _, bill_id = callback_data.data.split("_")
  230.     text = f"Платеж с уникальным идентификатором : #{bill_id} был отменен"
  231.     await callback_data.message.answer(text)
  232.     await callback_data.message.delete()
  233.  
  234. @dp.callback_query_handler(text_startswith="check_")
  235. async def check_payment(callback_data: types.CallbackQuery):
  236.     _, bill_id, user_id, amount = callback_data.data.split("_")
  237.  
  238.     cursor.execute(f"SELECT * from `purchases` WHERE bill_id={bill_id} AND user_id={user_id}")
  239.     purchases = dict(cursor.fetchone())
  240.     if len(purchases) > 0:
  241.         if await QIWI.check_payment(f"{user_id}_{bill_id}") == QIWI.paid:
  242.             cursor.execute(f"SELECT * from `users` WHERE user_id={user_id}")
  243.             user = dict(cursor.fetchone())
  244.             purchases_ = user["purchases"]
  245.  
  246.             content = purchases["content"].split(";")
  247.             output = ";".join([content[i] for i in range(0, int(amount))])
  248.             for i in range(0, int(amount)):
  249.                 del content[0]
  250.  
  251.             content = ';'.join(content)
  252.             cursor.execute(
  253.                 f"UPDATE `purchases` SET paid=True, content='{output}' WHERE user_id={user_id} AND bill_id={bill_id}")
  254.             connection.commit()
  255.             cursor.execute(
  256.                 f"UPDATE `products` SET amount={len(purchases['content'].split(';')) - int(amount)}, content='{content}' WHERE category='{purchases['product_category']}' AND name='{purchases['product_name']}' AND id=1")
  257.             connection.commit()
  258.             cursor.execute(f"UPDATE `users` SET purchases={purchases_ + 1} WHERE user_id={user_id}")
  259.             connection.commit()
  260.             await callback_data.message.edit_text(f"Заказ номер #{bill_id}\n" + '\n'.join(o for o in output.split(';')))
  261.         else:
  262.             await callback_data.message.answer("Оплатите товар")
  263.  
  264.  
  265. @dp.message_handler(text="Наличие товара")
  266. async def products_in_store(message: types.Message):
  267.     cursor.execute("SELECT * from `products`")
  268.     products = cursor.fetchall()
  269.  
  270.     categories = {products[i][category]: [] for i in range(len(products)) for _, category, _, _, _, _, _ in products}
  271.     for product in products:
  272.         product = dict(product)
  273.         categories[product["category"]].append([product["name"], product["price"], product["amount"]])
  274.  
  275.     text = []
  276.     for key in categories.keys():
  277.         text.append(f"➖➖➖ {key} ➖➖➖\n")
  278.         for product in categories[key]:
  279.             product_name, price, amount = product
  280.             text.append(f"{hbold(product_name)} | {hbold(price)} ₽ | {hbold(amount)}  шт.\n")
  281.         text.append("\n\n")
  282.     try:
  283.         await message.reply(text="".join(text), parse_mode=DEFAULT_PARSE_MODE)
  284.     except MessageTextIsEmpty:
  285.         await message.reply(text="Весь товар закончился, приносим сови извинения", parse_mode=DEFAULT_PARSE_MODE)
  286.  
  287.  
  288. @dp.message_handler(text="Профиль")
  289. async def profile(message: types.Message):
  290.     cursor.execute(f"SELECT * from `users` WHERE user_id={message.from_user.id}")
  291.     user_data = dict(cursor.fetchone())
  292.     text = f"❤ {hbold('Пользователь')}: @{user_data['username'] if user_data['username'] is not None else 'Неизвестно'}\n" \
  293.            f"💸 {hbold('Количество покупок')}: {user_data['purchases'] if user_data['purchases'] is not None else 'Неизвестно'}\n" \
  294.            f"🔑 {hbold('ID')}: {user_data['id'] if user_data['id'] is not None else 'Неизвестно'}"
  295.  
  296.     keyboard = InlineKeyboardMarkup(row_width=1, inline_keyboard=[
  297.         [InlineKeyboardButton("История заказов", callback_data="history")],
  298.     ])
  299.     await message.reply(text=text, reply_markup=keyboard, parse_mode=DEFAULT_PARSE_MODE)
  300.  
  301.  
  302. @dp.callback_query_handler(text='history')
  303. async def show_history(callback_data: types.CallbackQuery):
  304.     cursor.execute(f"SELECT * from `purchases` WHERE user_id={callback_data.from_user.id}")
  305.     purchases_data = cursor.fetchall()
  306.     print(purchases_data)
  307.     if len(purchases_data) <= 0:
  308.         await callback_data.message.reply(text=f"{hbold('Вы еще не совершали покупок :(')}",
  309.                                           parse_mode=DEFAULT_PARSE_MODE)
  310.     else:
  311.         keyboard = InlineKeyboardMarkup(row_width=1, inline_keyboard=[
  312.             [InlineKeyboardButton(text=f"#{purchases_data[i]['bill_id']}",
  313.                                   callback_data=f"show-history-{purchases_data[i]['bill_id']}-{purchases_data[i]['content']}")]
  314.             for i in range(len(purchases_data))
  315.         ])
  316.         await callback_data.message.reply(text=f"{hbold('Ваши покупки:')}", reply_markup=keyboard,
  317.                                           parse_mode=DEFAULT_PARSE_MODE)
  318.  
  319.  
  320. @dp.callback_query_handler(text_startswith='show-history')
  321. async def show_history_products(callback_data: types.CallbackQuery):
  322.     _, _, bill_id, content = callback_data.data.split("-")
  323.     cursor.execute(f"SELECT paid from `purchases` WHERE user_id={callback_data.from_user.id} AND bill_id={bill_id}")
  324.     paid = dict(cursor.fetchone())["paid"]
  325.  
  326.     if paid:
  327.         await callback_data.message.reply(text=f"{hbold('Ваша покупка #' + bill_id + ' :')}\n{content}",
  328.                                           parse_mode=DEFAULT_PARSE_MODE)
  329.     else:
  330.         await callback_data.message.reply(text=f"{hbold('Этот товар еще не оплачен')}", parse_mode=DEFAULT_PARSE_MODE)
  331.  
  332.  
  333. @dp.message_handler(text="О магазине")
  334. async def about(message: types.Message):
  335.     text = f"🏠 {hbold('Магазин')}: {SHOP_NAME}\n" \
  336.            f"⏰ {hbold('Дата создания')}: {CREATION_TIME}\n" \
  337.            f"📢 {hbold('Канал')}:  Посмотреть ({CHANNEL_LINK})"
  338.     await message.reply(text=text, parse_mode=DEFAULT_PARSE_MODE)
  339.  
  340.  
  341. @dp.message_handler(text="Правила")
  342. async def rules(message: types.Message):
  343.     text = f"{hbold('Правила магазина:')}\n\n" + RULES
  344.     await message.reply(text=text, parse_mode=DEFAULT_PARSE_MODE)
  345.  
  346.  
  347. @dp.message_handler(text="Помощь")
  348. async def help_manager(message: types.Message):
  349.     await message.reply(text=f"{hbold('За помощью обращаться к')} - " + SUPPORT_USERNAME,
  350.                         parse_mode=DEFAULT_PARSE_MODE)
  351.  
  352.  
  353.  
  354.  
  355.  
  356. @dp.message_handler(commands=["start"])
  357. async def start(message: types.Message):
  358.     keyboard1 = KeyboardButton('Проверить')
  359.     button1 = ReplyKeyboardMarkup(resize_keyboard=True)
  360.     button1.add(keyboard1)
  361.     await message.reply('Чтобы перейти к покупкам, необходимо подписаться на @abctestxyz', reply_markup=button1)
  362.    
  363.  
  364. @dp.message_handler(text='Проверить')
  365. async def start(message: types.Message):
  366.     user_channel_status = await bot.get_chat_member(chat_id=CHANNEL_ID, user_id=message.chat.id)
  367.     user_channel_status = re.findall(r"\w*", str(user_channel_status))
  368.    
  369.     keyboard1 = KeyboardButton('Проверить')
  370.     button1 = ReplyKeyboardMarkup(resize_keyboard=True)
  371.     button1.add(keyboard1)
  372.    
  373.     keyboard2 = KeyboardButton('К покупкам')
  374.     button2 = ReplyKeyboardMarkup(resize_keyboard=True)
  375.     button2.add(keyboard2)
  376.    
  377.     try:
  378.         if user_channel_status[70] != 'left':
  379.             await bot.send_message(message.chat.id, 'Спасибо за подписку!', reply_markup=button2)
  380.             #Условие для тех, кто подписался
  381.         else:
  382.             await bot.send_message(message.chat.id, 'Чтобы перейти к покупкам, необходимо подписаться на @abctestxyz', reply_markup=button1)
  383.     except:
  384.         if user_channel_status[60] != 'left':
  385.             await bot.send_message(message.from_user.id, 'Спасибо за подписку!', reply_markup=button2)
  386.             #Условие для тех, кто подписался
  387.         else:
  388.             await bot.send_message(message.from_user.id, 'Чтобы перейти к покупкам, необходимо подписаться на @abctestxyz', reply_markup=button1)
  389.              #Условие для тех, кто не подписался
  390.  
  391. @dp.message_handler(text='К покупкам')
  392. async def start_start(message: types.Message):
  393.     if cursor.execute(f"SELECT * FROM `users` WHERE user_id={message.from_user.id}") == 0:
  394.         cursor.execute(f"INSERT INTO `users`(user_id, username, purchases) VALUES (%s, %s, %s)",
  395.                        (message.from_user.id, message.from_user.username, 0))
  396.         connection.commit()
  397.  
  398.     text = f"Добро пожаловать в магазин {hbold(SHOP_NAME)}!\n\n\n" \
  399.            f"Наличие можно посмотреть по кнопке {hbold('Наличие товара')}.\n\n" \
  400.            f"{hbold('Саппорт')}: {SUPPORT_USERNAME}\n" \
  401.            f"{hbold('Создатель')}: @dkhodos"
  402.     await message.reply(text=text, reply_markup=main_keyboard, parse_mode=DEFAULT_PARSE_MODE)
  403.  
  404.  
  405. @dp.message_handler(commands=["admin"])
  406. async def admin_panel(message: types.Message):
  407.     if message.from_user.id == ADMIN_ID:
  408.         await message.reply(f"{hbold('Выберите действие')}:",
  409.                             reply_markup=admin_inline_keyboard, parse_mode=DEFAULT_PARSE_MODE)
  410.  
  411.  
  412. @dp.callback_query_handler(text='add_product')
  413. async def add_product(callback_data: types.CallbackQuery):
  414.     await callback_data.message.edit_text(text=f"{hbold('Скачайте файл и заполните его, затем отправьте обратно')}:",
  415.                                           parse_mode=DEFAULT_PARSE_MODE)
  416.     await callback_data.message.reply_document(document=open("./output.xlsx", "rb"))
  417.     await States.add_product.set()
  418.  
  419.  
  420. @dp.message_handler(state=States.add_product, content_types=[ContentType.DOCUMENT])
  421. async def add_product_state(message: types.Message, state: FSMContext):
  422.     await message.document.download(destination_file="./temp_products.xlsx")
  423.  
  424.     for data in get_data_from_xlsx("./temp_products.xlsx"):
  425.         category, product_name, desciption, price, content = data
  426.         amount = len(content.split(";"))
  427.         cursor.execute(
  428.             f"INSERT INTO `products`(category, name, description, price, amount, content) VALUES (%s, %s, %s, %s, %s, %s)",
  429.             (category, product_name, desciption, price, amount, content))
  430.         connection.commit()
  431.     await message.answer(text=f"{hbold('Товар был успешно добавлен')}", parse_mode=DEFAULT_PARSE_MODE)
  432.     await state.finish()
  433.  
  434.  
  435. @dp.callback_query_handler(text_startswith='update_product')
  436. async def update_product(callback_data: types.CallbackQuery):
  437.     cursor.execute(f"SELECT * FROM `products`")
  438.     products_data = cursor.fetchall()
  439.  
  440.     keyboard = InlineKeyboardMarkup(row_width=1, inline_keyboard=[
  441.         [InlineKeyboardButton(text=f"{products_data[i][category]} | {products_data[i][name]}",
  442.                               callback_data=f"ut_{products_data[i][category]}_{products_data[i][name]}")] for
  443.         _, category, name, _, _, _, _ in products_data for i in range(len(products_data))
  444.     ])
  445.  
  446.     await callback_data.message.edit_text(text=f"{hbold('Выберите товар который хотите обновить:')}",
  447.                                           reply_markup=keyboard, parse_mode=DEFAULT_PARSE_MODE)
  448.  
  449.  
  450. @dp.callback_query_handler(text_startswith='ut_')
  451. async def choose_updated_product(callback_data: types.CallbackQuery):
  452.     _, category, name = callback_data.data.split("_")
  453.  
  454.     keyboard = InlineKeyboardMarkup(row_width=3, inline_keyboard=[
  455.         [
  456.             InlineKeyboardButton(text="Категорию", callback_data=f"chg_ctgr_{category}_{name}"),
  457.             InlineKeyboardButton(text="Имя", callback_data=f"chg_nm_{category}_{name}"),
  458.             InlineKeyboardButton(text="Описание", callback_data=f"chg_dscr_{category}_{name}"),
  459.         ],
  460.         [
  461.             InlineKeyboardButton(text="Цену", callback_data=f"chg_pr_{category}_{name}"),
  462.             InlineKeyboardButton(text="Содержимое", callback_data=f"chg_cnt_{category}_{name}"),
  463.         ]
  464.     ])
  465.     await callback_data.message.edit_text(text=f"{hbold('Что хотите обновить:')}", reply_markup=keyboard,
  466.                                           parse_mode=DEFAULT_PARSE_MODE)
  467.  
  468.  
  469. @dp.callback_query_handler(text_startswith='chg_')
  470. async def change_updated_product(callback_data: types.CallbackQuery):
  471.     _, action, category, name = callback_data.data.split("_")
  472.  
  473.     state = Dispatcher.get_current().current_state()
  474.     await state.update_data(product_category=category)
  475.     await state.update_data(product_name=name)
  476.  
  477.     if action == "ctgr":
  478.         await callback_data.message.edit_text(text=f"{hbold('Напишите новую категорию:')}",
  479.                                               parse_mode=DEFAULT_PARSE_MODE)
  480.         await States.change_category.set()
  481.  
  482.     if action == "nm":
  483.         await callback_data.message.edit_text(text=f"{hbold('Напишите новое название:')}",
  484.                                               parse_mode=DEFAULT_PARSE_MODE)
  485.         await States.change_name.set()
  486.  
  487.     if action == "dscr":
  488.         await callback_data.message.edit_text(text=f"{hbold('Напишите новое описание:')}",
  489.                                               parse_mode=DEFAULT_PARSE_MODE)
  490.         await States.change_description.set()
  491.  
  492.     if action == "pr":
  493.         await callback_data.message.edit_text(text=f"{hbold('Напишите новую цену товара:')}",
  494.                                               parse_mode=DEFAULT_PARSE_MODE)
  495.         await States.change_price.set()
  496.  
  497.     if action == "cnt":
  498.         await callback_data.message.edit_text(text=f"{hbold('Напишите новое содержание товара:')}",
  499.                                               parse_mode=DEFAULT_PARSE_MODE)
  500.         await States.change_content.set()
  501.  
  502.  
  503. @dp.message_handler(state=States.change_category)
  504. async def apply_changes(message: types.Message, state: FSMContext):
  505.     await state.update_data(new_category=message.text)
  506.     data = await state.get_data()
  507.     new_category = data["new_category"]
  508.     product_category = data["product_category"]
  509.     product_name = data["product_name"]
  510.  
  511.     cursor.execute(
  512.         f"UPDATE `products` SET category='{new_category}' WHERE category='{product_category}' AND name='{product_name}' AND id=1;")
  513.     connection.commit()
  514.  
  515.     await message.answer(text=f"{hbold('Категория успешно обновлена')}", reply_markup=admin_inline_keyboard,
  516.                          parse_mode=DEFAULT_PARSE_MODE)
  517.     await state.finish()
  518.  
  519.  
  520. @dp.message_handler(state=States.change_name)
  521. async def apply_changes(message: types.Message, state: FSMContext):
  522.     await state.update_data(new_name=message.text)
  523.     data = await state.get_data()
  524.     new_name = data["new_name"]
  525.     product_category = data["product_category"]
  526.     product_name = data["product_name"]
  527.  
  528.     cursor.execute(
  529.         f"UPDATE `products` SET name='{new_name}' WHERE category='{product_category}' AND name='{product_name}' AND id=1;")
  530.     connection.commit()
  531.  
  532.     await message.answer(text=f"{hbold('Имя успешно обновлено')}", reply_markup=admin_inline_keyboard,
  533.                          parse_mode=DEFAULT_PARSE_MODE)
  534.     await state.finish()
  535.  
  536.  
  537. @dp.message_handler(state=States.change_description)
  538. async def apply_changes(message: types.Message, state: FSMContext):
  539.     await state.update_data(new_decr=message.text)
  540.     data = await state.get_data()
  541.     new_decr = data["new_decr"]
  542.     product_category = data["product_category"]
  543.     product_name = data["product_name"]
  544.  
  545.     cursor.execute(
  546.         f"UPDATE `products` SET description='{new_decr}' WHERE category='{product_category}' AND name='{product_name}' AND id=1;")
  547.     connection.commit()
  548.  
  549.     await message.answer(text=f"{hbold('Описание успешно обновлено')}", reply_markup=admin_inline_keyboard,
  550.                          parse_mode=DEFAULT_PARSE_MODE)
  551.     await state.finish()
  552.  
  553.  
  554. @dp.message_handler(state=States.change_price)
  555. async def apply_changes(message: types.Message, state: FSMContext):
  556.     await state.update_data(new_price=message.text)
  557.     data = await state.get_data()
  558.     new_price = data["new_price"]
  559.     product_category = data["product_category"]
  560.     product_name = data["product_name"]
  561.  
  562.     cursor.execute(
  563.         f"UPDATE `products` SET price={new_price} WHERE category='{product_category}' AND name='{product_name}' AND id=1;")
  564.     connection.commit()
  565.  
  566.     await message.answer(text=f"{hbold('Цена успешно обновлена')}", reply_markup=admin_inline_keyboard,
  567.                          parse_mode=DEFAULT_PARSE_MODE)
  568.     await state.finish()
  569.  
  570.  
  571. # @dp.message_handler(state=States.change_amount)
  572. # async def apply_changes(message: types.Message, state: FSMContext):
  573. #     await state.update_data(new_amount=message.text)
  574. #     data = await state.get_data()
  575. #     new_amount = data["new_amount"]
  576. #     product_category = data["product_category"]
  577. #     product_name = data["product_name"]
  578. #
  579. #     cursor.execute(
  580. #         f"UPDATE `products` SET amount={new_amount} WHERE category='{product_category}' AND name='{product_name}' AND id=1;")
  581. #     connection.commit()
  582. #
  583. #     await message.answer(text=f"{hbold('Кол-во успешно обновлено')}", reply_markup=admin_inline_keyboard,
  584. #                          parse_mode=DEFAULT_PARSE_MODE)
  585. #     await state.finish()
  586.  
  587.  
  588. @dp.message_handler(state=States.change_content)
  589. async def apply_changes(message: types.Message, state: FSMContext):
  590.     await state.update_data(new_content=message.text)
  591.     data = await state.get_data()
  592.     new_content = data["new_content"]
  593.     product_category = data["product_category"]
  594.     product_name = data["product_name"]
  595.     amount = len(new_content.split(";"))
  596.  
  597.     cursor.execute(
  598.         f"UPDATE `products` SET content='{new_content}' WHERE category='{product_category}' AND name='{product_name}' AND id=1;")
  599.     cursor.execute(
  600.         f"UPDATE `products` SET amount={amount} WHERE category='{product_category}' AND name='{product_name}' AND id=1;")
  601.     connection.commit()
  602.  
  603.     await message.answer(text=f"{hbold('Содержание успешно обновлено')}", reply_markup=admin_inline_keyboard,
  604.                          parse_mode=DEFAULT_PARSE_MODE)
  605.     await state.finish()
  606.  
  607.  
  608. @dp.message_handler(commands=["keyboard"])
  609. async def show_keyboard(message: types.Message):
  610.     await message.reply(text=f"{hbold('Показываю клавиатуру')}", reply_markup=main_keyboard,
  611.                         parse_mode=DEFAULT_PARSE_MODE)
  612.  
  613.  
  614. @dp.callback_query_handler(text='delete_product')
  615. async def delete_product(callback_data: types.CallbackQuery):
  616.     cursor.execute(f"SELECT * FROM `products`")
  617.     products_data = cursor.fetchall()
  618.     keyboard = InlineKeyboardMarkup(row_width=1, inline_keyboard=[
  619.         [InlineKeyboardButton(text=f"{products_data[i][category]} | {products_data[i][name]}",
  620.                               callback_data=f"dlt_{products_data[i][category]}_{products_data[i][name]}")] for
  621.         _, category, name, _, _, _, _ in products_data for i in range(len(products_data))
  622.     ])
  623.  
  624.     await callback_data.message.edit_text(text=f"{hbold('Выберите товар который хотите удалить:')}",
  625.                                           reply_markup=keyboard, parse_mode=DEFAULT_PARSE_MODE)
  626.  
  627.  
  628. @dp.callback_query_handler(text_startswith='dlt')
  629. async def apply_changes(callback_data: types.CallbackQuery):
  630.     _, category, name = callback_data.data.split("_")
  631.  
  632.     cursor.execute(f"DELETE from `products` WHERE category='{category}' and name='{name}'")
  633.     connection.commit()
  634.  
  635.     await callback_data.message.edit_text(text=f"{hbold('Товар ' + name + ' успешно удален')}",
  636.                                           parse_mode=DEFAULT_PARSE_MODE)
  637.  
  638.  
  639. @dp.callback_query_handler(text="delete_all_products")
  640. async def delete_all_products(callback_data: types.CallbackQuery):
  641.     cursor.execute("DELETE from `products`")
  642.     connection.commit()
  643.  
  644.     keyboard = InlineKeyboardMarkup(row_width=2, inline_keyboard=[
  645.         [
  646.             InlineKeyboardButton(text="Уверен", callback_data="delete_answer_yes"),
  647.             InlineKeyboardButton(text="Отменить", callback_data="delete_answer_no"),
  648.         ]
  649.     ])
  650.     await callback_data.message.edit_text(text=f"{hbold('Вы уверены?')}",
  651.                                           reply_markup=keyboard,
  652.                                           parse_mode=DEFAULT_PARSE_MODE)
  653.  
  654.  
  655. @dp.callback_query_handler(text_startswith="delete_answer")
  656. async def delete_all_products(callback_data: types.CallbackQuery):
  657.     _, _, answer = callback_data.data.split("_")
  658.  
  659.     if answer == "yes":
  660.         cursor.execute("DELETE from `products`")
  661.         connection.commit()
  662.  
  663.         await callback_data.message.edit_text(text=f"{hbold('Все товары были удалены.')}",
  664.                                               parse_mode=DEFAULT_PARSE_MODE)
  665.     else:
  666.         await callback_data.message.edit_text(text=f"{hbold('Удаление отменено.')}", parse_mode=DEFAULT_PARSE_MODE)
  667.  
  668.  
  669. if __name__ == '__main__':
  670.     # register_all_message_functions(dp)
  671.     # register_all_callback_functions(dp)
  672.  
  673.     executor.start_polling(dp, skip_updates=True)
Tags: python
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement