mirror of
https://github.com/nonebot/nonebot2.git
synced 2025-07-29 09:10:22 +00:00
move decorators to plugin module
This commit is contained in:
@ -15,20 +15,17 @@ from nonebot.helpers import context_id, send, render_expression
|
||||
from nonebot.log import logger
|
||||
from nonebot.message import Message
|
||||
from nonebot.session import BaseSession
|
||||
from nonebot.typing import (CommandName_T, CommandArgs_T, Message_T, State_T,
|
||||
Filter_T)
|
||||
from nonebot.typing import (CommandName_T, CommandArgs_T, CommandHandler_T,
|
||||
Message_T, State_T, Filter_T)
|
||||
|
||||
# key: context id
|
||||
# value: CommandSession object
|
||||
_sessions = {} # type: Dict[str, "CommandSession"]
|
||||
|
||||
CommandHandler_T = Callable[['CommandSession'], Any]
|
||||
|
||||
|
||||
class Command:
|
||||
__slots__ = ('name', 'func', 'permission', 'only_to_me', 'privileged',
|
||||
'args_parser_func', '__name__', '__qualname__', '__doc__',
|
||||
'__annotations__', '__dict__')
|
||||
'args_parser_func')
|
||||
|
||||
def __init__(self, *, name: CommandName_T, func: CommandHandler_T,
|
||||
permission: int, only_to_me: bool, privileged: bool):
|
||||
@ -361,55 +358,6 @@ class CommandManager:
|
||||
cmd_name] if state is None else bool(state)
|
||||
|
||||
|
||||
def on_command(name: Union[str, CommandName_T],
|
||||
*,
|
||||
aliases: Union[Iterable[str], str] = (),
|
||||
permission: int = perm.EVERYBODY,
|
||||
only_to_me: bool = True,
|
||||
privileged: bool = False,
|
||||
shell_like: bool = False) -> Callable:
|
||||
"""
|
||||
Decorator to register a function as a command.
|
||||
|
||||
:param name: command name (e.g. 'echo' or ('random', 'number'))
|
||||
:param aliases: aliases of command name, for convenient access
|
||||
:param permission: permission required by the command
|
||||
:param only_to_me: only handle messages to me
|
||||
:param privileged: can be run even when there is already a session
|
||||
:param shell_like: use shell-like syntax to split arguments
|
||||
"""
|
||||
|
||||
def deco(func: CommandHandler_T) -> Command:
|
||||
if not isinstance(name, (str, tuple)):
|
||||
raise TypeError('the name of a command must be a str or tuple')
|
||||
if not name:
|
||||
raise ValueError('the name of a command must not be empty')
|
||||
|
||||
cmd_name = (name,) if isinstance(name, str) else name
|
||||
|
||||
cmd = Command(name=cmd_name,
|
||||
func=func,
|
||||
permission=permission,
|
||||
only_to_me=only_to_me,
|
||||
privileged=privileged)
|
||||
|
||||
if shell_like:
|
||||
|
||||
async def shell_like_args_parser(session):
|
||||
session.args['argv'] = shlex.split(session.current_arg)
|
||||
|
||||
cmd.args_parser_func = shell_like_args_parser
|
||||
|
||||
CommandManager.add_command(cmd_name, cmd)
|
||||
CommandManager.add_aliases(aliases, cmd)
|
||||
|
||||
update_wrapper(wrapper=cmd, wrapped=func) # type: ignore
|
||||
|
||||
return cmd
|
||||
|
||||
return deco
|
||||
|
||||
|
||||
class _PauseException(Exception):
|
||||
"""
|
||||
Raised by session.pause() indicating that the command session
|
||||
|
@ -4,5 +4,6 @@ from nonebot.typing import Message_T
|
||||
|
||||
|
||||
class ValidateError(ValueError):
|
||||
|
||||
def __init__(self, message: Optional[Message_T] = None):
|
||||
self.message = message
|
||||
|
@ -11,8 +11,8 @@ def handle_cancellation(session: CommandSession):
|
||||
|
||||
def control(value):
|
||||
if _is_cancellation(value) is True:
|
||||
session.finish(render_expression(
|
||||
session.bot.config.SESSION_CANCEL_EXPRESSION))
|
||||
session.finish(
|
||||
render_expression(session.bot.config.SESSION_CANCEL_EXPRESSION))
|
||||
return value
|
||||
|
||||
return control
|
||||
|
@ -15,13 +15,15 @@ def _simple_chinese_to_bool(text: str) -> Optional[bool]:
|
||||
"""
|
||||
text = text.strip().lower().replace(' ', '') \
|
||||
.rstrip(',.!?~,。!?~了的呢吧呀啊呗啦')
|
||||
if text in {'要', '用', '是', '好', '对', '嗯', '行',
|
||||
'ok', 'okay', 'yeah', 'yep',
|
||||
'当真', '当然', '必须', '可以', '肯定', '没错', '确定', '确认'}:
|
||||
if text in {
|
||||
'要', '用', '是', '好', '对', '嗯', '行', 'ok', 'okay', 'yeah', 'yep',
|
||||
'当真', '当然', '必须', '可以', '肯定', '没错', '确定', '确认'
|
||||
}:
|
||||
return True
|
||||
if text in {'不', '不要', '不用', '不是', '否', '不好', '不对', '不行', '别',
|
||||
'no', 'nono', 'nonono', 'nope', '不ok', '不可以', '不能',
|
||||
'不可以'}:
|
||||
if text in {
|
||||
'不', '不要', '不用', '不是', '否', '不好', '不对', '不行', '别', 'no', 'nono',
|
||||
'nonono', 'nope', '不ok', '不可以', '不能', '不可以'
|
||||
}:
|
||||
return False
|
||||
return None
|
||||
|
||||
@ -31,8 +33,8 @@ def _split_nonempty_lines(text: str) -> List[str]:
|
||||
|
||||
|
||||
def _split_nonempty_stripped_lines(text: str) -> List[str]:
|
||||
return list(filter(lambda x: x,
|
||||
map(lambda x: x.strip(), text.splitlines())))
|
||||
return list(filter(lambda x: x, map(lambda x: x.strip(),
|
||||
text.splitlines())))
|
||||
|
||||
|
||||
simple_chinese_to_bool = _simple_chinese_to_bool
|
||||
|
@ -14,8 +14,11 @@ def _extract_text(arg: Message_T) -> str:
|
||||
def _extract_image_urls(arg: Message_T) -> List[str]:
|
||||
"""Extract all image urls from a message-like object."""
|
||||
arg_as_msg = Message(arg)
|
||||
return [s.data['url'] for s in arg_as_msg
|
||||
if s.type == 'image' and 'url' in s.data]
|
||||
return [
|
||||
s.data['url']
|
||||
for s in arg_as_msg
|
||||
if s.type == 'image' and 'url' in s.data
|
||||
]
|
||||
|
||||
|
||||
def _extract_numbers(arg: Message_T) -> List[float]:
|
||||
|
@ -6,6 +6,7 @@ from nonebot.typing import Filter_T
|
||||
|
||||
|
||||
class BaseValidator:
|
||||
|
||||
def __init__(self, message=None):
|
||||
self.message = message
|
||||
|
||||
@ -69,8 +70,7 @@ def match_regex(pattern: str, message=None, *, flags=0,
|
||||
return validate
|
||||
|
||||
|
||||
def ensure_true(bool_func: Callable[[Any], bool],
|
||||
message=None) -> Filter_T:
|
||||
def ensure_true(bool_func: Callable[[Any], bool], message=None) -> Filter_T:
|
||||
"""
|
||||
Validate any object to ensure the result of applying
|
||||
a boolean function to it is True.
|
||||
|
Reference in New Issue
Block a user