CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-nonebot2

An asynchronous Python bot framework for building cross-platform chatbots with plugin architecture and adapter support.

Pending
Overview
Eval results
Files

dependencies-parameters.mddocs/

Dependencies & Parameters

Dependency injection system for accessing framework components, event data, and parsed parameters in handlers. This system provides type-safe access to bot functionality and event information.

Capabilities

Dependency Injection

Core dependency injection functionality for handler parameters.

def Depends(dependency: _DEPENDENCY_TYPE) -> Any:
    """
    Declare a dependency for handler parameter injection.

    Parameters:
    - dependency: Dependency callable or function

    Returns:
    Any: Dependency result
    """

Usage example:

from nonebot import on_command
from nonebot.params import Depends
from nonebot.adapters import Bot, Event

async def get_user_info(event: Event) -> dict:
    """Custom dependency that extracts user information."""
    return {
        "user_id": event.get_user_id(),
        "session_id": event.get_session_id()
    }

# Use dependency in handler
cmd = on_command("profile")

@cmd.handle()
async def handle_profile(
    bot: Bot,
    event: Event,
    user_info: dict = Depends(get_user_info)
):
    await bot.send(event, f"User ID: {user_info['user_id']}")

Event Information Parameters

Access basic event information and metadata.

def EventType() -> str:
    """
    Get the event type.

    Returns:
    str: Event type string
    """
def EventMessage() -> Any:
    """
    Get the event message object.

    Returns:
    Any: Message object from the event
    """
def EventPlainText() -> str:
    """
    Get the plain text content of the event message.

    Returns:
    str: Plain text message content
    """
def EventToMe() -> bool:
    """
    Check if the event is directed to the bot.

    Returns:
    bool: True if event is directed to bot, False otherwise
    """

Usage example:

from nonebot import on_message
from nonebot.params import EventType, EventMessage, EventPlainText, EventToMe
from nonebot.adapters import Bot, Event

handler = on_message()

@handler.handle()
async def handle_message(
    bot: Bot,
    event: Event,
    event_type: str = EventType(),
    message: Any = EventMessage(),
    plain_text: str = EventPlainText(),
    to_me: bool = EventToMe()
):
    await bot.send(event, f"Type: {event_type}")
    await bot.send(event, f"Text: {plain_text}")
    if to_me:
        await bot.send(event, "This message was directed to me!")

Command Parameters

Access command-related information and arguments.

def Command() -> tuple[str, ...]:
    """
    Get the command tuple that triggered this handler.

    Returns:
    tuple[str, ...]: Command parts as tuple
    """
def RawCommand() -> str:
    """
    Get the raw command text.

    Returns:
    str: Raw command text
    """
def CommandArg() -> Any:
    """
    Get the arguments passed to the command.

    Returns:
    Any: Command arguments (usually Message object)
    """
def CommandStart() -> str:
    """
    Get the command prefix that was used.

    Returns:
    str: Command prefix character
    """
def CommandWhitespace() -> str:
    """
    Get the whitespace between command and arguments.

    Returns:
    str: Whitespace string
    """

Usage example:

from nonebot import on_command
from nonebot.params import Command, RawCommand, CommandArg, CommandStart
from nonebot.adapters import Bot, Event

cmd = on_command("weather")

@cmd.handle()
async def handle_weather(
    bot: Bot,
    event: Event,
    command: tuple[str, ...] = Command(),
    raw_cmd: str = RawCommand(),
    args: Any = CommandArg(),
    prefix: str = CommandStart()
):
    city = args.extract_plain_text().strip()
    await bot.send(event, f"Command: {command}")
    await bot.send(event, f"Raw: {raw_cmd}")
    await bot.send(event, f"Prefix: {prefix}")
    await bot.send(event, f"Weather for: {city}")

Shell Command Parameters

Access parsed shell command arguments.

def ShellCommandArgs() -> Any:
    """
    Get parsed shell command arguments as Namespace.

    Returns:
    Any: Parsed arguments (argparse.Namespace)
    """
def ShellCommandArgv() -> Any:
    """
    Get raw shell command argument list.

    Returns:
    Any: Raw argument list
    """

Usage example:

from nonebot import on_shell_command
from nonebot.params import ShellCommandArgs, ShellCommandArgv
from nonebot.rule import ArgumentParser
from nonebot.adapters import Bot, Event

# Create argument parser
parser = ArgumentParser()
parser.add_argument("--name", type=str, required=True)
parser.add_argument("--count", type=int, default=1)
parser.add_argument("--verbose", "-v", action="store_true")

greet = on_shell_command("greet", parser=parser)

@greet.handle()
async def handle_greet(
    bot: Bot,
    event: Event,
    args: Any = ShellCommandArgs(),
    argv: Any = ShellCommandArgv()
):
    name = args.name
    count = args.count
    verbose = args.verbose
    
    if verbose:
        await bot.send(event, f"Raw arguments: {argv}")
    
    for i in range(count):
        await bot.send(event, f"Hello, {name}!")

Regular Expression Parameters

Access regex match results and captured groups.

def RegexMatched() -> Match[str]:
    """
    Get the regex match result.

    Returns:
    Match[str]: Regular expression match object
    """
def RegexStr(*groups: Union[str, int]) -> Union[str, tuple[Union[str, Any], ...], Any]:
    """
    Get specific regex groups by index or name.

    Parameters:
    - *groups: Group indices or names to extract

    Returns:
    Union[str, tuple, Any]: Single group string or tuple of groups
    """
def RegexGroup() -> tuple[Any, ...]:
    """
    Get all regex groups as tuple.

    Returns:
    tuple[Any, ...]: All captured groups
    """
def RegexDict() -> dict[str, Any]:
    """
    Get named regex groups as dictionary.

    Returns:
    dict[str, Any]: Named captured groups
    """

Usage example:

from nonebot import on_regex
from nonebot.params import RegexMatched, RegexStr, RegexGroup, RegexDict
from nonebot.adapters import Bot, Event

# Match pattern with named groups
pattern = r"(?P<command>\w+)\s+(?P<number>\d+)"
handler = on_regex(pattern)

@handler.handle()
async def handle_regex(
    bot: Bot,
    event: Event,
    matched: Match = RegexMatched(),
    command: str = RegexStr("command"),
    number: str = RegexStr("number"),
    groups: tuple = RegexGroup(),
    group_dict: dict = RegexDict()
):
    await bot.send(event, f"Full match: {matched.group()}")
    await bot.send(event, f"Command: {command}")
    await bot.send(event, f"Number: {number}")
    await bot.send(event, f"All groups: {groups}")
    await bot.send(event, f"Named groups: {group_dict}")

Text Matching Parameters

Access matched text from various text matching handlers.

def Startswith() -> str:
    """
    Get the text that matched startswith pattern.

    Returns:
    str: Matched startswith text
    """
def Endswith() -> str:
    """
    Get the text that matched endswith pattern.

    Returns:
    str: Matched endswith text
    """
def Fullmatch() -> str:
    """
    Get the text that matched fullmatch pattern.

    Returns:
    str: Matched fullmatch text
    """
def Keyword() -> str:
    """
    Get the keyword that was matched.

    Returns:
    str: Matched keyword
    """

Usage example:

from nonebot import on_startswith, on_keyword
from nonebot.params import Startswith, Keyword
from nonebot.adapters import Bot, Event

# Startswith handler
starts_handler = on_startswith("prefix")

@starts_handler.handle()
async def handle_starts(
    bot: Bot,
    event: Event,
    matched_text: str = Startswith()
):
    await bot.send(event, f"Matched prefix: {matched_text}")

# Keyword handler
keyword_handler = on_keyword("help", "assist", "support")

@keyword_handler.handle()
async def handle_keyword(
    bot: Bot,
    event: Event,
    keyword: str = Keyword()
):
    await bot.send(event, f"Detected keyword: {keyword}")

Conversation State Parameters

Access conversation state and received events.

def Received(id: Optional[str] = None, default: Any = None) -> Any:
    """
    Get received event by ID.

    Parameters:
    - id: Event ID to retrieve, None for any event
    - default: Default value if event not found

    Returns:
    Any: Received event or default value
    """
def LastReceived(default: Any = None) -> Any:
    """
    Get the last received event.

    Parameters:
    - default: Default value if no event received

    Returns:
    Any: Last received event or default value
    """
def ReceivePromptResult(id: Optional[str] = None) -> Any:
    """
    Get the result of a receive prompt.

    Parameters:
    - id: Prompt ID, None for latest

    Returns:
    Any: Prompt result
    """
def PausePromptResult() -> Any:
    """
    Get the result of a pause prompt.

    Returns:
    Any: Pause prompt result
    """

Usage example:

from nonebot import on_command
from nonebot.params import Received, LastReceived
from nonebot.adapters import Bot, Event

multi_step = on_command("setup")

@multi_step.handle()
async def handle_setup(bot: Bot, event: Event):
    await bot.send(event, "What's your name?")

@multi_step.got("name")
async def got_name(bot: Bot, event: Event):
    name = event.get_plaintext().strip()
    await bot.send(event, f"Hello {name}! What's your age?")

@multi_step.got("age")
async def got_age(
    bot: Bot,
    event: Event,
    name_event: Event = Received("name"),
    last_event: Event = LastReceived()
):
    name = name_event.get_plaintext().strip()
    age = event.get_plaintext().strip()
    await bot.send(event, f"Nice to meet you, {name} ({age} years old)!")

Types

Parameter Classes

class Param(abc.ABC, FieldInfo):
    """Base class for dependency injection parameters."""
    
    def _solve(self, **kwargs) -> Any:
        """Solve parameter value (abstract method)."""
    
    def _check(self, **kwargs) -> None:
        """Pre-check parameter (optional)."""

class Dependent[R](Generic[R]):
    """Dependency injection container."""
    
    call: _DependentCallable[R]
    """Callable object."""
    
    params: tuple[ModelField, ...]
    """Named parameters."""
    
    parameterless: tuple[Param, ...]
    """Parameterless parameters."""
    
    def __call__(self, **kwargs) -> R:
        """Execute dependent."""
    
    def solve(self, **params) -> dict[str, Any]:
        """Solve parameter values."""

Framework Parameter Classes

class BotParam(Param):
    """Bot parameter injection."""

class EventParam(Param):
    """Event parameter injection."""

class StateParam(Param):
    """State parameter injection."""

class MatcherParam(Param):
    """Matcher parameter injection."""

class ExceptionParam(Param):
    """Exception parameter injection."""

class DependParam(Param):
    """Sub-dependency parameter injection."""

class DefaultParam(Param):
    """Default parameter injection."""

Argument Parameters

class Arg(Param):
    """Handler argument parameter."""

class ArgStr(Param):
    """Handler string argument parameter."""

class ArgPlainText(Param):
    """Handler plain text argument parameter."""

class ArgPromptResult(Param):
    """Argument prompt result parameter."""

Install with Tessl CLI

npx tessl i tessl/pypi-nonebot2

docs

adapters-drivers.md

bot-management.md

configuration.md

dependencies-parameters.md

event-handlers.md

framework-control.md

index.md

message-matching.md

plugin-system.md

tile.json