An asynchronous Python bot framework for building cross-platform chatbots with plugin architecture and adapter support.
—
Functions for loading, managing, and configuring plugins that extend NoneBot2 framework functionality. The plugin system enables modular bot development and code reusability.
Load plugins from various sources including files, directories, and package names.
def load_plugin(module_path: Union[str, Path]) -> Optional[Plugin]:
"""
Load a single plugin by module path.
Parameters:
- module_path: Module path or file path to plugin
Returns:
Optional[Plugin]: Loaded Plugin object, None if failed
Raises:
RuntimeError: If plugin loading fails
"""def load_plugins(*plugin_dir: str) -> set[Plugin]:
"""
Load all plugins from specified directories.
Parameters:
- *plugin_dir: Directory paths containing plugins
Returns:
set[Plugin]: Set of loaded Plugin objects
"""def load_all_plugins(
module_path: Iterable[str],
plugin_dir: Iterable[str]
) -> set[Plugin]:
"""
Load plugins from both module paths and directories.
Parameters:
- module_path: Iterable of module paths
- plugin_dir: Iterable of directory paths
Returns:
set[Plugin]: Set of loaded Plugin objects
"""Usage example:
import nonebot
from pathlib import Path
# Load single plugin
plugin = nonebot.load_plugin("my_bot.plugins.echo")
# Load all plugins from directory
plugins = nonebot.load_plugins("./plugins")
# Load from multiple sources
all_plugins = nonebot.load_all_plugins(
["my_bot.plugins.echo", "my_bot.plugins.weather"],
["./plugins", "./custom_plugins"]
)
print(f"Loaded {len(all_plugins)} plugins")Load plugins from JSON and TOML configuration files.
def load_from_json(file_path: str, encoding: str = "utf-8") -> set[Plugin]:
"""
Load plugins from JSON configuration file.
Parameters:
- file_path: Path to JSON configuration file
- encoding: File encoding, defaults to utf-8
Returns:
set[Plugin]: Set of loaded Plugin objects
"""def load_from_toml(file_path: str, encoding: str = "utf-8") -> set[Plugin]:
"""
Load plugins from TOML configuration file.
Parameters:
- file_path: Path to TOML configuration file
- encoding: File encoding, defaults to utf-8
Returns:
set[Plugin]: Set of loaded Plugin objects
"""Usage example:
import nonebot
# Load plugins from JSON config
plugins = nonebot.load_from_json("plugins.json")
# Load plugins from TOML config
plugins = nonebot.load_from_toml("pyproject.toml")Example JSON configuration:
{
"plugins": ["echo", "weather"],
"plugin_dirs": ["./plugins", "./custom_plugins"]
}Example TOML configuration:
[nonebot.plugins]
plugins = ["echo", "weather"]
plugin_dirs = ["./plugins", "./custom_plugins"]Load built-in plugins provided by NoneBot2.
def load_builtin_plugin(name: str) -> Optional[Plugin]:
"""
Load a built-in plugin by name.
Parameters:
- name: Built-in plugin name
Returns:
Optional[Plugin]: Loaded Plugin object, None if not found
"""def load_builtin_plugins(*plugins: str) -> set[Plugin]:
"""
Load multiple built-in plugins.
Parameters:
- *plugins: Built-in plugin names
Returns:
set[Plugin]: Set of loaded Plugin objects
"""Usage example:
import nonebot
# Load single built-in plugin
echo_plugin = nonebot.load_builtin_plugin("echo")
# Load multiple built-in plugins
builtin_plugins = nonebot.load_builtin_plugins("echo", "single_session")Require and access plugin dependencies.
def require(name: str) -> ModuleType:
"""
Require a plugin dependency.
Parameters:
- name: Plugin or module name to require
Returns:
ModuleType: Required module
Raises:
RuntimeError: If required plugin not found or failed to load
"""Usage example:
import nonebot
# Require a plugin dependency
config_plugin = nonebot.require("nonebot_plugin_config")
# Use required plugin
config = config_plugin.get_config()Get information about loaded and available plugins.
def get_plugin(plugin_id: str) -> Optional[Plugin]:
"""
Get loaded plugin by ID.
Parameters:
- plugin_id: Plugin identifier
Returns:
Optional[Plugin]: Plugin object if found, None otherwise
"""def get_plugin_by_module_name(module_name: str) -> Optional[Plugin]:
"""
Get plugin by module name (supports submodules).
Parameters:
- module_name: Module name to search for
Returns:
Optional[Plugin]: Plugin object if found, None otherwise
"""def get_loaded_plugins() -> set[Plugin]:
"""
Get all currently loaded plugins.
Returns:
set[Plugin]: Set of all loaded Plugin objects
"""def get_available_plugin_names() -> set[str]:
"""
Get available plugin names (including unloaded).
Returns:
set[str]: Set of available plugin names
"""Usage example:
import nonebot
# Get specific plugin
echo_plugin = nonebot.get_plugin("echo")
if echo_plugin:
print(f"Plugin: {echo_plugin.name}")
# Get plugin by module name
plugin = nonebot.get_plugin_by_module_name("my_bot.plugins.echo")
# List all loaded plugins
loaded = nonebot.get_loaded_plugins()
for plugin in loaded:
print(f"Loaded: {plugin.name}")
# List available plugins
available = nonebot.get_available_plugin_names()
print(f"Available plugins: {available}")Access plugin-specific configuration from global config.
def get_plugin_config(config: type[C]) -> C:
"""
Get plugin configuration from global config.
Parameters:
- config: Configuration class type
Returns:
C: Configuration instance
Raises:
ValueError: If configuration not found or invalid
"""Usage example:
import nonebot
from pydantic import BaseModel
# Define plugin configuration
class WeatherConfig(BaseModel):
api_key: str
default_city: str = "Beijing"
# Get plugin configuration
config = nonebot.get_plugin_config(WeatherConfig)
print(f"API Key: {config.api_key}")
print(f"Default City: {config.default_city}")class Plugin:
"""Plugin information model."""
name: str
"""Plugin name."""
module: ModuleType
"""Plugin module object."""
module_name: str
"""Module path name."""
manager: PluginManager
"""Plugin manager instance."""
matcher: set[type[Matcher]]
"""Event matchers in this plugin."""
parent_plugin: Optional[Plugin]
"""Parent plugin if this is a sub-plugin."""
sub_plugins: set[Plugin]
"""Sub-plugins of this plugin."""
class PluginMetadata:
"""Plugin metadata for providing plugin information."""
name: str
"""Plugin display name."""
description: str
"""Plugin description."""
usage: str
"""Plugin usage instructions."""
type: str
"""Plugin type."""
homepage: str
"""Plugin homepage URL."""
config: Optional[type[BaseModel]]
"""Plugin configuration class."""
class CommandGroup:
"""Command group for creating commands with shared prefixes."""
def __init__(
self,
cmd: Union[str, tuple[str, ...]],
prefix_aliases: bool = False,
**kwargs
): ...
def command(self, cmd: Union[str, tuple[str, ...]], **kwargs) -> type[Matcher]:
"""Register a new command in this group."""
def shell_command(self, cmd: Union[str, tuple[str, ...]], **kwargs) -> type[Matcher]:
"""Register a new shell command in this group."""
class MatcherGroup:
"""Matcher group for creating event handlers with shared configuration."""
def __init__(self, **kwargs): ...
def on(self, **kwargs) -> type[Matcher]:
"""Register a basic event handler."""
def on_metaevent(self, **kwargs) -> type[Matcher]:
"""Register a meta event handler."""
def on_message(self, **kwargs) -> type[Matcher]:
"""Register a message event handler."""
def on_notice(self, **kwargs) -> type[Matcher]:
"""Register a notice event handler."""
def on_request(self, **kwargs) -> type[Matcher]:
"""Register a request event handler."""
def on_startswith(self, msg: Union[str, tuple[str, ...]], **kwargs) -> type[Matcher]:
"""Register a startswith message handler."""
def on_endswith(self, msg: Union[str, tuple[str, ...]], **kwargs) -> type[Matcher]:
"""Register an endswith message handler."""
def on_fullmatch(self, msg: Union[str, tuple[str, ...]], **kwargs) -> type[Matcher]:
"""Register a fullmatch message handler."""
def on_keyword(self, *keywords: str, **kwargs) -> type[Matcher]:
"""Register a keyword message handler."""
def on_command(self, cmd: Union[str, tuple[str, ...]], **kwargs) -> type[Matcher]:
"""Register a command handler."""
def on_shell_command(self, cmd: Union[str, tuple[str, ...]], **kwargs) -> type[Matcher]:
"""Register a shell command handler."""
def on_regex(self, pattern: Union[str, re.Pattern[str]], **kwargs) -> type[Matcher]:
"""Register a regex message handler."""
def on_type(self, types: Union[type[Event], tuple[type[Event], ...]], **kwargs) -> type[Matcher]:
"""Register a type-based event handler."""
supported_adapters: Optional[set[str]]
"""Supported adapter names."""
class PluginManager:
"""Plugin loading and management."""
def load_plugin(self, name: str) -> Optional[Plugin]:
"""Load plugin by name."""
def list_plugins(self) -> dict[str, Plugin]:
"""List all managed plugins."""class CommandGroup:
"""Group related commands together."""
def __init__(self, cmd: Union[str, tuple[str, ...]], **kwargs):
"""Initialize command group."""
def command(self, cmd: Union[str, tuple[str, ...]], **kwargs) -> type[Matcher]:
"""Create command in this group."""
class MatcherGroup:
"""Group related matchers together."""
def __init__(self, **kwargs):
"""Initialize matcher group."""
def on(self, **kwargs) -> type[Matcher]:
"""Create matcher in this group."""
def on_message(self, **kwargs) -> type[Matcher]:
"""Create message matcher in this group."""
def on_command(self, cmd: Union[str, tuple[str, ...]], **kwargs) -> type[Matcher]:
"""Create command matcher in this group."""Usage example:
import nonebot
from nonebot import CommandGroup, MatcherGroup
# Create command group
weather_group = CommandGroup("weather", permission=SUPERUSER)
# Add commands to group
current = weather_group.command("current")
forecast = weather_group.command("forecast")
@current.handle()
async def handle_current_weather(bot: Bot, event: Event):
await bot.send(event, "Current weather info")
@forecast.handle()
async def handle_weather_forecast(bot: Bot, event: Event):
await bot.send(event, "Weather forecast")
# Create matcher group
admin_group = MatcherGroup(permission=SUPERUSER, priority=1)
# Add matchers to group
admin_message = admin_group.on_message()
admin_command = admin_group.on_command("admin")Install with Tessl CLI
npx tessl i tessl/pypi-nonebot2