88 lines
2.8 KiB
Python
88 lines
2.8 KiB
Python
from enum import Enum
|
|
from typing import List
|
|
|
|
|
|
class Feature(Enum):
|
|
"""功能权限枚举,带序号和描述"""
|
|
ROBOT = "🔧 群机器人 [总开关]"
|
|
|
|
def __new__(cls, *args):
|
|
if len(args) == 2:
|
|
value, description = args
|
|
elif len(args) == 1 and isinstance(args[0], tuple):
|
|
value, description = args[0]
|
|
else:
|
|
raise TypeError(f"Invalid arguments for Feature.__new__: {args}")
|
|
|
|
obj = object.__new__(cls)
|
|
obj._value_ = value
|
|
obj.description = description
|
|
return obj
|
|
|
|
def __str__(self):
|
|
return self.description
|
|
|
|
@classmethod
|
|
def get_max_value(cls) -> int:
|
|
return max(member.value for member in cls)
|
|
|
|
_dynamic_features = {}
|
|
|
|
@classmethod
|
|
def register_feature(cls, key: str, description: str) -> 'Feature':
|
|
if key in cls._dynamic_features:
|
|
return cls._dynamic_features[key]
|
|
|
|
new_value = cls.get_max_value() + 1
|
|
new_feature = object.__new__(cls)
|
|
new_feature._value_ = new_value
|
|
new_feature.description = description
|
|
cls._dynamic_features[key] = new_feature
|
|
return new_feature
|
|
|
|
@classmethod
|
|
def get_feature(cls, key: str) -> 'Feature':
|
|
return cls._dynamic_features.get(key)
|
|
|
|
@classmethod
|
|
def get_all_features(cls) -> List['Feature']:
|
|
return list(cls) + list(cls._dynamic_features.values())
|
|
|
|
@classmethod
|
|
def _missing_(cls, value):
|
|
if isinstance(value, int):
|
|
for member in cls:
|
|
if member.value == value:
|
|
return member
|
|
for feature in cls._dynamic_features.values():
|
|
if feature.value == value:
|
|
return feature
|
|
return None
|
|
|
|
|
|
|
|
if __name__ == '__main__':
|
|
# 测试新增功能
|
|
print("当前功能列表:")
|
|
for feature in Feature.get_all_features():
|
|
print(f"{feature.value} - {feature.description}")
|
|
|
|
# 测试注册新功能
|
|
print("\n注册新功能...")
|
|
new_feature = Feature.register_feature("TEST_FEATURE", "🧪 测试功能 [测试]")
|
|
print(f"新功能: {new_feature.value} - {new_feature.description}")
|
|
|
|
# 验证新功能是否添加成功
|
|
print("\n更新后的功能列表:")
|
|
for feature in Feature.get_all_features():
|
|
print(f"{feature.value} - {feature.description}")
|
|
|
|
# 测试重复注册
|
|
print("\n测试重复注册...")
|
|
same_feature = Feature.register_feature("TEST_FEATURE", "🧪 测试功能 [测试]")
|
|
print(f"重复注册结果: {same_feature.value} - {same_feature.description}")
|
|
|
|
# 测试获取功能
|
|
print("\n测试获取功能...")
|
|
retrieved_feature = Feature.get_feature("TEST_FEATURE")
|
|
print(f"获取到的功能: {retrieved_feature.value} - {retrieved_feature.description}") |