or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

adapters-drivers.mdbot-management.mdconfiguration.mddependencies-parameters.mdevent-handlers.mdframework-control.mdindex.mdmessage-matching.mdplugin-system.md
tile.json

tessl/pypi-nonebot2

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

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
pypipkg:pypi/nonebot2@2.4.x

To install, run

npx @tessl/cli install tessl/pypi-nonebot2@2.4.0

index.mddocs/

NoneBot2

An asynchronous Python bot framework for building cross-platform chatbots and automated messaging systems. NoneBot2 provides a plugin-based architecture with support for multiple adapters (QQ, Telegram, Discord, etc.), event-driven message handling, dependency injection, and flexible routing through matchers and rules.

Package Information

  • Package Name: nonebot2
  • Language: Python
  • Installation: pip install nonebot2

Core Imports

import nonebot

Common pattern for framework setup:

import nonebot
from nonebot import on_command, on_message, get_driver
from nonebot.adapters import Bot, Event

Basic Usage

import nonebot
from nonebot import on_command
from nonebot.adapters import Bot, Event
from nonebot.params import CommandArg
from nonebot.typing import T_State

# Initialize NoneBot
nonebot.init()

# Create a simple command handler
hello = on_command("hello")

@hello.handle()
async def handle_hello(bot: Bot, event: Event, state: T_State, args=CommandArg()):
    message = args.extract_plain_text().strip()
    if message:
        await bot.send(event, f"Hello, {message}!")
    else:
        await bot.send(event, "Hello, world!")

# Run the bot
if __name__ == "__main__":
    nonebot.run()

Architecture

NoneBot2 uses an event-driven architecture with several key components:

  • Driver: Core runtime that handles connections and lifecycle management
  • Adapters: Protocol implementations for different platforms (QQ, Telegram, etc.)
  • Bots: Platform-specific instances that send/receive messages
  • Events: Structured data representing user interactions and platform events
  • Matchers: Event handlers that process specific types of events based on rules
  • Plugins: Modular components containing related matchers and functionality
  • Dependencies: Injection system for accessing framework components and parameters

This design enables maximum reusability across messaging platforms while maintaining type safety and extensibility through a comprehensive plugin ecosystem.

Capabilities

Framework Control

Core functions for initializing, configuring, and running the NoneBot2 framework, including global state management.

def init(*, _env_file: Optional[DOTENV_TYPE] = None, **kwargs: Any) -> None: ...
def run(*args: Any, **kwargs: Any) -> None: ...
def get_driver() -> Driver: ...

Framework Control

Bot Management

Functions for accessing and managing bot instances connected to the framework.

def get_bot(self_id: Optional[str] = None) -> Bot: ...
def get_bots() -> dict[str, Bot]: ...
def get_adapter(name: Union[str, type[Adapter]]) -> Adapter: ...
def get_adapters() -> dict[str, Adapter]: ...

Bot Management

Event Handlers

Create event responders that react to different types of platform events and messages.

def on(type: str = "", rule: Optional[Rule] = None, **kwargs) -> type[Matcher]: ...
def on_message(**kwargs) -> type[Matcher]: ...
def on_notice(**kwargs) -> type[Matcher]: ...
def on_request(**kwargs) -> type[Matcher]: ...
def on_metaevent(**kwargs) -> type[Matcher]: ...
def on_type(types: Union[type[Event], tuple[type[Event], ...]], **kwargs) -> type[Matcher]: ...

Event Handlers

Message Matching

Specialized handlers for matching and responding to specific message patterns and commands.

def on_command(cmd: Union[str, tuple[str, ...]], **kwargs) -> type[Matcher]: ...
def on_shell_command(
    cmd: Union[str, tuple[str, ...]],
    rule: Optional[Union[Rule, T_RuleChecker]] = None,
    aliases: Optional[set[Union[str, tuple[str, ...]]]] = None,
    parser: Optional[ArgumentParser] = None,
    **kwargs
) -> type[Matcher]: ...
def on_startswith(msg: Union[str, tuple[str, ...]], **kwargs) -> type[Matcher]: ...
def on_endswith(msg: Union[str, tuple[str, ...]], **kwargs) -> type[Matcher]: ...
def on_fullmatch(msg: Union[str, tuple[str, ...]], **kwargs) -> type[Matcher]: ...
def on_keyword(*keywords: str, **kwargs) -> type[Matcher]: ...
def on_regex(pattern: Union[str, re.Pattern[str]], **kwargs) -> type[Matcher]: ...

Message Matching

Plugin System

Functions for loading, managing, and configuring plugins that extend framework functionality.

def load_plugin(module_path: Union[str, Path]) -> Optional[Plugin]: ...
def load_plugins(*plugin_dir: str) -> set[Plugin]: ...
def load_all_plugins(module_path: Iterable[str], plugin_dir: Iterable[str]) -> set[Plugin]: ...
def load_from_json(file_path: str, encoding: str = "utf-8") -> set[Plugin]: ...
def load_from_toml(file_path: str, encoding: str = "utf-8") -> set[Plugin]: ...
def load_builtin_plugin(name: str) -> Optional[Plugin]: ...
def load_builtin_plugins(*plugins: str) -> set[Plugin]: ...
def get_plugin(plugin_id: str) -> Optional[Plugin]: ...
def get_plugin_by_module_name(module_name: str) -> Optional[Plugin]: ...
def get_loaded_plugins() -> set[Plugin]: ...
def get_available_plugin_names() -> set[str]: ...
def get_plugin_config(config: type[C]) -> C: ...
def require(name: str) -> ModuleType: ...

class CommandGroup:
    def __init__(self, cmd: Union[str, tuple[str, ...]], prefix_aliases: bool = False, **kwargs): ...
    def command(self, cmd: Union[str, tuple[str, ...]], **kwargs) -> type[Matcher]: ...
    def shell_command(self, cmd: Union[str, tuple[str, ...]], **kwargs) -> type[Matcher]: ...

class MatcherGroup:
    def __init__(self, **kwargs): ...
    def on(self, **kwargs) -> type[Matcher]: ...
    def on_message(self, **kwargs) -> type[Matcher]: ...
    def on_command(self, cmd: Union[str, tuple[str, ...]], **kwargs) -> type[Matcher]: ...
    # ... other event handler methods

Plugin System

Configuration

Configuration classes and utilities for setting up the framework environment and behavior.

class Config(BaseSettings):
    driver: str = "~fastapi"
    host: IPvAnyAddress = IPv4Address("127.0.0.1")
    port: int = Field(default=8080, ge=1, le=65535)
    log_level: Union[int, str] = "INFO"
    api_timeout: Optional[float] = 30.0
    superusers: set[str] = set()
    nickname: set[str] = set()
    command_start: set[str] = {"/"}
    command_sep: set[str] = {"."}
    session_expire_timeout: timedelta = timedelta(minutes=2)

class Env(BaseSettings):
    environment: str = "prod"

Configuration

Dependencies & Parameters

Dependency injection system for accessing framework components, event data, and parsed parameters in handlers.

def Depends(dependency: _DEPENDENCY_TYPE) -> Any: ...
def EventType() -> str: ...
def EventMessage() -> Any: ...
def EventPlainText() -> str: ...
def EventToMe() -> bool: ...
def Command() -> tuple[str, ...]: ...
def CommandArg() -> Any: ...
def CommandStart() -> str: ...
def RawCommand() -> str: ...
def ShellCommandArgs() -> Any: ...
def ShellCommandArgv() -> Any: ...
def RegexMatched() -> Match[str]: ...

class Arg(Param): ...
class ArgPlainText(Param): ...
class ArgStr(Param): ...

Dependencies & Parameters

Adapters & Drivers

Base classes and interfaces for implementing protocol adapters and runtime drivers.

class Adapter(abc.ABC):
    def get_name(self) -> str: ...
    def bot_connect(self, bot: Bot) -> None: ...
    # ... additional methods

class Driver(abc.ABC):
    def run(self, *args, **kwargs) -> None: ...
    # ... additional methods

Adapters & Drivers

Exception Handling

NoneBot2 provides a comprehensive exception hierarchy for handling different types of errors and control flow:

class NoneBotException(Exception): ...

# Rule Exception
class ParserExit(NoneBotException): ...

# Processor Exceptions  
class ProcessException(NoneBotException): ...
class IgnoredException(ProcessException): ...
class SkippedException(ProcessException): ...
class TypeMisMatch(SkippedException): ...
class MockApiException(ProcessException): ...
class StopPropagation(ProcessException): ...

# Matcher Exceptions
class MatcherException(NoneBotException): ...
class PausedException(MatcherException): ...
class RejectedException(MatcherException): ...
class FinishedException(MatcherException): ...

# Adapter Exceptions
class AdapterException(NoneBotException): ...
class NoLogException(AdapterException): ...
class ApiNotAvailable(AdapterException): ...
class NetworkError(AdapterException): ...
class ActionFailed(AdapterException): ...

# Driver Exceptions
class DriverException(NoneBotException): ...
class WebSocketClosed(DriverException): ...

Exception hierarchy organized by purpose:

  • Control Flow: FinishedException, PausedException, RejectedException - Control handler execution
  • Processing: IgnoredException, SkippedException, StopPropagation - Control event processing
  • API/Network: ApiNotAvailable, ActionFailed, NetworkError - Handle API and network issues
  • Parsing: ParserExit, TypeMisMatch - Handle parsing and type errors
  • Connection: WebSocketClosed - Handle connection issues

Types

Core Types

T_State = dict[Any, Any]
T_Handler = _DependentCallable[Any]
T_RuleChecker = _DependentCallable[bool] 
T_PermissionChecker = _DependentCallable[bool]
C = TypeVar("C")  # Configuration type variable

Rule and Parser Types

from collections.abc import Iterable
from datetime import timedelta
from ipaddress import IPv4Address
from typing import TypeVar
from pydantic import Field, BaseSettings
from pydantic.networks import IPvAnyAddress
from nonebot.rule import Rule, ArgumentParser

Configuration Types

DOTENV_TYPE = Union[Path, str, list[Union[Path, str]], tuple[Union[Path, str], ...]]

Hook Types

T_BotConnectionHook = _DependentCallable[Any]
T_BotDisconnectionHook = _DependentCallable[Any]
T_CallingAPIHook = _DependentCallable[Any]
T_CalledAPIHook = _DependentCallable[Any]