MCPcopy
hub / github.com/nonebot/nonebot2 / ShellCommandRule

Class ShellCommandRule

nonebot/rule.py:522–586  ·  view source on GitHub ↗

检查消息是否为指定 shell 命令。 参数: cmds: 指定命令元组列表 parser: 可选参数解析器

Source from the content-addressed store, hash-verified

520
521
522class ShellCommandRule:
523 """检查消息是否为指定 shell 命令。
524
525 参数:
526 cmds: 指定命令元组列表
527 parser: 可选参数解析器
528 """
529
530 __slots__ = ("cmds", "parser")
531
532 def __init__(self, cmds: list[tuple[str, ...]], parser: ArgumentParser | None):
533 self.cmds = tuple(cmds)
534 self.parser = parser
535
536 def __repr__(self) -> str:
537 return f"ShellCommand(cmds={self.cmds}, parser={self.parser})"
538
539 def __eq__(self, other: object) -> bool:
540 return (
541 isinstance(other, ShellCommandRule)
542 and frozenset(self.cmds) == frozenset(other.cmds)
543 and self.parser is other.parser
544 )
545
546 def __hash__(self) -> int:
547 return hash((frozenset(self.cmds), self.parser))
548
549 async def __call__(
550 self,
551 state: T_State,
552 cmd: tuple[str, ...] | None = Command(),
553 msg: Message | None = CommandArg(),
554 ) -> bool:
555 if cmd not in self.cmds or msg is None:
556 return False
557
558 try:
559 state[SHELL_ARGV] = list(
560 chain.from_iterable(
561 shlex.split(str(seg))
562 if cast(MessageSegment, seg).is_text()
563 else (seg,)
564 for seg in msg
565 )
566 )
567 except Exception as e:
568 # set SHELL_ARGV to none indicating shlex error
569 state[SHELL_ARGV] = None
570 # ensure SHELL_ARGS is set to ParserExit if parser is provided
571 if self.parser:
572 state[SHELL_ARGS] = ParserExit(status=2, message=str(e))
573 return True
574
575 if self.parser:
576 t = parser_message.set("")
577 try:
578 args = self.parser.parse_args(state[SHELL_ARGV])
579 state[SHELL_ARGS] = args

Callers 1

shell_commandFunction · 0.85

Calls

no outgoing calls

Tested by

no test coverage detected