Расчёт статистики сразу в файл, начисление CDM за время сразу
This commit is contained in:
parent
967d49506e
commit
3d550af0f6
171
api.py
171
api.py
@ -22,21 +22,53 @@ def token_check(token):
|
||||
return False
|
||||
|
||||
def stat_run(cdm_change):
|
||||
stat = read('stat.json')
|
||||
# Общий баланс, среднее значение, медиана
|
||||
# Низшее значение, высшее значение
|
||||
# Изменение баланса и time2cdm
|
||||
# Прирост за счёт алмазов, за счёт time2cdm
|
||||
|
||||
# Получаем все балансы
|
||||
db = read()
|
||||
bals = []
|
||||
for id in db['id']:
|
||||
bals.append(db['id'][id]['bal'])
|
||||
|
||||
date = datetime.today().strftime('%Y-%m-%d')
|
||||
stat = read('stat.json')
|
||||
if date in stat:
|
||||
stat[date]['gbal'] += cdm_change
|
||||
write(stat, 'stat.json')
|
||||
else:
|
||||
db = read()
|
||||
bal = 0
|
||||
for id in db['id']:
|
||||
bal += db['id'][id]['bal']
|
||||
stat[date] = {'gbal': bal, 'time2cdm': 0}
|
||||
write(stat, 'stat.json')
|
||||
stat[date] = {'gbal': sum(bals), 'time2cdm': 0}
|
||||
|
||||
|
||||
stats = {'gbal': 0, 'average': 0, 'median': 0, 'time2cdm': 0,
|
||||
'gbal_delta': '0', 'time2cdm_delta': '',
|
||||
'min': 0, 'max': 0,
|
||||
'up_diamond': 0}
|
||||
|
||||
date = datetime.today().strftime('%Y-%m-%d')
|
||||
yesterday = (datetime.today() - timedelta(days=1)).strftime('%Y-%m-%d')
|
||||
if yesterday in stat:
|
||||
gbal_y = stat[yesterday]['gbal']
|
||||
time2cdm_y = stat[yesterday]['time2cdm']
|
||||
else:
|
||||
gbal_y, time2cdm_y = 0, 0
|
||||
time2cdm = stat[date]['time2cdm']
|
||||
gbal = stat[date]['gbal']
|
||||
|
||||
# Заполняем данные
|
||||
stats['gbal'] = round(gbal, 3)
|
||||
stats['average'] = round(sum([x for x in bals if x != 0])/len([x for x in bals if x != 0]), 3)
|
||||
stats['median'] = round(median([x for x in bals if x != 0]), 3)
|
||||
stats['time2cdm'] = round(time2cdm, 3)
|
||||
stats['time2cdm_delta'] = round(time2cdm-time2cdm_y, 3)
|
||||
stats['gbal_delta'] = round(gbal-gbal_y, 3)
|
||||
stats['min'] = round(min([x for x in bals if x != 0]), 3)
|
||||
stats['max'] = round(max(bals), 3)
|
||||
stats['up_diamond'] = round(gbal - (gbal_y + time2cdm), 3)
|
||||
|
||||
def format_sign(number):
|
||||
return f"+{number}" if number > 0 else f"{number}"
|
||||
stat[date] = stats
|
||||
write(stat, 'stat.json')
|
||||
|
||||
class User_in_db(BaseModel):
|
||||
token: str
|
||||
@ -73,7 +105,6 @@ 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?'
|
||||
@ -90,10 +121,10 @@ class User_add(BaseModel):
|
||||
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, 'time': 0}
|
||||
db['id'][id] = {'tg': tg, 'ds': ds, 'mine': mine, 'nick': nick, 'passwd': passwd
|
||||
, 'bal': 0.0, 'time2cdm': [0, datetime.today().strftime('%Y-%m-%d')]}
|
||||
db['nick'][nick] = id
|
||||
if tg:
|
||||
db['tg'][tg] = id
|
||||
@ -291,20 +322,21 @@ def update_passwd(it: Update_passwd):
|
||||
else:
|
||||
return 'Error'
|
||||
|
||||
class Update_time(BaseModel):
|
||||
token: str
|
||||
id: str
|
||||
time: str
|
||||
@app.post('/api/update_time/')
|
||||
def update_time(it: Update_time):
|
||||
token, id, time = it.token, it.id, int(it.time)
|
||||
if token_check(token):
|
||||
db = read()
|
||||
db['id'][id]['time'] = time
|
||||
write(db)
|
||||
return 'OK'
|
||||
else:
|
||||
return 'Error'
|
||||
# DEPRECATED
|
||||
# class Update_time(BaseModel):
|
||||
# token: str
|
||||
# id: str
|
||||
# time: str
|
||||
# @app.post('/api/update_time/')
|
||||
# def update_time(it: Update_time):
|
||||
# token, id, time = it.token, it.id, int(it.time)
|
||||
# if token_check(token):
|
||||
# db = read()
|
||||
# db['id'][id]['time'] = time
|
||||
# write(db)
|
||||
# return 'OK'
|
||||
# else:
|
||||
# return 'Error'
|
||||
|
||||
|
||||
class Add_time(BaseModel):
|
||||
@ -315,9 +347,26 @@ class Add_time(BaseModel):
|
||||
def add_time(it: Add_time):
|
||||
token, id, time = it.token, it.id, int(it.time)
|
||||
if token_check(token):
|
||||
stat_run(0)
|
||||
course = read('conf.json')['time2cdm']
|
||||
amount = time*course
|
||||
# Пополнение баланса
|
||||
db = read()
|
||||
db['id'][id]['time'] += time
|
||||
db['id'][id]['bal'] += amount
|
||||
# Статистика
|
||||
date = datetime.today().strftime('%Y-%m-%d')
|
||||
# Для пользователя
|
||||
t2c_date = db['id'][id]['time2cdm'][1]
|
||||
if t2c_date != date:
|
||||
db['id'][id]['time2cdm'][0] = amount
|
||||
db['id'][id]['time2cdm'][1] = date
|
||||
else:
|
||||
db['id'][id]['time2cdm'][0] += amount
|
||||
write(db)
|
||||
# Глобально
|
||||
stat = read('stat.json')
|
||||
stat[date]['time2cdm'] += amount
|
||||
write(stat, 'stat.json')
|
||||
return 'OK'
|
||||
else:
|
||||
return 'Error'
|
||||
@ -328,12 +377,20 @@ class Check_bal(BaseModel):
|
||||
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'
|
||||
token, id = it.token, it.id
|
||||
if token_check(token):
|
||||
stat_run(0)
|
||||
db = read()
|
||||
# Если дата time2cdm прошла - обнулить баланс
|
||||
date = datetime.today().strftime('%Y-%m-%d')
|
||||
t2c_date = db['id'][id]['time2cdm'][1]
|
||||
if t2c_date != date:
|
||||
db['id'][id]['time2cdm'][0] = 0
|
||||
db['id'][id]['time2cdm'][1] = date
|
||||
write(db)
|
||||
return db['id'][id]['bal']
|
||||
else:
|
||||
return 'Error'
|
||||
|
||||
class Get_nick(BaseModel):
|
||||
token: str
|
||||
@ -395,15 +452,15 @@ def get_passwd(it: Get_passwd):
|
||||
else:
|
||||
return 'Error'
|
||||
|
||||
class Get_time(BaseModel):
|
||||
class Get_time2cdm(BaseModel):
|
||||
token: str
|
||||
id: str
|
||||
@app.post('/api/get_time/')
|
||||
def get_time(it: Get_time):
|
||||
@app.post('/api/get_time2cdm/')
|
||||
def get_time(it: Get_time2cdm):
|
||||
token, id = it.token, it.id
|
||||
if token_check(token):
|
||||
db = read()
|
||||
return db['id'][id]['time']
|
||||
return db['id'][id]['time2cdm'][0]
|
||||
else:
|
||||
return 'Error'
|
||||
|
||||
@ -413,44 +470,10 @@ class Get_stat(BaseModel):
|
||||
def get_stat(it: Get_stat):
|
||||
token = it.token
|
||||
if token_check(token):
|
||||
# Общий баланс, среднее значение, медиана
|
||||
# Низшее значение, высшее значение
|
||||
# Изменение баланса и time2cdm
|
||||
# Прирост за счёт алмазов, за счёт time2cdm
|
||||
stat_run(0)
|
||||
stats = {'gbal': 0, 'average': 0, 'median': 0, 'time2cdm': 0,
|
||||
'gbal_delta': '0', 'time2cdm_delta': '',
|
||||
'min': 0, 'max': 0,
|
||||
'up_diamond': 0}
|
||||
|
||||
stat = read('stat.json')
|
||||
db = read('stat.json')
|
||||
date = datetime.today().strftime('%Y-%m-%d')
|
||||
yesterday = (datetime.today() - timedelta(days=1)).strftime('%Y-%m-%d')
|
||||
if yesterday in stat:
|
||||
gbal_y = stat[yesterday]['gbal']
|
||||
time2cdm_y = stat[yesterday]['time2cdm']
|
||||
else:
|
||||
gbal_y, time2cdm_y = 0, 0
|
||||
gbal = stat[date]['gbal']
|
||||
time2cdm = stat[date]['time2cdm']
|
||||
|
||||
# Получаем все балансы
|
||||
db = read()
|
||||
bals = []
|
||||
for id in db['id']:
|
||||
bals.append(db['id'][id]['bal'])
|
||||
|
||||
# Заполняем данные
|
||||
stats['gbal'] = round(gbal, 3)
|
||||
stats['average'] = round(sum(bals)/len(bals), 3)
|
||||
stats['median'] = round(median(bals), 3)
|
||||
stats['time2cdm'] = round(time2cdm, 3)
|
||||
stats['gbal_delta'] = format_sign(round(gbal-gbal_y, 3))
|
||||
stats['time2cdm_delta'] = format_sign(round(time2cdm-time2cdm_y, 3))
|
||||
stats['min'] = round(min([x for x in bals if x != 0]), 3)
|
||||
stats['max'] = round(max(bals), 3)
|
||||
stats['up_diamond'] = round(gbal - (gbal_y + time2cdm), 3)
|
||||
|
||||
stats = db[date]
|
||||
return stats
|
||||
else:
|
||||
return 'Error'
|
||||
|
@ -121,9 +121,9 @@ def get_passwd(token, id):
|
||||
data = {'token': token, 'id': id}
|
||||
return call('api/get_passwd/', data)
|
||||
|
||||
def get_time(token, id):
|
||||
def get_time2cdm(token, id):
|
||||
data = {'token': token, 'id': id}
|
||||
return call('api/get_time/', data)
|
||||
return call('api/get_time2cdm/', data)
|
||||
|
||||
def get_stat(token):
|
||||
data = {'token': token}
|
||||
|
61
tg.py
61
tg.py
@ -58,12 +58,10 @@ def help(message):
|
||||
{hcode("""/help - Помощь
|
||||
/reg ник - Регистрация
|
||||
/login ник пароль - Войти в аккаунт
|
||||
/unreg - Выйти из аккаунта
|
||||
/passwd пароль - Смена пароля
|
||||
/nick ник - Смена ника
|
||||
/bal - Баланс
|
||||
/pay ник сумма - Перевод
|
||||
/time2cdm - Конвертация времени на сервере в CDM
|
||||
/stats - Статистика
|
||||
""")}
|
||||
''', parse_mode='HTML')
|
||||
@ -101,7 +99,6 @@ def login(message):
|
||||
return 0
|
||||
com, nick, passwd = message.text.split()
|
||||
id = user_in_db(API_TOKEN, nick=nick)
|
||||
print('!!!!', get_tg(API_TOKEN, id))
|
||||
if get_tg(API_TOKEN, id) != 'null':
|
||||
bot.reply_to(message, 'Этот пользователь уже авторизован')
|
||||
elif get_passwd(API_TOKEN, id) == hash(passwd):
|
||||
@ -114,21 +111,12 @@ def login(message):
|
||||
else:
|
||||
bot.reply_to(message, '/login ник пароль')
|
||||
|
||||
@bot.message_handler(commands=['unreg'])
|
||||
def unreg(message):
|
||||
id = user_in_db(API_TOKEN, tg=message.chat.id)
|
||||
if update_tg(API_TOKEN, id, 'None') == 'OK':
|
||||
bot.reply_to(message, 'Вы успешно вышли из аккаунта')
|
||||
|
||||
'''
|
||||
@bot.message_handler(commands=['unreg'])
|
||||
def unreg(message):
|
||||
id = user_in_db(API_TOKEN, tg=message.chat.id)
|
||||
print(int(id))
|
||||
print("1")
|
||||
if user_del(API_TOKEN, id) == 'OK':
|
||||
bot.reply_to(message, 'OK')
|
||||
'''
|
||||
# @bot.message_handler(commands=['unreg'])
|
||||
# def unreg(message):
|
||||
# id = user_in_db(API_TOKEN, tg=message.chat.id)
|
||||
# if update_tg(API_TOKEN, id, 'None') == 'OK':
|
||||
# bot.reply_to(message, 'Вы успешно вышли из аккаунта')
|
||||
|
||||
@bot.message_handler(commands=['passwd'])
|
||||
def passwd(message):
|
||||
@ -161,12 +149,11 @@ def nick(message):
|
||||
def bal(message):
|
||||
if checkauth(message):
|
||||
id = user_in_db(API_TOKEN, tg=message.chat.id)
|
||||
coins = check_bal(API_TOKEN, id)
|
||||
coins = round(float(check_bal(API_TOKEN, id)), 4)
|
||||
nick = get_nick(API_TOKEN, id)
|
||||
time = int(get_time(API_TOKEN, id))
|
||||
hours = time//3600 ; minutes = (time - hours*3600)//60
|
||||
bot.reply_to(message, f'''Ваш баланс: {hcode(coins)} CDM
|
||||
Время на сервере: {hcode(f"{hours}:{minutes}")}
|
||||
time2cdm = round(float(get_time2cdm(API_TOKEN, id)), 4)
|
||||
bot.reply_to(message, f'''Ваш баланс: {hcode(f"{coins}")} CDM
|
||||
Валюта за время (сегодня): {hcode(f"{time2cdm}")}
|
||||
|
||||
Ник: {hcode(nick)}''', parse_mode='HTML')
|
||||
|
||||
@ -201,29 +188,20 @@ def pay(message):
|
||||
else:
|
||||
bot.reply_to(message, '/pay ник количество')
|
||||
|
||||
@bot.message_handler(commands=['time2cdm'])
|
||||
def time2cdm(message):
|
||||
if checkauth(message):
|
||||
id = user_in_db(API_TOKEN, tg=message.chat.id)
|
||||
course = read('conf.json')['time2cdm']
|
||||
time = int(get_time(API_TOKEN, id))
|
||||
amount = time*course
|
||||
if update_time(API_TOKEN, id, '0'):
|
||||
if coins_add(API_TOKEN, id, str(amount)):
|
||||
# Статистика
|
||||
stat = read('stat.json')
|
||||
date = datetime.today().strftime('%Y-%m-%d')
|
||||
stat[date]['time2cdm'] += amount
|
||||
write(stat, 'stat.json')
|
||||
bot.reply_to(message, f'''Вы успешно конвертировали время на сервере в {hcode(str(amount))} CDM.'''
|
||||
, parse_mode='HTML')
|
||||
|
||||
def format_sign(number):
|
||||
if number > 0:
|
||||
return f"+{number}"
|
||||
elif number == 0:
|
||||
return f"{number}"
|
||||
else:
|
||||
return f"-{number}"
|
||||
|
||||
@bot.message_handler(commands=['stats'])
|
||||
def stats(message):
|
||||
if checkauth(message):
|
||||
data = get_stat(API_TOKEN)
|
||||
bal = f'Баланс ({data["gbal_delta"]})'
|
||||
t2cdm = f'Time2cdm ({data["time2cdm_delta"]})'
|
||||
bal = f'Баланс ({format_sign(data["gbal_delta"])})'
|
||||
t2cdm = f'Time2cdm ({format_sign(data["time2cdm_delta"])})'
|
||||
max_len = max(len(bal), len(t2cdm), 19)
|
||||
bot.reply_to(message, f'''
|
||||
```json
|
||||
@ -278,7 +256,6 @@ def transfer_callback_api(it: Transfer_callback_api):
|
||||
if token in db['tokens']:
|
||||
dst_id = user_in_db(API_TOKEN, nick=dst_nick)
|
||||
tg_dst = int(get_tg(API_TOKEN, id=dst_id))
|
||||
print(tg_dst)
|
||||
bot.send_message(tg_dst, f'''Вам перевели {hcode(amount)} CDM.
|
||||
|
||||
Отправитель: {hcode(src_nick)}''', parse_mode='HTML')
|
||||
|
Loading…
Reference in New Issue
Block a user