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

View File

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