An asynchronous Python bot framework for building cross-platform chatbots with plugin architecture and adapter support.
npx @tessl/cli install tessl/pypi-nonebot2@2.4.0An 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.
pip install nonebot2import nonebotCommon pattern for framework setup:
import nonebot
from nonebot import on_command, on_message, get_driver
from nonebot.adapters import Bot, Eventimport 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()NoneBot2 uses an event-driven architecture with several key components:
This design enables maximum reusability across messaging platforms while maintaining type safety and extensibility through a comprehensive plugin ecosystem.
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: ...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]: ...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]: ...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]: ...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 methodsConfiguration 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"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): ...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 methodsNoneBot2 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:
FinishedException, PausedException, RejectedException - Control handler executionIgnoredException, SkippedException, StopPropagation - Control event processingApiNotAvailable, ActionFailed, NetworkError - Handle API and network issuesParserExit, TypeMisMatch - Handle parsing and type errorsWebSocketClosed - Handle connection issuesT_State = dict[Any, Any]
T_Handler = _DependentCallable[Any]
T_RuleChecker = _DependentCallable[bool]
T_PermissionChecker = _DependentCallable[bool]
C = TypeVar("C") # Configuration type variablefrom 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, ArgumentParserDOTENV_TYPE = Union[Path, str, list[Union[Path, str]], tuple[Union[Path, str], ...]]T_BotConnectionHook = _DependentCallable[Any]
T_BotDisconnectionHook = _DependentCallable[Any]
T_CallingAPIHook = _DependentCallable[Any]
T_CalledAPIHook = _DependentCallable[Any]