Skip to content

Commit

Permalink
重构了设置类型
Browse files Browse the repository at this point in the history
  • Loading branch information
sudoskys committed Dec 9, 2022
1 parent 37087e8 commit d2d5634
Show file tree
Hide file tree
Showing 7 changed files with 306 additions and 151 deletions.
227 changes: 144 additions & 83 deletions App/Event.py

Large diffs are not rendered by default.

40 changes: 23 additions & 17 deletions Config/config.json
Original file line number Diff line number Diff line change
@@ -1,19 +1,25 @@
{
"statu": true,
"input_limit": 200,
"token_limit": 1000,
"usage_limit": 15000,
"per_user_limit": 1,
"usercold_time": 10,
"groupcold_time": 1,
"whiteUserSwitch": true,
"whiteGroupSwitch": false,
"blockGroup": [],
"blockUser": [],
"whiteGroup": [],
"whiteUser": [
"5275155445"
],
"Model": {
}
"statu": true,
"input_limit": 200,
"token_limit": 1000,
"hour_limit": 15000,
"per_user_limit": 1,
"usercold_time": 10,
"groupcold_time": 1,
"User": {
"5275155445": {
"white": false,
"block": false,
"usage": 1
}
},
"Group": {
"1001583282373": {
"white": false,
"block": false
}
},
"whiteUserSwitch": true,
"whiteGroupSwitch": false,
"Model": {}
}
10 changes: 6 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -182,9 +182,9 @@ kill -9
| `/see_api_key` | 现在几个 Api key | |
| `/del_api_key` +key | 删除 Api key | 可跟多参数,空格分割 |
| `/add_api_key` +key | 增加 Api key | 可跟多参数,空格分割 |
| `/set_user_usage_limit` | 用户分配总额度 | 1 为无限制 按用户计量 |
| `/set_user_hour_limit` | 用户分配总额度 | 1 为无限制 按用户计量 |
| `/set_hour_limit` | 用户小时可用量 | 1 为无限制 按用户计量 |
| `/reset_user_usage_limit`+userID | 重置用户分配额度 | 按用户计量 可跟多参数,空格分割 |
| `/reset_user_hour_limit`+userID | 重置用户分配额度 | 按用户计量 可跟多参数,空格分割 |

### 样表

Expand All @@ -199,8 +199,8 @@ see_api_key - 现在几个 Api key
del_api_key - 删除 Api key
add_api_key - 增加 Api key
config - 获取/备份热配置文件
set_user_usage_limit - 设置用户总额限度
reset_user_usage_limit - 重置用户额度
set_user_hour_limit - 设置用户总额限度
reset_user_hour_limit - 重置用户额度
set_hour_limit - 设置用户小时限额
add_block_group - 禁止群组
del_block_group - 解禁群组
Expand All @@ -225,6 +225,8 @@ close - 关闭机器人

``analysis.json`` 是频率统计,60s 内的请求次数。

还有 total usage ,这个不包含所有用量数据,只是从 redis 拉取下来了而已

### Config.json

会自动合并缺失的键值进行修复。
Expand Down
2 changes: 1 addition & 1 deletion analysis.json
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
{
"frequency": 2,
"frequency": 0,
"usage": {
"5275155445": 1468
}
Expand Down
19 changes: 8 additions & 11 deletions setup.sh
Original file line number Diff line number Diff line change
Expand Up @@ -93,40 +93,37 @@ run() {
mkdir "$config"
fi


# 备份配置文件
if [ -f "${dir}/config.json" ]; then
echox skyBlue "移动配置文件:backup ${dir}/config.json to ${config} ...."
cp -f "${dir}/config.json" "$config"
fi

# 备份配置文件
# 统计数据
if [ -f "${dir}/analysis.json" ]; then
echox skyBlue "移动配置文件:backup ${dir}/analysis.json to ${dataBack} ...."
echox skyBlue "备份统计数据:backup ${dir}/analysis.json to ${dataBack} ...."
cp -f "${dir}/analysis.json" "$dataBack"
fi
fi



# 备份运行数据
if [ -d "$data" ]; then
echox skyBlue "备份运行数据:Copy run data to ${dataBack}...."
cp -rf "$data" "$dataBack" #文件夹目录 文件夹上级
fi

# 备份配置数据
if [ -d "$config" ]; then
echox skyBlue "备份运行数据:Copy Config to ${dataBack}...."
cp -rf "$config" "$dataBack" #文件夹目录 文件夹上级
fi
read -r -p "请问,是否使用可能存在的上一次配置?Do you want to update your app with probably exist old data?${dir} y/n?[default=y]" input
read -r -p "HELLO!请问,是否使用可能存在的上一次配置?Update your app with probably EXIST old data?${dir} y/n?[default=y]" input
if [ -z "${input}" ]; then
input=y
fi


case $input in
[nN][oO] | [nN])
echox red "We will reinstall a pure app...."
echox red "Reinstalling A Pure APP....BUT IF YOU WANT TO RECOVER OLD DATA,PLEASE CHECK /tmp DIR"
rm -rf "${dir}"
Gitpull
dependenceInit
Expand All @@ -139,8 +136,8 @@ run() {
# cp -f "${dataBack}/Captcha.toml" "$dir" #文件夹目录 文件夹上级
# fi
if [ -f "${dataBack}/analysis.json" ]; then
echox green "恢复配置文件:Reuse the analysis.json from ${dataBack}...."
cp -f "${dataBack}/analysis.json" "$dir" #文件夹目录 文件夹上级
echox green "恢复配置文件:Reuse the analysis.json from ${dataBack}...."
cp -f "${dataBack}/analysis.json" "$dir" #文件夹目录 文件夹上级
fi
if [ -d "${dataBack}/Config" ]; then
echox green "恢复配置库:Reuse the Config from ${dataBack}...."
Expand Down
125 changes: 98 additions & 27 deletions utils/Chat.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,14 +6,12 @@
import json
import time
from typing import Union

from utils.Data import DefaultData, DataWorker, DictUpdate
from pydantic import BaseModel
from utils.Data import DefaultData, DataWorker, DictUpdate, Usage_Data
from loguru import logger

MsgsRecordUtils = DataWorker(prefix="Open_Ai_bot_msg_record")
# 工具数据类型
DataUtils = DataWorker(prefix="Open_Ai_bot_")
MsgsRecordUtils = DataWorker(prefix="Open_Ai_bot_msg_record")

global _csonfig

Expand All @@ -34,6 +32,80 @@ def save_csonfig():
json.dump(_csonfig, f, indent=4, ensure_ascii=False)


class UserManger(object):
def __init__(self, uid: int):
"""
"""
self._uid = str(abs(uid))
load_csonfig()
user = _csonfig["User"].get(self._uid)
if not user:
user = {}
self._renew(user)

def _renew(self, item):
"""
UpDTA进去
:param item:
:return:
"""
load_csonfig()
# 更新默认设置的必要结构
_item = item
_reply = DefaultData.defaultUser()
DictUpdate.dict_update(_reply, _item)
_csonfig["User"][self._uid] = _reply
save_csonfig()

def save(self, setting: dict = None):
if not setting:
return None
_reply = DefaultData.defaultUser()
DictUpdate.dict_update(_reply, setting)
return self._renew(_reply)

def read(self, key) -> Union[any]:
_item = _csonfig["User"].get(self._uid)
return _item.get(key)


class GroupManger(object):
def __init__(self, uid: int):
"""
"""
self._uid = str(abs(uid))
load_csonfig()
user = _csonfig["Group"].get(self._uid)
if not user:
user = {}
self._renew(user)

def _renew(self, item):
"""
UpDTA进去
:param item:
:return:
"""
load_csonfig()
# 更新默认设置的必要结构
_item = item
_reply = DefaultData.defaultGroup()
DictUpdate.dict_update(_reply, _item)
_csonfig["Group"][self._uid] = _reply
save_csonfig()

def save(self, setting: dict = None):
if not setting:
return None
_reply = DefaultData.defaultGroup()
DictUpdate.dict_update(_reply, setting)
return self._renew(_reply)

def read(self, key) -> Union[any]:
_item = _csonfig["Group"].get(self._uid)
return _item.get(key)


class Utils(object):
@staticmethod
def forget_me(user_id, group_id):
Expand Down Expand Up @@ -134,13 +206,6 @@ def get_response_usage(response):
return usage


class Usage_Data(BaseModel):
user: str
now: int
usage: int
total_usage: int


class Usage(object):
def __init__(self, uid: Union[int, str]):
self.__uid = str(uid)
Expand Down Expand Up @@ -174,24 +239,30 @@ def isOutUsage(self):
load_csonfig()
key_time = int(time.strftime("%Y%m%d%H", time.localtime()))
GET = self.__get_usage()
if GET:
if GET.usage < _csonfig["usage_limit"]:
return {"status": False, "use": GET.dict(), "time": key_time}
else:
# 没有设置限制
if _csonfig["usage_limit"] < 2:
return {"status": False, "use": GET.dict(), "time": key_time}

if GET.total_usage < _csonfig["per_user_limit"]:
return {"status": False, "use": GET.dict(), "time": key_time}
else:
# 没有设置限制
if _csonfig["per_user_limit"] < 2:
return {"status": False, "use": GET.dict(), "time": key_time}
else:
# 居然没有记录
if not GET:
GET = self.__set_usage(now=key_time, usage=0, total_usage=0)
return {"status": False, "use": GET.dict(), "time": key_time}
return {"status": True, "use": GET.dict(), "time": key_time}
# 按照异常返回的逻辑
# 小时计量
if _csonfig["hour_limit"] > 1:
# 设定了,又超额了
if GET.usage > _csonfig["hour_limit"]:
return {"status": True, "use": GET.dict(), "time": key_time}
# 用户额度计量---特殊额度---还有通用额度
USER_ = _csonfig["per_user_limit"]
_LIMIT = UserManger(int(self.__uid)).read("usage")
if not isinstance(_LIMIT, int):
_LIMIT = 10000
if _LIMIT != 1:
USER_ = _LIMIT
# 没有设置限制
if USER_ == 1 and _LIMIT == 1:
return {"status": False, "use": GET.dict(), "time": key_time}
# 覆盖完毕
if GET.total_usage > USER_:
return {"status": True, "use": GET.dict(), "time": key_time}
return {"status": False, "use": GET.dict(), "time": key_time}

def renewUsage(self, usage: int):
key_time = int(time.strftime("%Y%m%d%H", time.localtime()))
Expand Down
34 changes: 26 additions & 8 deletions utils/Data.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,12 @@
import ast
import json
import pathlib

# 缓冲
from collections import OrderedDict
from datetime import datetime, timedelta

from utils.Base import ReadConfig
from loguru import logger
from pydantic import BaseModel

redis_installed = True

Expand All @@ -22,6 +21,13 @@
redis_installed = False


class Usage_Data(BaseModel):
user: str
now: int
usage: int
total_usage: int


class Api_keys(object):
"""
管理 Api
Expand Down Expand Up @@ -110,17 +116,14 @@ def defaultConfig():
"statu": True,
"input_limit": 250,
"token_limit": 300,
"usage_limit": 15000,
"hour_limit": 15000,
"per_user_limit": 1,
"usercold_time": 10,
"groupcold_time": 1,
"User": {},
"Group": {},
"whiteUserSwitch": True,
"whiteGroupSwitch": True,
"blockGroup": [],
"blockUser": [],
"whiteGroup": [],
"whiteUser": [
],
"Model": {
}
}
Expand Down Expand Up @@ -151,6 +154,21 @@ def setAnalysis(self,
with open("./analysis.json", "w", encoding="utf8") as f:
json.dump(_Analysis, f, indent=4, ensure_ascii=False)

@staticmethod
def defaultUser():
return {"white": False,
"block": False,
"usage": 1
}

# 单独配额,如果这里不是 1,优先按这这分配额度
@staticmethod
def defaultGroup():
return {
"white": False,
"block": False
}


class ExpiringDict(OrderedDict):
"""
Expand Down

0 comments on commit d2d5634

Please sign in to comment.