Spaces:
Paused
Paused
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,11 +1,15 @@
|
|
| 1 |
-
import
|
| 2 |
-
from telebot import types
|
| 3 |
-
from flask import Flask, request, jsonify, render_template_string
|
| 4 |
-
import threading
|
| 5 |
import json
|
| 6 |
-
from datetime import datetime
|
| 7 |
import os
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 8 |
import logging
|
|
|
|
| 9 |
|
| 10 |
# Настройка логирования
|
| 11 |
logging.basicConfig(level=logging.INFO)
|
|
@@ -13,7 +17,8 @@ logger = logging.getLogger(__name__)
|
|
| 13 |
|
| 14 |
# Инициализация бота и Flask
|
| 15 |
BOT_TOKEN = '7734802681:AAGKHGG8O9uNk64JWTHH5yqXzvSxCcoLUdA'
|
| 16 |
-
bot =
|
|
|
|
| 17 |
app = Flask(__name__)
|
| 18 |
|
| 19 |
# Путь для хранения данных (товары и заказы)
|
|
@@ -39,60 +44,45 @@ def save_data(data):
|
|
| 39 |
|
| 40 |
data = load_data()
|
| 41 |
|
| 42 |
-
#
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 51 |
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
elif message.text == "🛒 Корзина":
|
| 57 |
-
show_cart(message)
|
| 58 |
-
elif message.text == "📦 Заказы":
|
| 59 |
-
show_orders(message)
|
| 60 |
|
| 61 |
-
|
|
|
|
| 62 |
if not data['products']:
|
| 63 |
-
|
| 64 |
return
|
| 65 |
for product in data['products']:
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
def get_product_keyboard(product_id):
|
| 70 |
-
markup = types.InlineKeyboardMarkup()
|
| 71 |
-
btn_add = types.InlineKeyboardButton("Добавить в корзину", callback_data=f"add_{product_id}")
|
| 72 |
-
markup.add(btn_add)
|
| 73 |
-
return markup
|
| 74 |
-
|
| 75 |
-
@bot.callback_query_handler(func=lambda call: call.data.startswith('add_'))
|
| 76 |
-
def callback_handler(call):
|
| 77 |
-
product_id = int(call.data.split('_')[1])
|
| 78 |
-
product = next((p for p in data['products'] if p['id'] == product_id), None)
|
| 79 |
-
if product:
|
| 80 |
-
user_id = call.from_user.id
|
| 81 |
-
cart = next((o for o in data['orders'] if o['user_id'] == user_id and not o['completed']), None)
|
| 82 |
-
if not cart:
|
| 83 |
-
cart = {'user_id': user_id, 'items': [], 'completed': False, 'date': datetime.now().isoformat()}
|
| 84 |
-
data['orders'].append(cart)
|
| 85 |
-
cart['items'].append({'product_id': product_id, 'quantity': 1})
|
| 86 |
-
save_data(data)
|
| 87 |
-
bot.answer_callback_query(call.id, "Товар добавлен в корзину!")
|
| 88 |
-
else:
|
| 89 |
-
bot.answer_callback_query(call.id, "Товар не найден.")
|
| 90 |
|
| 91 |
-
|
|
|
|
| 92 |
user_id = message.from_user.id
|
| 93 |
cart = next((o for o in data['orders'] if o['user_id'] == user_id and not o['completed']), None)
|
| 94 |
if not cart or not cart['items']:
|
| 95 |
-
|
| 96 |
return
|
| 97 |
total = 0
|
| 98 |
response = "Ваша корзина:\n"
|
|
@@ -101,28 +91,44 @@ def show_cart(message):
|
|
| 101 |
response += f"🏷 {product['name']} - {product['price']} руб. x {item['quantity']}\n"
|
| 102 |
total += product['price'] * item['quantity']
|
| 103 |
response += f"\nИтого: {total} руб."
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 108 |
|
| 109 |
-
@
|
| 110 |
-
def complete_order(
|
| 111 |
-
user_id = int(
|
| 112 |
cart = next((o for o in data['orders'] if o['user_id'] == user_id and not o['completed']), None)
|
| 113 |
if cart:
|
| 114 |
cart['completed'] = True
|
| 115 |
save_data(data)
|
| 116 |
-
bot.answer_callback_query(
|
| 117 |
-
bot.send_message(user_id, "Спасибо за заказ! Мы скоро свяжемся с вами.")
|
| 118 |
else:
|
| 119 |
-
bot.answer_callback_query(
|
| 120 |
|
| 121 |
-
|
|
|
|
| 122 |
user_id = message.from_user.id
|
| 123 |
user_orders = [o for o in data['orders'] if o['user_id'] == user_id and o['completed']]
|
| 124 |
if not user_orders:
|
| 125 |
-
|
| 126 |
return
|
| 127 |
for order in user_orders:
|
| 128 |
response = "Ваш заказ:\n"
|
|
@@ -132,7 +138,7 @@ def show_orders(message):
|
|
| 132 |
response += f"🏷 {product['name']} - {product['price']} руб. x {item['quantity']}\n"
|
| 133 |
total += product['price'] * item['quantity']
|
| 134 |
response += f"\nИтого: {total} руб.\nДата: {order['date']}"
|
| 135 |
-
|
| 136 |
|
| 137 |
# Админ-панель (Flask) с HTML, CSS и JavaScript в строке
|
| 138 |
admin_html = """
|
|
@@ -236,9 +242,12 @@ def delete_product(product_id):
|
|
| 236 |
return jsonify({'status': 'error', 'message': str(e)}), 500
|
| 237 |
|
| 238 |
# Запуск бота и Flask в разных потоках
|
|
|
|
|
|
|
|
|
|
| 239 |
def run_bot():
|
| 240 |
try:
|
| 241 |
-
|
| 242 |
except Exception as e:
|
| 243 |
logger.error(f"Ошибка в боте: {e}")
|
| 244 |
|
|
|
|
| 1 |
+
import asyncio
|
|
|
|
|
|
|
|
|
|
| 2 |
import json
|
|
|
|
| 3 |
import os
|
| 4 |
+
from datetime import datetime
|
| 5 |
+
from aiogram import Bot, Dispatcher, types, F
|
| 6 |
+
from aiogram.filters import Command
|
| 7 |
+
from aiogram.fsm.context import FSMContext
|
| 8 |
+
from aiogram.fsm.state import State, StatesGroup
|
| 9 |
+
from aiogram.utils.keyboard import ReplyKeyboardBuilder, InlineKeyboardBuilder
|
| 10 |
+
from flask import Flask, request, jsonify, render_template_string
|
| 11 |
import logging
|
| 12 |
+
import threading
|
| 13 |
|
| 14 |
# Настройка логирования
|
| 15 |
logging.basicConfig(level=logging.INFO)
|
|
|
|
| 17 |
|
| 18 |
# Инициализация бота и Flask
|
| 19 |
BOT_TOKEN = '7734802681:AAGKHGG8O9uNk64JWTHH5yqXzvSxCcoLUdA'
|
| 20 |
+
bot = Bot(token=BOT_TOKEN)
|
| 21 |
+
dp = Dispatcher()
|
| 22 |
app = Flask(__name__)
|
| 23 |
|
| 24 |
# Путь для хранения данных (товары и заказы)
|
|
|
|
| 44 |
|
| 45 |
data = load_data()
|
| 46 |
|
| 47 |
+
# Состояния для FSM (Finite State Machine)
|
| 48 |
+
class CartStates(StatesGroup):
|
| 49 |
+
waiting_for_product = State()
|
| 50 |
+
waiting_for_quantity = State()
|
| 51 |
+
|
| 52 |
+
# Клавиатуры
|
| 53 |
+
def get_main_keyboard():
|
| 54 |
+
builder = ReplyKeyboardBuilder()
|
| 55 |
+
builder.button(text="📋 Меню")
|
| 56 |
+
builder.button(text="🛒 Корзина")
|
| 57 |
+
builder.button(text="📦 Заказы")
|
| 58 |
+
builder.adjust(2)
|
| 59 |
+
return builder.as_markup(resize_keyboard=True)
|
| 60 |
+
|
| 61 |
+
def get_product_keyboard(product_id):
|
| 62 |
+
builder = InlineKeyboardBuilder()
|
| 63 |
+
builder.button(text="Добавить в корзину", callback_data=f"add_{product_id}")
|
| 64 |
+
return builder.as_markup()
|
| 65 |
|
| 66 |
+
# Обработчики для бота
|
| 67 |
+
@dp.message(Command("start"))
|
| 68 |
+
async def cmd_start(message: types.Message):
|
| 69 |
+
await message.answer("Привет! Я твой бот-магазин. Выбери действие:", reply_markup=get_main_keyboard())
|
|
|
|
|
|
|
|
|
|
|
|
|
| 70 |
|
| 71 |
+
@dp.message(F.text == "📋 Меню")
|
| 72 |
+
async def show_products(message: types.Message):
|
| 73 |
if not data['products']:
|
| 74 |
+
await message.answer("Нет доступных товаров.")
|
| 75 |
return
|
| 76 |
for product in data['products']:
|
| 77 |
+
await message.answer(f"🏷 {product['name']} - {product['price']} руб.\nОписание: {product['description']}\n/id: {product['id']}",
|
| 78 |
+
reply_markup=get_product_keyboard(product['id']))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 79 |
|
| 80 |
+
@dp.message(F.text == "🛒 Корзина")
|
| 81 |
+
async def show_cart(message: types.Message):
|
| 82 |
user_id = message.from_user.id
|
| 83 |
cart = next((o for o in data['orders'] if o['user_id'] == user_id and not o['completed']), None)
|
| 84 |
if not cart or not cart['items']:
|
| 85 |
+
await message.answer("Ваша корзина пуста.")
|
| 86 |
return
|
| 87 |
total = 0
|
| 88 |
response = "Ваша корзина:\n"
|
|
|
|
| 91 |
response += f"🏷 {product['name']} - {product['price']} руб. x {item['quantity']}\n"
|
| 92 |
total += product['price'] * item['quantity']
|
| 93 |
response += f"\nИтого: {total} руб."
|
| 94 |
+
builder = InlineKeyboardBuilder()
|
| 95 |
+
builder.button(text="Оформить заказ", callback_data=f"complete_{user_id}")
|
| 96 |
+
await message.answer(response, reply_markup=builder.as_markup())
|
| 97 |
+
|
| 98 |
+
@dp.callback_query(F.data.startswith("add_"))
|
| 99 |
+
async def add_to_cart(callback_query: types.CallbackQuery):
|
| 100 |
+
product_id = int(callback_query.data.split('_')[1])
|
| 101 |
+
product = next((p for p in data['products'] if p['id'] == product_id), None)
|
| 102 |
+
if product:
|
| 103 |
+
user_id = callback_query.from_user.id
|
| 104 |
+
cart = next((o for o in data['orders'] if o['user_id'] == user_id and not o['completed']), None)
|
| 105 |
+
if not cart:
|
| 106 |
+
cart = {'user_id': user_id, 'items': [], 'completed': False, 'date': datetime.now().isoformat()}
|
| 107 |
+
data['orders'].append(cart)
|
| 108 |
+
cart['items'].append({'product_id': product_id, 'quantity': 1})
|
| 109 |
+
save_data(data)
|
| 110 |
+
await bot.answer_callback_query(callback_query.id, "Товар добавлен в корзину!")
|
| 111 |
+
else:
|
| 112 |
+
await bot.answer_callback_query(callback_query.id, "Товар не найден.")
|
| 113 |
|
| 114 |
+
@dp.callback_query(F.data.startswith("complete_"))
|
| 115 |
+
async def complete_order(callback_query: types.CallbackQuery):
|
| 116 |
+
user_id = int(callback_query.data.split('_')[1])
|
| 117 |
cart = next((o for o in data['orders'] if o['user_id'] == user_id and not o['completed']), None)
|
| 118 |
if cart:
|
| 119 |
cart['completed'] = True
|
| 120 |
save_data(data)
|
| 121 |
+
await bot.answer_callback_query(callback_query.id, "Заказ успешно оформлен!")
|
| 122 |
+
await bot.send_message(user_id, "Спасибо за заказ! Мы скоро свяжемся с вами.")
|
| 123 |
else:
|
| 124 |
+
await bot.answer_callback_query(callback_query.id, "Корзина пуста или заказ уже оформлен.")
|
| 125 |
|
| 126 |
+
@dp.message(F.text == "📦 Заказы")
|
| 127 |
+
async def show_orders(message: types.Message):
|
| 128 |
user_id = message.from_user.id
|
| 129 |
user_orders = [o for o in data['orders'] if o['user_id'] == user_id and o['completed']]
|
| 130 |
if not user_orders:
|
| 131 |
+
await message.answer("У вас нет оформленных заказов.")
|
| 132 |
return
|
| 133 |
for order in user_orders:
|
| 134 |
response = "Ваш заказ:\n"
|
|
|
|
| 138 |
response += f"🏷 {product['name']} - {product['price']} руб. x {item['quantity']}\n"
|
| 139 |
total += product['price'] * item['quantity']
|
| 140 |
response += f"\nИтого: {total} руб.\nДата: {order['date']}"
|
| 141 |
+
await message.answer(response)
|
| 142 |
|
| 143 |
# Админ-панель (Flask) с HTML, CSS и JavaScript в строке
|
| 144 |
admin_html = """
|
|
|
|
| 242 |
return jsonify({'status': 'error', 'message': str(e)}), 500
|
| 243 |
|
| 244 |
# Запуск бота и Flask в разных потоках
|
| 245 |
+
async def on_startup(_):
|
| 246 |
+
logger.info("Бот запущен!")
|
| 247 |
+
|
| 248 |
def run_bot():
|
| 249 |
try:
|
| 250 |
+
asyncio.run(dp.start_polling(bot, on_startup=on_startup))
|
| 251 |
except Exception as e:
|
| 252 |
logger.error(f"Ошибка в боте: {e}")
|
| 253 |
|