2 months ago
import zipfile
import io
# Создание ZIP архива с файлами проекта
zip_buffer = io.BytesIO()
files = {
"bot.py": """import os
import json
import random
import aiosqlite
from aiogram import Bot, Dispatcher, types
from aiogram.types import LabeledPrice, InlineKeyboardMarkup, InlineKeyboardButton
from aiogram.utils import executor
API_TOKEN = os.getenv("API_TOKEN")
PAYMENT_PROVIDER_TOKEN = os.getenv("PAYMENT_PROVIDER_TOKEN")
ADMIN_ID = int(os.getenv("ADMIN_ID"))
bot = Bot(token=API_TOKEN)
dp = Dispatcher(bot)
def load_products():
with open("products.json", "r", encoding="utf-8") as f:
return json.load(f)
def load_keys():
with open("keys.json", "r", encoding="utf-8") as f:
return json.load(f)
def save_keys(keys):
with open("keys.json", "w", encoding="utf-8") as f:
json.dump(keys, f, ensure_ascii=False, indent=4)
products = load_products()
keys = load_keys()
async def init_db():
async with aiosqlite.connect("database.db") as db:
await db.execute(\"\"\"
CREATE TABLE IF NOT EXISTS orders (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id INTEGER,
product TEXT,
key TEXT,
amount INTEGER,
paid INTEGER
)
\"\"\")
await db.commit()
@dp.message_handler(commands=['start'])
async def start(message: types.Message):
await message.answer("Привет! Чтобы купить товар, нажми /buy")
if message.from_user.id == ADMIN_ID:
keyboard = InlineKeyboardMarkup()
keyboard.add(
InlineKeyboardButton("
Добавить товар", callback_data="admin_add_product"),
InlineKeyboardButton("
Добавить ключи", callback_data="admin_add_keys"),
InlineKeyboardButton("
Просмотр заказов", callback_data="admin_view_orders")
)
await message.answer("Панель администратора:", reply_markup=keyboard)
@dp.message_handler(commands=['buy'])
async def buy(message: types.Message):
keyboard = InlineKeyboardMarkup()
for key, product in products.items():
keyboard.add(InlineKeyboardButton(text=f"{product['name']} ({product['price']/100:.2f} грн)", callback_data=f"buy_{key}"))
await message.answer("Выберите товар:", reply_markup=keyboard)
@dp.callback_query_handler(lambda c: c.data.startswith("buy_"))
async def process_callback_buy(callback_query: types.CallbackQuery):
product_key = callback_query.data[4:]
product = products[product_key]
prices = [LabeledPrice(label=product['name'], amount=product['price'])]
await bot.send_invoice(
callback_query.from_user.id,
title=product['name'],
description="Автопродажа товара",
provider_token=PAYMENT_PROVIDER_TOKEN,
currency="UAH",
prices=prices,
start_parameter=f"buy_{product_key}",
payload=product_key
)
@dp.pre_checkout_query_handler(lambda query: True)
async def checkout(pre_checkout_query: types.PreCheckoutQuery):
await bot.answer_pre_checkout_query(pre_checkout_query.id, ok=True)
@dp.message_handler(content_types=types.ContentType.SUCCESSFUL_PAYMENT)
async def got_payment(message: types.Message):
product_key = message.successful_payment.invoice_payload
if keys.get(product_key) and keys[product_key]:
user_key = keys[product_key].pop(0)
else:
user_key = f"{product_key.upper()}-{random.randint(1000,9999)}"
if product_key not in keys:
keys[product_key] = []
save_keys(keys)
async with aiosqlite.connect("database.db") as db:
await db.execute(
"INSERT INTO orders (user_id, product, key, amount, paid) VALUES (?, ?, ?, ?, ?)",
(message.from_user.id, products[product_key]["name"], user_key, products[product_key]["price"], 1)
)
await db.commit()
await message.answer(f"Спасибо за покупку! Ваш ключ/ссылка: {user_key}")
await bot.send_message(ADMIN_ID, f"Пользователь @{message.from_user.username} купил {products[product_key]['name']}. Ключ: {user_key}")
@dp.callback_query_handler(lambda c: c.data.startswith("admin_"))
async def admin_panel(callback_query: types.CallbackQuery):
if callback_query.from_user.id != ADMIN_ID:
return
action = callback_query.data
if action == "admin_view_orders":
async with aiosqlite.connect("database.db") as db:
cursor = await db.execute("SELECT user_id, product, key, amount, paid FROM orders")
rows = await cursor.fetchall()
if not rows:
await callback_query.message.answer("Заказов пока нет.")
return
text = "\\n".join([f"User: {r[0]}, Product: {r[1]}, Key: {r[2]}, Amount: {r[3]/100:.2f}, Paid: {r[4]}" for r in rows])
await callback_query.message.answer(text)
elif action == "admin_add_product":
await callback_query.message.answer("Введите новый товар в формате: product_key|Название|Цена(грн)")
elif action == "admin_add_keys":
await callback_query.message.answer("Введите ключи для продукта в формате: product_key|KEY1,KEY2,KEY3")
if name == "__main__":
import asyncio
asyncio.run(init_db())
executor.start_polling(dp, skip_updates=True)
""",
"requirements.txt": "aiogram\naiosqlite\n",
"Procfile": "worker: python bot.py\n",
"products.json": '{"product1": {"name": "Товар 1", "price": 5000}, "product2": {"name": "Товар 2", "price": 10000}}\n',
"keys.json": '{"product1": ["KEY1A","KEY1B","KEY1C"], "product2": ["KEY2A","KEY2B","KEY2C"]}\n',
"README.md": "# Telegram Auto-Sales Bot for Railway\n\n### Установка\n1. Добавьте файлы в Railway vпроект.\n2. Установите переменные окружения API_TOKEN, PAYMENT_PROVIDER_TOKEN, ADMIN_ID.\n3. Railway автоматически запустит бота.\n"
}
with zipfile.ZipFile(zip_buffer, "a", zipfile.ZIP_DEFLATED) as zf:
for filename, content in files.items():
zf.writestr(filename, content)
zip_buffer.seek(0)
zip_path = "/mnt/data/telegram_autobot_railway.zip"
with open(zip_path, "wb") as f:
f.write(zip_buffer.getvalue())
zip_path
1 Replies
2 months ago
Hi,
Not sure what this is. If you have an issue please make a thread in the help section, not community. Make sure to share any errors.