app.py:
from flask import Flask, request, jsonify, render_template
import logging
from db import *
from keyboard import get_keyboard
import os

app = Flask(name)
logging.basicConfig(level=logging.INFO, filename=“info.log”)

start_capital = 100

@app.route(“/”)
def index():
return render_template(“index.html”)

@app.route(“/start”, methods=[“GET”])
def start():
user_id = request.args.get(“user_id”)
username = request.args.get(“username”)
temp = add_user(user_id, start_capital, username)
if temp is not None:
return jsonify({“message”: “Привет! Ваш начальный баланс: {}”.format(start_capital), “keyboard”: get_keyboard()})
return jsonify({“message”: “Пользователь уже существует”, “keyboard”: get_keyboard()})

@app.route(“/balance”, methods=[“GET”])
def balance():
user_id = request.args.get(“user_id”)
if get_balance(user_id) is None:
username = request.args.get(“username”)
temp = add_user(user_id, start_capital, username)

wallet_id = get_wallet(user_id)
current_balance = get_balance(user_id)
return jsonify({“message”: f"Ваш номер кошелька: {wallet_id}\nВаш текущий баланс: {current_balance}“, “keyboard”: get_keyboard()})

@app.route(”/send", methods=[“POST”])
def send():
data = request.json
sender_id = data.get(“sender_id”)
recipient_id_str = data.get(“recipient_id_str”)
amount_str = data.get(“amount_str”)

try:
recipient_id = get_user_id(int(recipient_id_str))
amount = int(amount_str)

sender_balance = get_balance(sender_id)

if sender_balance is None:
return jsonify({“message”: “Изначально нужно зарегистрироваться, напишите /start”, “keyboard”: get_keyboard()})

if sender_balance < amount:
return jsonify({“message”: “Недостаточно средств для перевода.”, “keyboard”: get_keyboard()})

if recipient_id is None or not has_user(recipient_id):
return jsonify({“message”: “Такого пользователя нет”, “keyboard”: get_keyboard()})

add_amount(sender_id, -amount)
add_amount(recipient_id, amount)

return jsonify({“message”: f"Вы успешно перевели {amount} пользователю с ID {recipient_id_str}.“})
except (ValueError, TypeError):
return jsonify({“message”: “Используйте правильный формат: /send <ID кошелька получателя> <сумма>”})

if name == “main”:
app.run(port=int(os.environ.get(“PORT”, 5000)))


index.html
<!-- templates/index.html -->
<!DOCTYPE html>
<html lang=“en”>
<head>
<meta charset=“UTF-8”>
<meta name=“viewport” content=“width=device-width, initial-scale=1.0”>
<title>Telegram Web App</title>
</head>
<body>
<div id=“app”>
<h1>Телеграм Веб-Приложение</h1>
<button onclick=“registerUser()”>Начать</button>
<button onclick=“getBalance()”>Проверка Баланса</button>
<form id=“sendForm”>
<input type=“text” id=“recipientId” placeholder=“ID получателя”>
<input type=“text” id=“amount” placeholder=“Сумма”>
<button type=“button” onclick=“sendCurrency()”>Отправить</button>
</form>
<div id=“message”></div>
</div>

<script>
function registerUser() {
let user_id = “”; // нужно получить user_id как-то, например от Telegram Web App initData
let username = “”; // и имя пользователя также

fetch(/start?user_id={user_id}&username=
{username})
.then(response => response.json())
.then(data => {
document.getElementById(“message”).innerText = data.message;
});
}

function getBalance() {
let user_id = “”; // тоже нужно получить user_id

fetch(/balance?user_id=${user_id})
.then(response => response.json())
.then(data => {
document.getElementById(“message”).innerText = data.message;
});
}

function sendCurrency() {
let sender_id = “”; // тоже нужно получить sender_id, это текущий пользователь
let recipient_id_str = document.getElementById(“recipientId”).value;
let amount_str = document.getElementById(“amount”).value;

fetch(”/send", {
method: “POST”,
headers: {
“Content-Type”: “application/json”
},
body: JSON.stringify({ sender_id, recipient_id_str, amount_str })
})
.then(response => response.json())
.then(data => {
document.getElementById(“message”).innerText = data.message;
});
}
</script>
</body>
</html>

распиши db.py, как пример:
import sqlite3

connection = sqlite3.connect(‘my_database.db’)
cursor = connection.cursor()

def create_table():
cursor.execute(‘’‘
CREATE TABLE IF NOT EXISTS Users (
user_id INTEGER,
wallet_id INTEGER PRIMARY KEY,
balance INTEGER ,
username TEXT
)
‘’’)
connection.commit()


def add_user(ID: int, balance: int, username: str):
if not has_user(ID):
cursor.execute(‘INSERT INTO Users (user_id, balance, username) VALUES (?, ?, ?)’, (ID, balance, username))
connection.commit()
return 1
return None


def get_user(ID):
cursor.execute(f’SELECT user_id, wallet_id, balance FROM Users WHERE user_id = {ID}‘)
results = cursor.fetchall()
if len(results) > 1:
print(“ERROR”)
if len(results) == 0:
return None

return results[0]


def has_user(ID: int):
cursor.execute(‘SELECT user_id FROM Users WHERE user_id = ?’, (ID,))
return len(cursor.fetchall())>=1


def get_balance(ID: int):
user_id, wallet_id, balance = get_user(ID)
return balance

def get_wallet(ID):
user_id, wallet_id, balance = get_user(ID)
return wallet_id

def get_user_id(wallet_id: int):
cursor.execute(f’SELECT user_id FROM Users WHERE wallet_id = {wallet_id}’)
results = cursor.fetchall()
if len(results) > 1:
print(“ERROR user_id”)
if len(results) == 0:
return None
return results[0][0]


def add_amount(user_id: int, amount: int):
old_balance = get_balance(user_id)
cursor.execute(‘UPDATE Users SET balance = ? WHERE user_id = ?’, (amount+old_balance, user_id))
connection.commit()

create_table()