refactor: 更改使用装饰器注册命令

This commit is contained in:
Rock Chin
2023-03-28 12:53:46 +00:00
parent e03585ad4d
commit 0b0271a1f4
2 changed files with 70 additions and 46 deletions

View File

@@ -164,7 +164,14 @@ class AbstractCommandNode:
)
@staticmethod
def register(cls: type, name: str, parent: type = None):
def register(
parent: type = None,
name: str = None,
description: str = None,
usage: str = None,
aliases: list[str] = None,
privilege: int = 0
):
"""注册指令
:param cls: 指令类
@@ -173,6 +180,16 @@ class AbstractCommandNode:
"""
global __command_list__, __tree_index__
def wrapper(cls):
cls.name = name
cls.parent = parent
cls.description = description
cls.usage = usage
cls.aliases = aliases
cls.privilege = privilege
logging.debug("cls: {}, name: {}, parent: {}".format(cls, name, parent))
if parent is None:
# 顶级指令注册
__command_list__[name] = {
@@ -206,6 +223,10 @@ class AbstractCommandNode:
# 更新索引
__tree_index__[cls.__module__ + '.' + cls.__name__] = path + '.' + name
return cls
return wrapper
class CommandPrivilegeError(Exception):
"""指令权限不足或不存在异常"""
@@ -235,6 +256,7 @@ def execute(context: Context) -> list:
while True:
try:
logging.debug('执行指令: {}'.format(path))
node = node[path]
# 检查权限
@@ -251,6 +273,7 @@ def execute(context: Context) -> list:
# 下一个path
path = path + '.' + ctx.crt_command
except KeyError:
traceback.print_exc()
raise CommandPrivilegeError('找不到指令: {}'.format(path))
@@ -281,10 +304,10 @@ def register_all():
walk(__import__(module.__name__ + '.' + item.name, fromlist=['']), prefix + item.name + '.', path_prefix + item.name + '/')
else:
m = __import__(module.__name__ + '.' + item.name, fromlist=[''])
for name, cls in inspect.getmembers(m, inspect.isclass):
# 检查是否为指令类
if cls.__module__ == m.__name__ and issubclass(cls, AbstractCommandNode) and cls != AbstractCommandNode:
cls.register(cls, cls.name, cls.parent)
# for name, cls in inspect.getmembers(m, inspect.isclass):
# # 检查是否为指令类
# if cls.__module__ == m.__name__ and issubclass(cls, AbstractCommandNode) and cls != AbstractCommandNode:
# cls.register(cls, cls.name, cls.parent)
walk(pkg.qqbot.cmds, '', '')
logging.debug(__command_list__)

View File

@@ -3,17 +3,18 @@ from ..mgr import AbstractCommandNode, Context
import pkg.openai.session
import pkg.utils.context
class ResetCommand(AbstractCommandNode):
parent: type = None
name = 'reset'
description = '重置当前会话'
usage = '!reset'
aliases = []
@AbstractCommandNode.register(
parent=None,
name='reset',
description='重置当前会话',
usage='!reset',
aliases=[],
privilege=1
)
class ResetCommand(AbstractCommandNode):
@classmethod
def process(cls, ctx: Context) -> tuple[bool, list, str]:
def process(cls, ctx: Context) -> tuple[bool, list]:
params = ctx.params
session_name = ctx.session_name