Расчёт статистики сразу в файл, начисление CDM за время сразу

This commit is contained in:
Your Name 2024-11-29 12:10:01 +03:00
parent 967d49506e
commit 3d550af0f6
3 changed files with 118 additions and 118 deletions

159
api.py
View File

@ -22,21 +22,53 @@ def token_check(token):
return False return False
def stat_run(cdm_change): 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') date = datetime.today().strftime('%Y-%m-%d')
stat = read('stat.json')
if date in stat: if date in stat:
stat[date]['gbal'] += cdm_change stat[date]['gbal'] += cdm_change
write(stat, 'stat.json')
else: else:
db = read() stat[date] = {'gbal': sum(bals), 'time2cdm': 0}
bal = 0
for id in db['id']:
bal += db['id'][id]['bal']
stat[date] = {'gbal': bal, 'time2cdm': 0}
write(stat, 'stat.json')
def format_sign(number):
return f"+{number}" if number > 0 else f"{number}" 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)
stat[date] = stats
write(stat, 'stat.json')
class User_in_db(BaseModel): class User_in_db(BaseModel):
token: str token: str
@ -73,7 +105,6 @@ def gen_id():
db = read() db = read()
for i in range(1,100000): for i in range(1,100000):
check = str(i) check = str(i)
print(db)
if check not in db['id']: if check not in db['id']:
return str(i) return str(i)
return 'Full?' return 'Full?'
@ -90,10 +121,10 @@ class User_add(BaseModel):
def user_add(it: 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 token, id, tg, ds, mine, nick, passwd = it.token, it.id, it.tg, it.ds, it.mine, it.nick, it.passwd
id = gen_id() id = gen_id()
print(id)
if token_check(token): if token_check(token):
db = read() 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 db['nick'][nick] = id
if tg: if tg:
db['tg'][tg] = id db['tg'][tg] = id
@ -291,20 +322,21 @@ def update_passwd(it: Update_passwd):
else: else:
return 'Error' return 'Error'
class Update_time(BaseModel): # DEPRECATED
token: str # class Update_time(BaseModel):
id: str # token: str
time: str # id: str
@app.post('/api/update_time/') # time: str
def update_time(it: Update_time): # @app.post('/api/update_time/')
token, id, time = it.token, it.id, int(it.time) # def update_time(it: Update_time):
if token_check(token): # token, id, time = it.token, it.id, int(it.time)
db = read() # if token_check(token):
db['id'][id]['time'] = time # db = read()
write(db) # db['id'][id]['time'] = time
return 'OK' # write(db)
else: # return 'OK'
return 'Error' # else:
# return 'Error'
class Add_time(BaseModel): class Add_time(BaseModel):
@ -315,9 +347,26 @@ class Add_time(BaseModel):
def add_time(it: Add_time): def add_time(it: Add_time):
token, id, time = it.token, it.id, int(it.time) token, id, time = it.token, it.id, int(it.time)
if token_check(token): if token_check(token):
stat_run(0)
course = read('conf.json')['time2cdm']
amount = time*course
# Пополнение баланса
db = read() 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) write(db)
# Глобально
stat = read('stat.json')
stat[date]['time2cdm'] += amount
write(stat, 'stat.json')
return 'OK' return 'OK'
else: else:
return 'Error' return 'Error'
@ -330,7 +379,15 @@ class Check_bal(BaseModel):
def check_bal(it: Check_bal): def check_bal(it: Check_bal):
token, id = it.token, it.id token, id = it.token, it.id
if token_check(token): if token_check(token):
stat_run(0)
db = read() 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'] return db['id'][id]['bal']
else: else:
return 'Error' return 'Error'
@ -395,15 +452,15 @@ def get_passwd(it: Get_passwd):
else: else:
return 'Error' return 'Error'
class Get_time(BaseModel): class Get_time2cdm(BaseModel):
token: str token: str
id: str id: str
@app.post('/api/get_time/') @app.post('/api/get_time2cdm/')
def get_time(it: Get_time): def get_time(it: Get_time2cdm):
token, id = it.token, it.id token, id = it.token, it.id
if token_check(token): if token_check(token):
db = read() db = read()
return db['id'][id]['time'] return db['id'][id]['time2cdm'][0]
else: else:
return 'Error' return 'Error'
@ -413,44 +470,10 @@ class Get_stat(BaseModel):
def get_stat(it: Get_stat): def get_stat(it: Get_stat):
token = it.token token = it.token
if token_check(token): if token_check(token):
# Общий баланс, среднее значение, медиана
# Низшее значение, высшее значение
# Изменение баланса и time2cdm
# Прирост за счёт алмазов, за счёт time2cdm
stat_run(0) stat_run(0)
stats = {'gbal': 0, 'average': 0, 'median': 0, 'time2cdm': 0, db = read('stat.json')
'gbal_delta': '0', 'time2cdm_delta': '',
'min': 0, 'max': 0,
'up_diamond': 0}
stat = read('stat.json')
date = datetime.today().strftime('%Y-%m-%d') date = datetime.today().strftime('%Y-%m-%d')
yesterday = (datetime.today() - timedelta(days=1)).strftime('%Y-%m-%d') stats = db[date]
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)
return stats return stats
else: else:
return 'Error' return 'Error'

View File

@ -121,9 +121,9 @@ def get_passwd(token, id):
data = {'token': token, 'id': id} data = {'token': token, 'id': id}
return call('api/get_passwd/', data) return call('api/get_passwd/', data)
def get_time(token, id): def get_time2cdm(token, id):
data = {'token': token, 'id': id} data = {'token': token, 'id': id}
return call('api/get_time/', data) return call('api/get_time2cdm/', data)
def get_stat(token): def get_stat(token):
data = {'token': token} data = {'token': token}

59
tg.py
View File

@ -58,12 +58,10 @@ def help(message):
{hcode("""/help - Помощь {hcode("""/help - Помощь
/reg ник - Регистрация /reg ник - Регистрация
/login ник пароль - Войти в аккаунт /login ник пароль - Войти в аккаунт
/unreg - Выйти из аккаунта
/passwd пароль - Смена пароля /passwd пароль - Смена пароля
/nick ник - Смена ника /nick ник - Смена ника
/bal - Баланс /bal - Баланс
/pay ник сумма - Перевод /pay ник сумма - Перевод
/time2cdm - Конвертация времени на сервере в CDM
/stats - Статистика /stats - Статистика
""")} """)}
''', parse_mode='HTML') ''', parse_mode='HTML')
@ -101,7 +99,6 @@ def login(message):
return 0 return 0
com, nick, passwd = message.text.split() com, nick, passwd = message.text.split()
id = user_in_db(API_TOKEN, nick=nick) id = user_in_db(API_TOKEN, nick=nick)
print('!!!!', get_tg(API_TOKEN, id))
if get_tg(API_TOKEN, id) != 'null': if get_tg(API_TOKEN, id) != 'null':
bot.reply_to(message, 'Этот пользователь уже авторизован') bot.reply_to(message, 'Этот пользователь уже авторизован')
elif get_passwd(API_TOKEN, id) == hash(passwd): elif get_passwd(API_TOKEN, id) == hash(passwd):
@ -114,21 +111,12 @@ def login(message):
else: else:
bot.reply_to(message, '/login ник пароль') 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'])
@bot.message_handler(commands=['unreg']) # def unreg(message):
def unreg(message): # id = user_in_db(API_TOKEN, tg=message.chat.id)
id = user_in_db(API_TOKEN, tg=message.chat.id) # if update_tg(API_TOKEN, id, 'None') == 'OK':
print(int(id)) # bot.reply_to(message, 'Вы успешно вышли из аккаунта')
print("1")
if user_del(API_TOKEN, id) == 'OK':
bot.reply_to(message, 'OK')
'''
@bot.message_handler(commands=['passwd']) @bot.message_handler(commands=['passwd'])
def passwd(message): def passwd(message):
@ -161,12 +149,11 @@ def nick(message):
def bal(message): def bal(message):
if checkauth(message): if checkauth(message):
id = user_in_db(API_TOKEN, tg=message.chat.id) 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) nick = get_nick(API_TOKEN, id)
time = int(get_time(API_TOKEN, id)) time2cdm = round(float(get_time2cdm(API_TOKEN, id)), 4)
hours = time//3600 ; minutes = (time - hours*3600)//60 bot.reply_to(message, f'''Ваш баланс: {hcode(f"{coins}")} CDM
bot.reply_to(message, f'''Ваш баланс: {hcode(coins)} CDM Валюта за время (сегодня): {hcode(f"{time2cdm}")}
Время на сервере: {hcode(f"{hours}:{minutes}")}
Ник: {hcode(nick)}''', parse_mode='HTML') Ник: {hcode(nick)}''', parse_mode='HTML')
@ -201,29 +188,20 @@ def pay(message):
else: else:
bot.reply_to(message, '/pay ник количество') bot.reply_to(message, '/pay ник количество')
@bot.message_handler(commands=['time2cdm']) def format_sign(number):
def time2cdm(message): if number > 0:
if checkauth(message): return f"+{number}"
id = user_in_db(API_TOKEN, tg=message.chat.id) elif number == 0:
course = read('conf.json')['time2cdm'] return f"{number}"
time = int(get_time(API_TOKEN, id)) else:
amount = time*course return f"-{number}"
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')
@bot.message_handler(commands=['stats']) @bot.message_handler(commands=['stats'])
def stats(message): def stats(message):
if checkauth(message): if checkauth(message):
data = get_stat(API_TOKEN) data = get_stat(API_TOKEN)
bal = f'Баланс ({data["gbal_delta"]})' bal = f'Баланс ({format_sign(data["gbal_delta"])})'
t2cdm = f'Time2cdm ({data["time2cdm_delta"]})' t2cdm = f'Time2cdm ({format_sign(data["time2cdm_delta"])})'
max_len = max(len(bal), len(t2cdm), 19) max_len = max(len(bal), len(t2cdm), 19)
bot.reply_to(message, f''' bot.reply_to(message, f'''
```json ```json
@ -278,7 +256,6 @@ def transfer_callback_api(it: Transfer_callback_api):
if token in db['tokens']: if token in db['tokens']:
dst_id = user_in_db(API_TOKEN, nick=dst_nick) dst_id = user_in_db(API_TOKEN, nick=dst_nick)
tg_dst = int(get_tg(API_TOKEN, id=dst_id)) tg_dst = int(get_tg(API_TOKEN, id=dst_id))
print(tg_dst)
bot.send_message(tg_dst, f'''Вам перевели {hcode(amount)} CDM. bot.send_message(tg_dst, f'''Вам перевели {hcode(amount)} CDM.
Отправитель: {hcode(src_nick)}''', parse_mode='HTML') Отправитель: {hcode(src_nick)}''', parse_mode='HTML')