Создание UserAPI. TODO: проверка оплаты счёта.
This commit is contained in:
parent
14b5758666
commit
d35ea3b900
@ -138,4 +138,8 @@ def token_gen(token, id):
|
||||
data = {'token': token, 'id': id}
|
||||
return call('api/token_gen/', data)
|
||||
|
||||
def fp_generate(token, nick, amount, chat_id):
|
||||
data = {'token': token, 'nick': nick, 'amount': amount, 'chat_id': chat_id}
|
||||
return call('http://127.0.0.1:7002/api/fp_generate/', data, pre=False)
|
||||
|
||||
#print( user_in_db('ee77b9d8-44f3-4e01-a702-69d5524ee50b', '1234') )
|
||||
|
7
db.py
7
db.py
@ -34,6 +34,13 @@ if not os.path.exists('stat.json'):
|
||||
outfile.write(js)
|
||||
print('Created new stat.json')
|
||||
|
||||
if not os.path.exists('user_api.json'):
|
||||
db = {'tokens': {}}
|
||||
js = json.dumps(db, indent=2)
|
||||
with open("user_api.json", "w") as outfile:
|
||||
outfile.write(js)
|
||||
print('Created new user_api.json')
|
||||
|
||||
def read(file = 'db.json'):
|
||||
with open(file, "r", encoding="utf-8") as openfile:
|
||||
db = json.load(openfile)
|
||||
|
72
tg.py
72
tg.py
@ -28,7 +28,6 @@ def checkauth(message, reg = False):
|
||||
if not reg:
|
||||
markup = ReplyKeyboardMarkup(resize_keyboard=True)
|
||||
markup.add('Баланс')
|
||||
#markup.add('Перевод')
|
||||
markup.add('Помощь')
|
||||
bot.reply_to(message, '''Пожалуйста, зарегистрируйтесь или войдите:
|
||||
/reg Nickname 1234567890
|
||||
@ -46,16 +45,44 @@ def start(message):
|
||||
markup.add('Помощь')
|
||||
|
||||
if not checkauth(message):
|
||||
pass
|
||||
else:
|
||||
return
|
||||
if message.text == '/start':
|
||||
bot.reply_to(message, 'Всё работает', reply_markup=markup)
|
||||
else:
|
||||
try:
|
||||
nick, amount = message.text.split(' ')[1].split('_')
|
||||
if float(amount) <= 0.0001:
|
||||
bot.reply_to(message, 'Слишком малое или недопустимое значение.')
|
||||
return
|
||||
amount = str(float(amount)) # Защиты от 1000 нулей в начале
|
||||
src_id = user_in_db(API_TOKEN, tg=message.chat.id)
|
||||
dst_id = user_in_db(API_TOKEN, nick=nick)
|
||||
if dst_id == 'false':
|
||||
bot.reply_to(message, 'Не существует такого пользователя.')
|
||||
else:
|
||||
status = coins_transfer(API_TOKEN, src_id, dst_id, amount)
|
||||
if status == 'No_money':
|
||||
bot.reply_to(message, 'Недостаточно средств.')
|
||||
elif status == 'OK':
|
||||
bot.reply_to(message, f'''Успешно переведено {hcode(amount)} CDM.
|
||||
Адресат: {hcode(nick)}''', parse_mode='HTML')
|
||||
|
||||
tg_dst = get_tg(API_TOKEN, dst_id)
|
||||
ds_dst = get_ds(API_TOKEN, dst_id)
|
||||
src_nick = nick
|
||||
if tg_dst != 'null':
|
||||
transfer_callback('http://127.0.0.1:7002/', API_TOKEN, src_nick, nick, amount)
|
||||
elif ds_dst != 'null':
|
||||
transfer_callback('http://127.0.0.1:7003/', API_TOKEN, src_nick, nick, amount)
|
||||
#bot.reply_to(message, f'CATCHED PAYLOAD: {str(params)}')
|
||||
except:
|
||||
pass
|
||||
|
||||
@bot.message_handler(commands=['help'])
|
||||
def help(message):
|
||||
bot.reply_to(message, f'''Исходный код: https://gitea.del.pw/justuser/CryptoDM
|
||||
|
||||
Доступные команды:
|
||||
{hcode("""/help - Помощь
|
||||
bot.reply_to(message, f'''
|
||||
Доступные команды: `
|
||||
/help - Помощь
|
||||
/reg ник - Регистрация
|
||||
/login ник пароль - Войти в аккаунт
|
||||
/passwd пароль - Смена пароля
|
||||
@ -63,8 +90,11 @@ def help(message):
|
||||
/bal - Баланс
|
||||
/pay ник сумма - Перевод
|
||||
/stats - Статистика
|
||||
""")}
|
||||
''', parse_mode='HTML')
|
||||
/token_gen - (Ре)генерация токена API`
|
||||
|
||||
[Исходный код](https://gitea.del.pw/justuser/CryptoDM)
|
||||
[API и документация](https://cdm-api.del.pw/docs#/)
|
||||
''', parse_mode='Markdown')
|
||||
|
||||
@bot.message_handler(commands=['reg'])
|
||||
def reg(message):
|
||||
@ -274,6 +304,30 @@ def transfer_callback_api(it: Transfer_callback_api):
|
||||
else:
|
||||
return 'Error'
|
||||
|
||||
# Генерация сообщения с быстрым платежом
|
||||
class Fp_generate_api(BaseModel):
|
||||
token: str
|
||||
nick: str
|
||||
amount: str
|
||||
chat_id: str
|
||||
@app.post('/api/fp_generate/')
|
||||
def fp_generate_api(it: Fp_generate_api):
|
||||
try:
|
||||
token, nick, amount, chat_id = it.token, it.nick, it.amount, it.chat_id
|
||||
keyboard = telebot.types.InlineKeyboardMarkup()
|
||||
url_button = telebot.types.InlineKeyboardButton('ОПЛАТИТЬ', url=f'https://t.me/cdm_bank_bot?start={nick}_{amount}')
|
||||
keyboard.add(url_button)
|
||||
bot.send_message(int(chat_id), f'''
|
||||
`----- ЧЕК -----`
|
||||
Сумма: `{amount}` CDM
|
||||
Получатель: `{nick}`
|
||||
`---------------`''', parse_mode='Markdown', reply_markup=keyboard)
|
||||
|
||||
#[ОПЛАТИТЬ](https://t.me/cdm_bank_bot?start={nick}_{amount})''', parse_mode='Markdown')
|
||||
return 'OK'
|
||||
except:
|
||||
return 'Error'
|
||||
|
||||
def run_api():
|
||||
uvicorn.run(app, host='127.0.0.1', port=7002)
|
||||
|
||||
|
139
user_api.py
Normal file
139
user_api.py
Normal file
@ -0,0 +1,139 @@
|
||||
from fastapi import FastAPI, Request, HTTPException
|
||||
from pydantic import BaseModel
|
||||
from time import time
|
||||
|
||||
# Отключение логирования для уменьшения нагрузки
|
||||
import logging
|
||||
logging.disable(logging.CRITICAL)
|
||||
|
||||
# Fix 3.3 + 0.15 = 3.4499999999999997
|
||||
from decimal import Decimal as d
|
||||
def fix_add(one, two):
|
||||
return float(d(str(one)) + d(str(two)))
|
||||
def fix_sub(one, two):
|
||||
return float(d(str(one)) - d(str(two)))
|
||||
|
||||
from db import *
|
||||
from call2api import *
|
||||
|
||||
app = FastAPI()
|
||||
API_TOKEN = read('conf.json')['api_token']
|
||||
|
||||
def token_check(nick, token):
|
||||
db = read('user_api.json')
|
||||
id = user_in_db(API_TOKEN, nick=nick)
|
||||
if id != 'false' and token == db['tokens'][id]:
|
||||
return True
|
||||
else:
|
||||
return False
|
||||
|
||||
# Анти-DDoS
|
||||
# Случайные тексты
|
||||
from faker import Faker
|
||||
from random import choice, randint
|
||||
FAKE_TEXTS = [Faker().text(max_nb_chars=100) for _ in range(100)]
|
||||
# Проверка на частоту обращений
|
||||
LAST_REQUESTS = {}
|
||||
def too_fast(request):
|
||||
ip = request.client.host
|
||||
now = time()
|
||||
if ip in LAST_REQUESTS and (now - LAST_REQUESTS[ip]) < 0.1:
|
||||
return True
|
||||
LAST_REQUESTS[ip] = time()
|
||||
return False
|
||||
|
||||
class Check_token_user(BaseModel):
|
||||
nick: str
|
||||
token: str
|
||||
@app.post('/api/check_token/')
|
||||
def check_token_user(request: Request, it: Check_token_user):
|
||||
if too_fast(request):
|
||||
raise HTTPException(status_code=randint(100,999), detail=f"{choice(FAKE_TEXTS)}")
|
||||
nick, token = it.nick, it.token
|
||||
if token_check(nick, token):
|
||||
return 'OK'
|
||||
else:
|
||||
return 'Error'
|
||||
|
||||
class Check_bal_user(BaseModel):
|
||||
nick: str
|
||||
token: str
|
||||
@app.post('/api/check_bal/')
|
||||
def check_bal_user(request: Request, it: Check_bal_user):
|
||||
if too_fast(request):
|
||||
raise HTTPException(status_code=randint(100,999), detail=f"{choice(FAKE_TEXTS)}")
|
||||
nick, token = it.nick, it.token
|
||||
if token_check(nick, token):
|
||||
id = user_in_db(API_TOKEN, nick=nick)
|
||||
return check_bal(API_TOKEN, id)
|
||||
else:
|
||||
return 'Error'
|
||||
|
||||
class Coins_transfer_user(BaseModel):
|
||||
nick: str
|
||||
token: str
|
||||
dst_nick: str
|
||||
amount: str
|
||||
@app.post('/api/coins_transfer/')
|
||||
def coins_transfer_user(request: Request, it: Coins_transfer_user):
|
||||
if too_fast(request):
|
||||
raise HTTPException(status_code=randint(100,999), detail=f"{choice(FAKE_TEXTS)}")
|
||||
nick, token, dst_nick, amount = it.nick, it.token, it.dst_nick, str(float(it.amount))
|
||||
if token_check(nick, token):
|
||||
id = user_in_db(API_TOKEN, nick=nick)
|
||||
dst_id = user_in_db(API_TOKEN, nick=dst_nick)
|
||||
if dst_id == 'false':
|
||||
return 'Error'
|
||||
if coins_transfer(API_TOKEN, id, dst_id, amount) == 'OK':
|
||||
tg_dst = get_tg(API_TOKEN, dst_id)
|
||||
if tg_dst != 'null':
|
||||
transfer_callback('http://127.0.0.1:7002/', API_TOKEN, nick, dst_nick, amount)
|
||||
return 'OK'
|
||||
else:
|
||||
return 'Error'
|
||||
|
||||
class Get_time2cdm_user(BaseModel):
|
||||
nick: str
|
||||
token: str
|
||||
@app.post('/api/get_time2cdm/')
|
||||
def get_time_user(request: Request, it: Get_time2cdm_user):
|
||||
if too_fast(request):
|
||||
raise HTTPException(status_code=randint(100,999), detail=f"{choice(FAKE_TEXTS)}")
|
||||
nick, token = it.nick, it.token
|
||||
if token_check(nick, token):
|
||||
id = user_in_db(API_TOKEN, nick=nick)
|
||||
return get_time2cdm(API_TOKEN, id)
|
||||
else:
|
||||
return 'Error'
|
||||
|
||||
class Get_stat_user(BaseModel):
|
||||
nick: str
|
||||
token: str
|
||||
@app.post('/api/get_stat/')
|
||||
def get_stat_user(request: Request, it: Get_stat_user):
|
||||
if too_fast(request):
|
||||
raise HTTPException(status_code=randint(100,999), detail=f"{choice(FAKE_TEXTS)}")
|
||||
nick, token = it.nick, it.token
|
||||
if token_check(nick, token):
|
||||
return get_stat(API_TOKEN)
|
||||
else:
|
||||
return 'Error'
|
||||
|
||||
class Fp_generate_user(BaseModel):
|
||||
nick: str
|
||||
token: str
|
||||
amount: str
|
||||
chat_id: str
|
||||
@app.post('/api/fp_generate/')
|
||||
def fp_generate_user(request: Request, it: Fp_generate_user):
|
||||
if too_fast(request):
|
||||
raise HTTPException(status_code=randint(100,999), detail=f"{choice(FAKE_TEXTS)}")
|
||||
nick, token, amount, chat_id = it.nick, it.token, it.amount, it.chat_id
|
||||
if token_check(nick, token):
|
||||
return fp_generate(token, nick, amount, chat_id)
|
||||
else:
|
||||
return 'Error'
|
||||
|
||||
if __name__ == '__main__':
|
||||
import uvicorn
|
||||
uvicorn.run(app, host='0.0.0.0', port=7010)
|
Loading…
Reference in New Issue
Block a user