Реализация переводов ДС-ТГ

main
justuser 4 months ago
parent 01a4c2e2d6
commit d5c2da6a93

@ -0,0 +1,305 @@
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
from db import *
app = FastAPI()
def token_check(token):
db = read()
if token in db['tokens']:
return True
else:
return False
class User_in_db(BaseModel):
token: str
id: str = None
tg: str = None
ds: str = None
mine: str = None
nick: str = None
@app.post('/api/user_in_db/')
def user_in_db(it: User_in_db):
token, id, tg, ds, mine, nick = it.token, it.id, it.tg, it.ds, it.mine, it.nick
if token_check(token):
db = read()
if id and id in db['id']:
return id
elif tg and tg in db['tg']:
return db['tg'][tg]
elif ds and ds in db['ds']:
return db['ds'][ds]
elif mine and mine in db['mine']:
return db['mine'][mine]
elif nick and nick in db['nick']:
return db['nick'][nick]
else:
return False
else:
return 'Error'
def gen_id():
db = read()
for i in range(1,100000):
check = str(i)
print(db)
if check not in db['id']:
return str(i)
return 'Full?'
class User_add(BaseModel):
token: str
id: str = None
tg: str = None
ds: str = None
mine: str = None
nick: str
passwd: str
@app.post('/api/user_add/')
def user_add(it: User_add):
token, id, tg, ds, mine, nick, passwd = it.token, it.id, it.tg, it.ds, it.mine, it.nick, it.passwd
id = gen_id()
print(id)
if token_check(token):
db = read()
db['id'][id] = {'tg': tg, 'ds': ds, 'mine': mine, 'nick': nick, 'passwd': passwd, 'bal': 0.0}
db['nick'][nick] = id
if tg:
db['tg'][tg] = id
if ds:
db['ds'][ds] = id
if mine:
db['mine'][mine] = id
write(db)
return 'OK'
else:
return 'Error'
class User_del(BaseModel):
token: str
id: str
@app.post('/api/user_del/')
def user_del(it: User_del):
token, id = it.token, it.id
if token_check(token):
db = read()
tg, ds, mine, nick = db['id'][id]['tg'], db['id'][id]['ds'], db['id'][id]['mine'], db['id'][id]['nick']
del db['nick'][nick]
if tg:
del db['tg'][tg]
if ds:
del db['ds'][ds]
if mine:
del db['mine'][mine]
del db['id'][id]
write(db)
return 'OK'
else:
return 'Error'
class Coins_add(BaseModel):
token: str
id: str
amount: str
@app.post('/api/coins_add/')
def coins_add(it: Coins_add):
token, id, amount = it.token, it.id, float(it.amount)
if token_check(token):
db = read()
db['id'][id]['bal'] += amount
write(db)
return 'OK'
else:
return 'Error'
class Coins_del(BaseModel):
token: str
id: str
amount: str
@app.post('/api/coins_del/')
def coins_del(it: Coins_del):
token, id, amount = it.token, it.id, float(it.amount)
if token_check(token):
db = read()
db['id'][id]['bal'] -= amount
write(db)
return 'OK'
else:
return 'Error'
class Coins_transfer(BaseModel):
token: str
src_id: str
dst_id: str
amount: str
@app.post('/api/coins_transfer/')
def coins_transfer(it: Coins_transfer):
token, src_id, dst_id, amount = it.token, it.src_id, it.dst_id, float(it.amount)
if token_check(token):
db = read()
src_bal = db['id'][src_id]['bal']
if src_bal > amount:
db['id'][src_id]['bal'] -= amount
db['id'][dst_id]['bal'] += amount
write(db)
return 'OK'
else:
return 'No_money'
else:
return 'Error'
class Update_tg(BaseModel):
token: str
id: str
tg: str
@app.post('/api/update_tg/')
def update_tg(it: Update_tg):
token, id, tg = it.token, it.id, it.tg
if token_check(token):
db = read()
cur_tg = db['id'][id]['tg']
del db['tg'][cur_tg]
db['id'][id]['tg'] = tg
db['tg'][tg] = id
write(db)
return 'OK'
else:
return 'Error'
class Update_ds(BaseModel):
token: str
id: str
ds: str
@app.post('/api/update_ds/')
def update_ds(it: Update_ds):
token, id, ds = it.token, it.id, it.ds
if token_check(token):
db = read()
cur_ds = db['id'][id]['ds']
del db['ds'][cur_ds]
db['id'][id]['ds'] = ds
db['ds'][ds] = id
write(db)
return 'OK'
else:
return 'Error'
class Update_mine(BaseModel):
token: str
id: str
mine: str
@app.post('/api/update_mine/')
def update_mine(it: Update_mine):
token, id, mine = it.token, it.id, it.mine
if token_check(token):
db = read()
cur_mine = db['id'][id]['mine']
del db['mine'][cur_mine]
db['id'][id]['mine'] = mine
db['mine'][mine] = id
write(db)
return 'OK'
else:
return 'Error'
class Update_nick(BaseModel):
token: str
id: str
nick: str
@app.post('/api/update_nick/')
def update_nick(it: Update_nick):
token, id, nick = it.token, it.id, it.nick
if token_check(token):
db = read()
cur_nick = db['id'][id]['nick']
del db['nick'][cur_nick]
db['id'][id]['nick'] = nick
db['nick'][nick] = id
write(db)
return 'OK'
else:
return 'Error'
class Update_passwd(BaseModel):
token: str
id: str
passwd: str
@app.post('/api/update_passwd/')
def update_tg(it: Update_tg):
token, id, passwd = it.token, it.id, it.passwd
if token_check(token):
db = read()
db['id'][id]['passwd'] = passwd
write(db)
return 'OK'
else:
return 'Error'
class Check_bal(BaseModel):
token: str
id: str
@app.post('/api/check_bal/')
def check_bal(it: Check_bal):
token, id = it.token, it.id
if token_check(token):
db = read()
return db['id'][id]['bal']
else:
return 'Error'
class Get_nick(BaseModel):
token: str
id: str
@app.post('/api/get_nick/')
def get_nick(it: Get_nick):
token, id = it.token, it.id
if token_check(token):
db = read()
return db['id'][id]['nick']
else:
return 'Error'
class Get_tg(BaseModel):
token: str
id: str
@app.post('/api/get_tg/')
def get_tg(it: Get_tg):
token, id = it.token, it.id
if token_check(token):
db = read()
return db['id'][id]['tg']
else:
return 'Error'
class Get_ds(BaseModel):
token: str
id: str
@app.post('/api/get_ds/')
def get_ds(it: Get_ds):
token, id = it.token, it.id
if token_check(token):
db = read()
return db['id'][id]['ds']
else:
return 'Error'
class Get_mine(BaseModel):
token: str
id: str
@app.post('/api/get_mine/')
def get_mine(it: Get_mine):
token, id = it.token, it.id
if token_check(token):
db = read()
return db['id'][id]['mine']
else:
return 'Error'
# TODO: unauth from account
if __name__ == '__main__':
import uvicorn
uvicorn.run(app, host='127.0.0.1', port=1111)

@ -11,8 +11,11 @@ def hash(text):
text = str(text)
return xxh32(text).hexdigest()
def call(api_url, data):
def call(api_url, data, pre=True):
if pre:
response = post(url_pre + api_url, data=dumps(data))
else:
response = post(api_url, data=dumps(data))
print(response.status_code)
print(response.text)
return response.text.replace('"', '')
@ -108,9 +111,10 @@ def get_passwd(token, id):
data = {'token': token, 'id': id}
return call('api/get_passwd/', data)
def transfer_callbak(addr, token, src_id, amount):
def transfer_callback(addr, token, src_nick, dst_nick, amount):
amount = str(amount)
data = {'token': token, 'src_id': src_id, 'amount': amount}
return call(addr + 'api/get_passwd/', data)
data = {'token': token, 'src_nick': src_nick, 'dst_nick': dst_nick, 'amount': amount}
print(addr + 'api/transfer_callback/')
return call(addr + 'api/transfer_callback/', data, pre=False)
#print( user_in_db('ee77b9d8-44f3-4e01-a702-69d5524ee50b', '1234') )

247
ds.py

@ -0,0 +1,247 @@
import discord
from time import sleep
intents = discord.Intents.default()
intents.message_content = True
bot = discord.Client(intents=intents)
# API для отправки сообщения о переводе
# TG -> DS / DS -> Mine / ...
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
import uvicorn
app = FastAPI()
# Для запуска API в потоке
from threading import Thread
from call2api import *
from db import *
API_TOKEN = read('conf.json')['api_token']
DS_TOKEN = read('conf.json')['ds_token']
from datetime import datetime
LCTIME = datetime.now()
# Обнуляем данные
db = read('conf.json')
db['push_src_nick'] = 0
db['push_id'] = 0
db['push_amount'] = 0
write(db, 'conf.json')
# Поток для приёма входящих переводов ТГ-ДС (костыль)
from discord.ext import tasks
@tasks.loop(seconds = 0.1)
async def push():
db = read('conf.json')
if db['push_id'] != 0:
src_nick, id, amount = db['push_src_nick'], db['push_id'], db['push_amount']
user = await bot.fetch_user(id)
await user.send(f'''Вам перевели `{amount}` CDM.
Отправитель: `{src_nick}`''')
db['push_src_nick'], db['push_id'], db['push_amount'] = 0, 0, 0
write(db, 'conf.json')
@bot.event
async def on_ready():
print(f'We have logged in as {bot.user}')
await push.start()
return 0
async def checkauth(message, reg = False):
send = message.channel.send
if user_in_db(API_TOKEN, ds=message.author.id) != 'false':
return True
elif reg:
pass
else:
await send('''Пожалуйста, зарегистрируйтесь или войдите:
`!reg Nickname 1234567890`
`!login Nickname 1234567890`
Ник вводить желательно игровой.
Пароль любой.''')
def command(com, message):
# Если не бот
if message.author != bot.user:
# Если не публичный чат
if message.channel.type != discord.ChannelType.text:
if message.content.startswith(f'!{com}'):
return True
async def help(message):
send = message.channel.send
await send('''Исходный код: https://gitea.del.pw/justuser/CryptoDM
Доступные команды:
`/help - Помощь
/reg ник - Регистрация
/login ник пароль - Войти в аккаунт
/unreg - Выйти из аккаунта
/passwd пароль - Смена пароля
/bal - Баланс
/pay ник сумма - Перевод
`
''')
async def bal(message):
send = message.channel.send
if await checkauth(message):
id = user_in_db(API_TOKEN, ds=message.author.id)
coins = check_bal(API_TOKEN, id)
nick = get_nick(API_TOKEN, id)
await send(f'''Ваш баланс: `{coins}` CDM
Ник: `{nick}`''')
async def reg(message):
send = message.channel.send
if not await checkauth(message, reg=True):
global LCTIME
time_delta = datetime.now() - LCTIME
if time_delta.seconds < 1:
await send('Большая нагрузка, повторите запрос позже...')
return 0
if len(message.content.split()) == 3:
com, nick, passwd = message.content.split()
# Проверяем нет ли такого же ника
if user_in_db(API_TOKEN, nick=nick) == 'false':
if user_add(API_TOKEN, nick, passwd, ds=message.author.id) == 'OK':
await send('Вы успешно зарегистрированны!')
else:
await send('Что-то пошло не так...')
else:
await send('Уже существует пользователь с таким ником')
else:
await send('/reg ник пароль')
else:
await send('Вы уже зарегистрированны')
async def login(message):
send = message.channel.send
if len(message.content.split()) == 3:
global LCTIME
time_delta = datetime.now() - LCTIME
if time_delta.seconds < 1:
await send('Большая нагрузка, повторите запрос позже...')
return 0
com, nick, passwd = message.content.split()
id = user_in_db(API_TOKEN, nick=nick)
if get_ds(API_TOKEN, id) != 'null':
await send('Этот пользователь уже авторизован')
elif get_passwd(API_TOKEN, id) == hash(passwd):
if update_ds(API_TOKEN, id, ds=message.author.id) == 'OK':
await send('Вы успешно авторизовались!')
else:
await send('Что-то пошло не так...')
else:
await send('Пароль не совпадает')
else:
await send('!login ник пароль')
async def unreg(message):
send = message.channel.send
id = user_in_db(API_TOKEN, ds=message.author.id)
if update_ds(API_TOKEN, id, 'None') == 'OK':
await send('Вы успешно вышли из аккаунта')
async def passwd(message):
send = message.channel.send
if await checkauth(message):
if len(message.content.split()) == 2:
com, passwd = message.content.split()
id = user_in_db(API_TOKEN, ds=message.author.id)
if update_passwd(API_TOKEN, id, passwd) == 'OK':
await send('Пароль успешно изменён.')
else:
await send('Что-то пошло не так...')
else:
await send('!passwd пароль')
async def pay(message):
send = message.channel.send
if await checkauth(message):
if len(message.content.split()) == 3:
com, nick, amount = message.content.split()
if float(amount) <= 0.0001:
await send('Слишком малое или недопустимое значение.')
return 0
amount = str(float(amount)) # Защиты от 1000 нулей в начале
src_id = user_in_db(API_TOKEN, ds=message.author.id)
dst_id = user_in_db(API_TOKEN, nick=nick)
if dst_id == 'false':
await send('Не существует такого пользователя.')
else:
status = coins_transfer(API_TOKEN, src_id, dst_id, amount)
if status == 'No_money':
await send('Недостаточно средств.')
elif status == 'OK':
await send(f'''Успешно переведено `{amount}` CDM.
Адресат: `{nick}`''')
ds_dst = get_ds(API_TOKEN, dst_id)
tg_dst = get_tg(API_TOKEN, dst_id)
src_nick = get_nick(API_TOKEN, src_id)
if ds_dst != 'null':
transfer_callback('http://127.0.0.1:3333/', API_TOKEN, src_nick, nick, amount)
elif tg_dst != 'null':
print(22222)
transfer_callback('http://127.0.0.1:2222/', API_TOKEN, src_nick, nick, amount)
else:
await send('!pay ник количество')
@bot.event
async def on_message(message):
send = message.channel.send
if command('help', message):
await help(message)
elif command('reg', message):
await reg(message)
elif command('login', message):
await login(message)
elif command('unreg', message):
await unreg(message)
elif command('bal', message):
await bal(message)
elif command('passwd', message):
await passwd(message)
elif command('pay', message):
await pay(message)
# API для переводов TG->DS / ...
class Transfer_callback_api(BaseModel):
token: str
src_nick: str
dst_nick: str
amount: str
@app.post('/api/transfer_callback/')
def transfer_callback_api(it: Transfer_callback_api):
token, src_nick, dst_nick, amount = it.token, it.src_nick, it.dst_nick, it.amount
db = read()
if token in db['tokens']:
dst_id = user_in_db(API_TOKEN, nick=dst_nick)
ds_dst = int(get_ds(API_TOKEN, id=dst_id))
# Передаём в поток данные (см начало скрипта)
db = read('conf.json')
db['push_src_nick'] = src_nick
db['push_id'] = ds_dst
db['push_amount'] = amount
write(db, 'conf.json')
return 200
else:
return 'Error'
def run_api():
uvicorn.run(app, host='127.0.0.1', port=3333)
# Запускаем API для переводов
api = Thread(target=run_api)
api.Daemon = True
api.start()
# Запускаем бота
bot.run(DS_TOKEN)

16
tg.py

@ -104,6 +104,8 @@ def login(message):
elif get_passwd(API_TOKEN, id) == hash(passwd):
if update_tg(API_TOKEN, id, message.chat.id) == 'OK':
bot.reply_to(message, 'Вы успешно авторизовались!')
else:
bot.reply_to(message, 'Что-то пошло не так...')
else:
bot.reply_to(message, 'Пароль не совпадает')
else:
@ -169,9 +171,14 @@ def pay(message):
elif status == 'OK':
bot.reply_to(message, f'''Успешно переведено {hcode(amount)} CDM.
Адресат: {hcode(nick)}''', parse_mode='HTML')
bot.send_message(int(get_tg(API_TOKEN, dst_id)), f'''Вам перевели {hcode(amount)} CDM.
Отправитель: {hcode(get_nick(API_TOKEN, src_id))}''', parse_mode='HTML')
tg_dst = get_tg(API_TOKEN, dst_id)
ds_dst = get_ds(API_TOKEN, dst_id)
src_nick = get_nick(API_TOKEN, src_id)
if tg_dst != 'null':
transfer_callback('http://127.0.0.1:2222/', API_TOKEN, src_nick, nick, amount)
elif ds_dst != 'null':
transfer_callback('http://127.0.0.1:3333/', API_TOKEN, src_nick, nick, amount)
else:
bot.reply_to(message, '/pay ник количество')
@ -182,15 +189,14 @@ def checks(message):
elif message.text == 'Помощь':
help(message)
# API для переводов TG->DS / ...
class Transfer_callback(BaseModel):
class Transfer_callback_api(BaseModel):
token: str
src_nick: str
dst_nick: str
amount: str
@app.post('/api/transfer_callback/')
def transfer_callback(it: Transfer_callback):
def transfer_callback_api(it: Transfer_callback_api):
token, src_nick, dst_nick, amount = it.token, it.src_nick, it.dst_nick, it.amount
db = read()
if token in db['tokens']:

Loading…
Cancel
Save