From 40ca58f1baf7f555cff1995a0ce159f85ad9368c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=B0=8F=E5=BF=B5?= <2660422452@qq.com> Date: Fri, 16 Aug 2024 18:27:39 +0800 Subject: [PATCH] Update command_util.py MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit feature:优化Commands指令装饰器 --- botpy/ext/command_util.py | 19 ++++++++++--------- 1 file changed, 10 insertions(+), 9 deletions(-) diff --git a/botpy/ext/command_util.py b/botpy/ext/command_util.py index 8f26b2b..a96740a 100644 --- a/botpy/ext/command_util.py +++ b/botpy/ext/command_util.py @@ -1,7 +1,7 @@ # -*- coding: utf-8 -*- +import re from functools import wraps -from botpy.message import BaseMessage - +from typing import Tuple class Commands: """ @@ -13,18 +13,19 @@ class Commands: def __init__(self, *args): self.commands = args + # 构建正则表达式模式 + self.pattern = re.compile(rf"({'|'.join(self.commands)})(?:\s+(.*))?") def __call__(self, func): @wraps(func) async def decorated(*args, **kwargs): message: BaseMessage = kwargs["message"] - for command in self.commands: - if command in message.content: - # 分割指令后面的指令参数 - params = message.content.split(command)[1].strip() - kwargs["params"] = params - return await func(*args, **kwargs) + match = self.pattern.match(message.content) + if match: + command, params = match.groups() + if params: + kwargs["params"] = params.strip() + return await func(*args, **kwargs) return False return decorated -