Advertisement
yasi04

Untitled

Mar 19th, 2024 (edited)
640
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 16.07 KB | None | 0 0
  1. # Импорт библиотек
  2. from telebot import *
  3. import os
  4. import json
  5. import requests
  6. from datetime import datetime
  7. from dotenv import load_dotenv
  8.  
  9.  
  10. load_dotenv()
  11.  
  12. telebot = telebot.TeleBot(os.getenv('TOKEN'))
  13.  
  14. user_ids = []
  15. cheque_ids = []
  16.  
  17.  
  18. # Команда старт
  19. @telebot.message_handler(commands=['start'])
  20. def start_command(message):
  21.     telebot.send_message(
  22.         message.chat.id,
  23.         "Привет! Я бот менеджер магазина кросовок, позволяющий"
  24.         " следить за ассортиментом и продажами")
  25.     telebot.send_message(message.chat.id, "/help для просмотр команд")
  26.     link = ('http://api.giphy.com/v1/gifs/random?'
  27.             'api_key=rlDW02wK9uxxfGLMavjGnQ1aAYKuuHgl&tag=приветствие')
  28.     response = requests.get(link)
  29.     data = response.json()
  30.     gif = data['data']['images']['original']['url']
  31.     telebot.send_document(message.chat.id, gif)
  32.     # Заполняем массивы id
  33.     with open('clients.json', mode='r', encoding='utf-8') as clients:
  34.         data = json.load(clients)
  35.     for key, item in data['client_id'].items():
  36.         user_ids.append(key)
  37.     with open('sales.json', mode='r', encoding='utf-8') as sales:
  38.         data = json.load(sales)
  39.     for key, item in data['client_id'].items():
  40.         for key2, item2 in item.items():
  41.             cheque_ids.append(key2)
  42.  
  43.  
  44. # Команда хелп
  45. @telebot.message_handler(commands=['help'])
  46. def help_command(message):
  47.     telebot.send_message(message.chat.id, """Доступные команды:
  48. /assortment - просмотр ассортимента
  49. /add_product - добавить новый товар в ассортимент
  50. /delete_product - удалить товар из ассортимента
  51. /change_price - изменить цену на товар
  52. /change_availability - изменить количество товара
  53. /product_search - поиск товара по названию
  54. /show_sales - просмотр статистики по продажам
  55. /add_client - добавление информации о клиенте
  56. /add_sell - запись информации, о покупке клиента
  57. /show_clients - просмотр информации по клиентам""")
  58.  
  59.  
  60. # Команда ассортмента
  61. @telebot.message_handler(commands=['assortment'])
  62. def assortment(message):
  63.     with open('products.json', mode='r', encoding='utf-8') as products:
  64.         data = json.load(products)
  65.         prices = ''
  66.         # Проходясь по всем значениям выводим товар
  67.         # с ценой, количеством и артиклем
  68.         for brand, models in data['brand'].items():
  69.             prices += f'{brand}\n\n'
  70.             for article, details in models.items():
  71.                 model = details[0]
  72.                 cost = details[1]
  73.                 count = details[2]
  74.                 if int(count) == 0:
  75.                     count = 'Законился'
  76.                     prices += f'{model} - {count}'
  77.                 else:
  78.                     prices += (f'{model} - {cost} руб.'
  79.                                f' / {count}шт. / артикул: {article}\n')
  80.             prices += '\n\n\n'
  81.         telebot.send_message(message.chat.id, prices)
  82.  
  83.  
  84. # Команда добавления товара
  85. @telebot.message_handler(commands=['add_product'])
  86. def add_product(message):
  87.     with open('products.json', mode='r', encoding='utf-8') as products:
  88.         data = json.load(products)
  89.     text = message.text.split(';')[1:]
  90.     try:
  91.         brand = text[0]
  92.         article = text[1]
  93.         model = text[2]
  94.         cost = text[3]
  95.         count = text[4]
  96.         int(cost)
  97.         int(count)
  98.         # Если заданого бренда не существует в нашем файле, то
  99.         # создаем его и добавляем туда модель
  100.         if brand not in data['brand']:
  101.             data['brand'][brand] = {}
  102.         data['brand'][brand][article] = [model, cost, count, '0']
  103.         with open('products.json', mode='w', encoding='utf-8') as products:
  104.             json.dump(data, products, ensure_ascii=False, indent=4)
  105.         telebot.send_message(message.chat.id, 'Модель успешно добавлена')
  106.     except Exception as e:
  107.         # Если где-то в функции вышла ошибка, то отправляем пасту с командой
  108.         print(e)
  109.         telebot.send_message(
  110.             message.chat.id,
  111.             'Введите /add_product ;марка;артикул;модель;цена;количество\n'
  112.             'Пример: /add_product ;Nike;FQ8225-100;Nike '
  113.             'Air Trainer 1 Essential;20999;10')
  114.  
  115.  
  116. # Команда удаления товара
  117. @telebot.message_handler(commands=['delete_product'])
  118. def delete_product(message):
  119.     with open('products.json', mode='r', encoding='utf-8') as products:
  120.         data = json.load(products)
  121.     text = message.text.split(';')[1:]
  122.     try:
  123.         # Проверка на существование и удаление
  124.         brand = text[0]
  125.         article = text[1]
  126.         if brand not in data['brand']:
  127.             telebot.send_message(message.chat.id, 'Бренд не найден')
  128.         elif article not in data['brand'][brand]:
  129.             telebot.send_message(message.chat.id, 'Артикул не найден')
  130.         else:
  131.             del data['brand'][brand][article]
  132.             with open('products.json', mode='w', encoding='utf-8') as products:
  133.                 json.dump(data, products, ensure_ascii=False, indent=4)
  134.             telebot.send_message(message.chat.id, 'Модель успешно удалена')
  135.     except Exception as e:
  136.         # Если где-то в функции вышла ошибка, то отправляем пасту с командой
  137.         print(e)
  138.         telebot.send_message(
  139.             message.chat.id,
  140.             'Введите /delete_product ;марка;артикул\n'
  141.             'Пример: /delete_product ;Nike;FQ8225-100')
  142.  
  143.  
  144. # Команда смены цены товара
  145. @telebot.message_handler(commands=['change_price'])
  146. def change_price(message):
  147.     with open('products.json', mode='r', encoding='utf-8') as products:
  148.         data = json.load(products)
  149.     text = message.text.split(';')[1:]
  150.     try:
  151.         # Проверка на существование и изменение цены
  152.         brand = text[0]
  153.         article = text[1]
  154.         cost = text[2]
  155.         if brand not in data['brand']:
  156.             telebot.send_message(message.chat.id, 'Бренд не найден')
  157.         elif article not in data['brand'][brand]:
  158.             telebot.send_message(message.chat.id, 'Артикул не найден')
  159.         else:
  160.             model = data['brand'][brand][article]
  161.             model[1] = cost
  162.             data['brand'][brand][article] = model
  163.             with open('products.json', mode='w', encoding='utf-8') as products:
  164.                 json.dump(data, products, ensure_ascii=False, indent=4)
  165.             telebot.send_message(message.chat.id, 'Цена успешно изменена')
  166.     except Exception as e:
  167.         # Если где-то в функции вышла ошибка, то отправляем пасту с командой
  168.         print(e)
  169.         telebot.send_message(
  170.             message.chat.id,
  171.             'Введите /change_price ;марка;артикул;новая цена\n'
  172.             'Пример: /change_price ;Nike;FQ8225-100;21999')
  173.  
  174.  
  175. # Команда смены количества товара
  176. @telebot.message_handler(commands=['change_availability'])
  177. def change_availability(message):
  178.     with open('products.json', mode='r', encoding='utf-8') as products:
  179.         data = json.load(products)
  180.     text = message.text.split(';')[1:]
  181.     try:
  182.         # Проверка на существование и изменение количества
  183.         brand = text[0]
  184.         article = text[1]
  185.         count = text[2]
  186.         if brand not in data['brand']:
  187.             telebot.send_message(message.chat.id, 'Бренд не найден')
  188.         elif article not in data['brand'][brand]:
  189.             telebot.send_message(message.chat.id, 'Артикул не найден')
  190.         else:
  191.             model = data['brand'][brand][article]
  192.             model[2] = count
  193.             data['brand'][brand][article] = model
  194.             with open('products.json', mode='w', encoding='utf-8') as products:
  195.                 json.dump(data, products, ensure_ascii=False, indent=4)
  196.             telebot.send_message(
  197.                 message.chat.id,
  198.                 'Количество успешно изменено')
  199.     except Exception as e:
  200.         # Если где-то в функции вышла ошибка, то отправляем пасту с командой
  201.         print(e)
  202.         telebot.send_message(
  203.             message.chat.id,
  204.             'Введите /change_availability ;марка;артикул;количество\n'
  205.             'Пример: /change_availability ;Nike;FQ8225-100;20')
  206.  
  207.  
  208. # Команда поиска товара по названию
  209. @telebot.message_handler(commands=['product_search'])
  210. def product_search(message):
  211.     with open('products.json', mode='r', encoding='utf-8') as products:
  212.         data = json.load(products)
  213.     text = message.text.split(';')[1:]
  214.     flag = False
  215.     try:
  216.         # Проверка на существование и передача flag = True в случае нахождения
  217.         model = text[0]
  218.         for brand, models in data['brand'].items():
  219.             for article, details in models.items():
  220.                 if model in details[0]:
  221.                     prices = (f'{model} - {details[1]} руб. /'
  222.                               f' {details[2]}шт. / артикул: {article}\n')
  223.                     telebot.send_message(message.chat.id, prices)
  224.                     flag = True
  225.         # Если не нашлось
  226.         if not flag:
  227.             telebot.send_message(message.chat.id, f'Модель {model} не найдена')
  228.     except Exception as e:
  229.         # Если где-то в функции вышла ошибка, то отправляем пасту с командой
  230.         print(e)
  231.         telebot.send_message(
  232.             message.chat.id,
  233.             'Введите /product_search ;модель\n'
  234.             'Пример: /product_search ;Nike Air Trainer 1 Essential')
  235.  
  236.  
  237. # Команда добавления клиента
  238. @telebot.message_handler(commands=['add_client'])
  239. def add_product(message):
  240.     with open('clients.json', mode='r', encoding='utf-8') as clients:
  241.         data = json.load(clients)
  242.     text = message.text.split(';')[1:]
  243.     try:
  244.         # Создаем нового клиента
  245.         client_id = max(user_ids) + 1
  246.         name = text[0]
  247.         sales = text[1]
  248.         data['client_id'][client_id] = {}
  249.         data['client_id'][client_id] = [name, sales]
  250.         with open('clients.json', mode='w', encoding='utf-8') as clients:
  251.             json.dump(data, clients, ensure_ascii=False, indent=4)
  252.         telebot.send_message(message.chat.id, 'Клиент успешно добавлен')
  253.     except Exception as e:
  254.         # Если где-то в функции вышла ошибка, то отправляем пасту с командой
  255.         print(e)
  256.         telebot.send_message(
  257.             message.chat.id,
  258.             'Введите /add_client ;имя;количество покупок\n'
  259.             'Пример: /add_client ;Иванов Иван Иванович;2')
  260.  
  261.  
  262. # Команда добавления продажи
  263. @telebot.message_handler(commands=['add_sell'])
  264. def add_sell(message):
  265.     with open('sales.json', mode='r', encoding='utf-8') as sales:
  266.         data = json.load(sales)
  267.     text = message.text.split(';')[1:]
  268.     try:
  269.         client_id = text[0]
  270.         name = text[1]
  271.         cheque_id = max(cheque_ids)
  272.         date = datetime.today().strftime('%d.%m.%y')
  273.         article = text[2]
  274.         cost = text[3]
  275.         count = text[4]
  276.         # Добавляем новый чек
  277.         if client_id not in data['client_id']:
  278.             data['client_id'][client_id] = {}
  279.         if cheque_id not in data['client_id'][client_id]:
  280.             data['client_id'][client_id][cheque_id] = {}
  281.         data['client_id'][client_id][cheque_id] = [date, article, cost, count]
  282.         with open('sales.json', mode='w', encoding='utf-8') as sales:
  283.             json.dump(data, sales, ensure_ascii=False, indent=4)
  284.         # Обновляем информацию о клиентах
  285.         with open('clients.json', mode='r', encoding='utf-8') as clients:
  286.             data = json.load(clients)
  287.             if client_id in data['client_id']:
  288.                 old_count = data['client_id'][client_id][1]
  289.                 data['client_id'][client_id] = [name, old_count + count]
  290.             else:
  291.                 data['client_id'][client_id] = {}
  292.                 data['client_id'][client_id] = [name, count]
  293.         with open('clients.json', mode='w', encoding='utf-8') as clients:
  294.             json.dump(data, clients, ensure_ascii=False, indent=4)
  295.         # Уменьшаем количество товара на то, сколько купили
  296.         with open('products.json', mode='r', encoding='utf-8') as products:
  297.             data = json.load(products)
  298.             for brand, models in data['brand'].items():
  299.                 for art, details in models.items():
  300.                     if art == article:
  301.                         model = data['brand'][brand][article]
  302.                         model[2] = str(int(model[2]) - int(count))
  303.         # Добавление чека
  304.         with open('products.json', mode='w', encoding='utf-8') as products:
  305.             json.dump(data, products, ensure_ascii=False, indent=4)
  306.         telebot.send_message(message.chat.id, 'Чек успешно добавлен')
  307.     except Exception as e:
  308.         # Если где-то в функции вышла ошибка, то отправляем пасту с командой
  309.         print(e)
  310.         telebot.send_message(
  311.             message.chat.id,
  312.             'Введите /add_sell ;id клиента;имя клиента;'
  313.             'артикул товара;цена;количество\n'
  314.             'Пример: /add_sell ;4;Иванов Иван Иванович;'
  315.             '56;FQ8225-100;20999;1')
  316.  
  317.  
  318. # Команда просмотра всех клиентов
  319. @telebot.message_handler(commands=['show_clients'])
  320. def show_clients(message):
  321.     with open('clients.json', mode='r', encoding='utf-8') as clients:
  322.         data = json.load(clients)
  323.         show = ''
  324.         # Проходимся по всем клиентам и выводим их
  325.         for client_id, client in data['client_id'].items():
  326.             show += (f'{client[0]} с id {client_id}'
  327.                      f' купил {client[1]} товара(-ов)\n')
  328.             show += '\n'
  329.         telebot.send_message(message.chat.id, show)
  330.  
  331.  
  332. # Команда просмотра всех продаж
  333. @telebot.message_handler(commands=['show_sales'])
  334. def show_sales(message):
  335.     # Проходимся по всем продажам и выводим их
  336.     with open('sales.json', mode='r', encoding='utf-8') as sales:
  337.         data = json.load(sales)
  338.         show = ''
  339.         for client_id, client in data['client_id'].items():
  340.             for cheque_id, cheque in client.items():
  341.                 show += (f'Клиент с id {client_id} {cheque[0]}'
  342.                          f' купил товар {cheque[1]} в количестве {cheque[3]}'
  343.                          f'шт на сумму {cheque[2]}. Чек номер {cheque_id}\n')
  344.                 show += '\n'
  345.         telebot.send_message(message.chat.id, show)
  346.  
  347.  
  348. # Запуск бота
  349. telebot.polling(none_stop=True, interval=0)
  350.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement