Skip to content

SlashedCommand

Sub classes

Name Children Inherits
HelpCommand
slashed.builtin.help_cmd
Display help information about commands.
    ExitCommand
    slashed.builtin.help_cmd
    Exit the chat session.
      ExecCommand
      slashed.builtin.system
      Execute a system command and capture its output.
        RunCommand
        slashed.builtin.system
        Launch a system command asynchronously.
          ProcessesCommand
          slashed.builtin.system
          List running processes.
            SystemInfoCommand
            slashed.builtin.system
            Show system information.
              KillCommand
              slashed.builtin.system
              Kill a running process.
                EnvCommand
                slashed.builtin.system
                Show or set environment variables.

                  Base classes

                  Name Children Inherits
                  BaseCommand
                  slashed.base
                  Abstract base class for commands.

                  ⋔ Inheritance diagram

                  graph TD
                    807245086["commands.SlashedCommand"]
                    900363605["base.BaseCommand"]
                    925645236["abc.ABC"]
                    2751680898["builtins.object"]
                    900363605 --> 807245086
                    925645236 --> 900363605
                    2751680898 --> 925645236

                  🛈 DocStrings

                  Bases: BaseCommand

                  Base class for declarative commands.

                  Allows defining commands using class syntax with explicit parameters:

                  Example

                  class AddWorkerCommand(SlashedCommand): '''Add a new worker to the pool.'''

                  name = "add-worker"
                  category = "tools"
                  
                  async def execute_command(
                      self,
                      ctx: CommandContext,  # Optional depending on implementation
                      worker_id: str,       # required param (no default)
                      host: str,            # required param (no default)
                      port: int = 8080,     # optional param (has default)
                  ):
                      await ctx.print(f"Adding worker {worker_id} at {host}:{port}")
                  

                  Context-free command

                  class VersionCommand(SlashedCommand): '''Show version information.'''

                  name = "version"
                  
                  async def execute_command(self, major: int, minor: int = 0):
                      return f"v{major}.{minor}"
                  
                  Source code in src/slashed/commands.py
                  class SlashedCommand(BaseCommand):
                      """Base class for declarative commands.
                  
                      Allows defining commands using class syntax with explicit parameters:
                  
                      Example:
                          class AddWorkerCommand(SlashedCommand):
                              '''Add a new worker to the pool.'''
                  
                              name = "add-worker"
                              category = "tools"
                  
                              async def execute_command(
                                  self,
                                  ctx: CommandContext,  # Optional depending on implementation
                                  worker_id: str,       # required param (no default)
                                  host: str,            # required param (no default)
                                  port: int = 8080,     # optional param (has default)
                              ):
                                  await ctx.print(f"Adding worker {worker_id} at {host}:{port}")
                  
                          # Context-free command
                          class VersionCommand(SlashedCommand):
                              '''Show version information.'''
                  
                              name = "version"
                  
                              async def execute_command(self, major: int, minor: int = 0):
                                  return f"v{major}.{minor}"
                      """
                  
                      name: str
                      """Command name"""
                  
                      category: str = "general"
                      """Command category"""
                  
                      description: str = ""
                      """Optional description override"""
                  
                      usage: str | None = None
                      """Optional usage override"""
                  
                      help_text: str = ""
                      """Optional help text override"""
                  
                      def __init__(self) -> None:
                          """Initialize command instance."""
                          self.description = self.description or inspect.getdoc(self.__class__) or "No description"
                          self.help_text = type(self).help_text or self.description
                  
                      def __init_subclass__(cls) -> None:
                          """Process command class at definition time.
                  
                          Validates required attributes and generates description/usage from metadata.
                          """
                          super().__init_subclass__()
                  
                          if not hasattr(cls, "name"):
                              msg = f"Command class {cls.__name__} must define 'name' attribute"
                              raise TypeError(msg)
                  
                          # Get description from docstring if not explicitly set on this class
                          if "description" not in cls.__dict__:
                              # Check if this class has its own docstring (not inherited)
                              own_doc = cls.__dict__.get("__doc__")
                              if own_doc:
                                  cls.description = own_doc
                              # Otherwise inherit parent's description (already set from parent's __init_subclass__)
                              # If no parent description exists, use "No description"
                              elif not hasattr(cls, "description") or not cls.description:
                                  cls.description = "No description"
                  
                          # Generate usage from execute signature if not explicitly set on THIS class
                          if "usage" not in cls.__dict__:
                              usage_params = extract_usage_params(cls.execute_command, skip_first=True)
                              cls.usage = " ".join(usage_params)
                  
                      @abstractmethod
                      async def execute_command(self, *args: Any, **kwargs: Any) -> Any:
                          """Execute the command logic.
                  
                          This method should be implemented with explicit parameters.
                          Parameters without default values are treated as required.
                  
                          Args:
                              args: Command arguments (may include context as first param)
                              kwargs: Command keyword arguments
                          """
                  
                      def get_callable(self) -> Callable[..., Any]:
                          """The ``execute_command`` method, whose signature defines the parameters."""
                          return self.execute_command
                  
                      async def execute(
                          self,
                          ctx: CommandContext[Any],
                          args: list[str],
                          kwargs: dict[str, str],
                      ) -> Any:
                          """Execute command by binding command-line arguments to method parameters."""
                          method = type(self).execute_command
                          call_args, coerced_kwargs = parse_args(method, ctx, args, kwargs, skip_first=True)
                          return await self.execute_command(*call_args, **coerced_kwargs)
                  

                  category class-attribute instance-attribute

                  category: str = 'general'
                  

                  Command category

                  description class-attribute instance-attribute

                  description: str = self.description or inspect.getdoc(self.__class__) or 'No description'
                  

                  Optional description override

                  help_text class-attribute instance-attribute

                  help_text: str = type(self).help_text or self.description
                  

                  Optional help text override

                  name instance-attribute

                  name: str
                  

                  Command name

                  usage class-attribute instance-attribute

                  usage: str | None = None
                  

                  Optional usage override

                  __init__

                  __init__() -> None
                  

                  Initialize command instance.

                  Source code in src/slashed/commands.py
                  def __init__(self) -> None:
                      """Initialize command instance."""
                      self.description = self.description or inspect.getdoc(self.__class__) or "No description"
                      self.help_text = type(self).help_text or self.description
                  

                  __init_subclass__

                  __init_subclass__() -> None
                  

                  Process command class at definition time.

                  Validates required attributes and generates description/usage from metadata.

                  Source code in src/slashed/commands.py
                  def __init_subclass__(cls) -> None:
                      """Process command class at definition time.
                  
                      Validates required attributes and generates description/usage from metadata.
                      """
                      super().__init_subclass__()
                  
                      if not hasattr(cls, "name"):
                          msg = f"Command class {cls.__name__} must define 'name' attribute"
                          raise TypeError(msg)
                  
                      # Get description from docstring if not explicitly set on this class
                      if "description" not in cls.__dict__:
                          # Check if this class has its own docstring (not inherited)
                          own_doc = cls.__dict__.get("__doc__")
                          if own_doc:
                              cls.description = own_doc
                          # Otherwise inherit parent's description (already set from parent's __init_subclass__)
                          # If no parent description exists, use "No description"
                          elif not hasattr(cls, "description") or not cls.description:
                              cls.description = "No description"
                  
                      # Generate usage from execute signature if not explicitly set on THIS class
                      if "usage" not in cls.__dict__:
                          usage_params = extract_usage_params(cls.execute_command, skip_first=True)
                          cls.usage = " ".join(usage_params)
                  

                  execute async

                  execute(ctx: CommandContext[Any], args: list[str], kwargs: dict[str, str]) -> Any
                  

                  Execute command by binding command-line arguments to method parameters.

                  Source code in src/slashed/commands.py
                  async def execute(
                      self,
                      ctx: CommandContext[Any],
                      args: list[str],
                      kwargs: dict[str, str],
                  ) -> Any:
                      """Execute command by binding command-line arguments to method parameters."""
                      method = type(self).execute_command
                      call_args, coerced_kwargs = parse_args(method, ctx, args, kwargs, skip_first=True)
                      return await self.execute_command(*call_args, **coerced_kwargs)
                  

                  execute_command abstractmethod async

                  execute_command(*args: Any, **kwargs: Any) -> Any
                  

                  Execute the command logic.

                  This method should be implemented with explicit parameters. Parameters without default values are treated as required.

                  Parameters:

                  Name Type Description Default
                  args Any

                  Command arguments (may include context as first param)

                  ()
                  kwargs Any

                  Command keyword arguments

                  {}
                  Source code in src/slashed/commands.py
                  @abstractmethod
                  async def execute_command(self, *args: Any, **kwargs: Any) -> Any:
                      """Execute the command logic.
                  
                      This method should be implemented with explicit parameters.
                      Parameters without default values are treated as required.
                  
                      Args:
                          args: Command arguments (may include context as first param)
                          kwargs: Command keyword arguments
                      """
                  

                  get_callable

                  get_callable() -> Callable[..., Any]
                  

                  The execute_command method, whose signature defines the parameters.

                  Source code in src/slashed/commands.py
                  def get_callable(self) -> Callable[..., Any]:
                      """The ``execute_command`` method, whose signature defines the parameters."""
                      return self.execute_command
                  

                  :fa-brands-github: Show source on GitHub