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

configuration.mddocs/

Configuration

Configuration classes and utilities for setting up the NoneBot2 framework environment and behavior. The configuration system supports environment variables, config files, and programmatic configuration.

Capabilities

Environment Configuration

Manage runtime environment settings.

class Env(BaseSettings):
    """Runtime environment configuration."""
    
    environment: str = "prod"
    """Current environment name (prod, dev, test, etc.)."""
    
    def __init__(self, **kwargs):
        """Initialize environment configuration."""

Usage example:

from nonebot.config import Env

# Get current environment
env = Env()
print(f"Current environment: {env.environment}")

# Set environment via environment variable
# export ENVIRONMENT=development
env = Env()
print(f"Environment: {env.environment}")  # "development"

Main Configuration

Core NoneBot2 framework configuration with all runtime settings.

class Config(BaseSettings):
    """Main NoneBot configuration with all framework settings."""
    
    # Driver Configuration
    driver: str = "~fastapi"
    """Driver specification string."""
    
    # Server Configuration  
    host: IPvAnyAddress = IPv4Address("127.0.0.1")
    """Server host address."""
    
    port: int = 8080
    """Server port number (1-65535)."""
    
    # Logging Configuration
    log_level: Union[int, str] = "INFO"
    """Logging level (DEBUG, INFO, WARNING, ERROR, CRITICAL)."""
    
    # API Configuration
    api_timeout: Optional[float] = 30.0
    """API request timeout in seconds."""
    
    # Bot Configuration
    superusers: set[str] = set()
    """Bot superuser IDs with administrative privileges."""
    
    nickname: set[str] = set()
    """Bot nicknames for @-mentions."""
    
    # Command Configuration
    command_start: set[str] = {"/"}
    """Command prefix characters."""
    
    command_sep: set[str] = {"."}
    """Command separator characters for sub-commands."""
    
    # Session Configuration
    session_expire_timeout: timedelta = timedelta(minutes=2)
    """Session timeout duration."""
    
    def __init__(self, **kwargs):
        """Initialize configuration with custom values."""

Usage example:

from nonebot.config import Config
from datetime import timedelta

# Create configuration with defaults
config = Config()

# Create configuration with custom values
config = Config(
    driver="~fastapi+~httpx+~websockets",
    host="0.0.0.0",
    port=8080,
    log_level="DEBUG",
    superusers={"12345", "67890"},
    nickname={"bot", "助手"},
    command_start={"/", "!", "#"},
    command_sep={".", " "},
    session_expire_timeout=timedelta(minutes=5),
    api_timeout=60.0
)

print(f"Driver: {config.driver}")
print(f"Host: {config.host}")
print(f"Port: {config.port}")
print(f"Superusers: {config.superusers}")

Base Settings Class

Foundation class for all configuration with environment variable support.

class BaseSettings(BaseModel):
    """Base class for settings with environment variable support."""
    
    def __init__(
        self,
        _env_file: Optional[DOTENV_TYPE] = None,
        _env_file_encoding: Optional[str] = None,
        _env_nested_delimiter: Optional[str] = None,
        _secrets_dir: Optional[Union[Path, str]] = None,
        **values: Any
    ):
        """
        Initialize settings with environment file and custom values.
        
        Parameters:
        - _env_file: Environment file path(s)
        - _env_file_encoding: Environment file encoding
        - _env_nested_delimiter: Delimiter for nested environment variables
        - _secrets_dir: Directory containing secret files
        - **values: Custom configuration values
        """
    
    def _settings_build_values(
        self,
        init_kwargs: dict[str, Any],
        _env_file: Optional[DOTENV_TYPE] = None,
        _env_file_encoding: Optional[str] = None,
        _env_nested_delimiter: Optional[str] = None,
        _secrets_dir: Optional[Union[Path, str]] = None,
    ) -> dict[str, Any]:
        """Build configuration values from multiple sources."""

Usage example:

from nonebot.config import BaseSettings
from pydantic import Field

# Create custom configuration class
class MyBotConfig(BaseSettings):
    bot_name: str = "MyBot"
    debug_mode: bool = False
    max_users: int = Field(default=100, ge=1, le=10000)
    
    class Config:
        env_prefix = "MYBOT_"

# Load from environment variables
# export MYBOT_BOT_NAME="SuperBot"
# export MYBOT_DEBUG_MODE=true
# export MYBOT_MAX_USERS=500

config = MyBotConfig()
print(f"Bot Name: {config.bot_name}")      # "SuperBot"
print(f"Debug Mode: {config.debug_mode}")  # True
print(f"Max Users: {config.max_users}")    # 500

# Load from .env file
config = MyBotConfig(_env_file=".env.local")

# Override with custom values
config = MyBotConfig(
    bot_name="CustomBot",
    debug_mode=True,
    _env_file=".env"
)

Configuration Examples

Environment File Configuration

Create .env files for different environments:

.env.development:

ENVIRONMENT=development
DRIVER=~fastapi+~httpx+~websockets
HOST=127.0.0.1
PORT=8080
LOG_LEVEL=DEBUG
SUPERUSERS=["12345"]
COMMAND_START=["/", "!"]
API_TIMEOUT=30.0

.env.production:

ENVIRONMENT=production
DRIVER=~fastapi+~httpx
HOST=0.0.0.0
PORT=80
LOG_LEVEL=INFO
SUPERUSERS=["admin123"]
COMMAND_START=["/"]
API_TIMEOUT=10.0

Programmatic Configuration

import nonebot
from nonebot.config import Config
from datetime import timedelta

# Configuration for development
dev_config = Config(
    driver="~fastapi+~httpx+~websockets",
    host="127.0.0.1",
    port=8080,
    log_level="DEBUG",
    superusers={"developer123"},
    nickname={"dev-bot", "开发机器人"},
    command_start={"/", "!", "#"},
    session_expire_timeout=timedelta(minutes=10),
    api_timeout=60.0
)

# Initialize NoneBot with custom config
nonebot.init(**dev_config.dict())

# Configuration for production  
prod_config = Config(
    driver="~fastapi+~httpx",
    host="0.0.0.0", 
    port=80,
    log_level="WARNING",
    superusers={"admin123", "admin456"},
    nickname={"bot"},
    command_start={"/"},
    session_expire_timeout=timedelta(minutes=2),
    api_timeout=30.0
)

Plugin-Specific Configuration

from pydantic import BaseModel, Field
from nonebot import get_plugin_config

# Define plugin configuration schema
class WeatherPluginConfig(BaseModel):
    api_key: str = Field(..., description="Weather API key")
    default_city: str = Field("Beijing", description="Default city")
    timeout: int = Field(30, ge=1, le=300, description="Request timeout")
    cache_ttl: int = Field(3600, ge=0, description="Cache TTL in seconds")
    
    class Config:
        env_prefix = "WEATHER_"

# Get plugin configuration
config = get_plugin_config(WeatherPluginConfig)

# Use configuration
async def get_weather(city: str = None):
    city = city or config.default_city
    # Use config.api_key, config.timeout, etc.

Types

Configuration Types

DOTENV_TYPE = Union[Path, str, list[Union[Path, str]], tuple[Union[Path, str], ...]]
"""Type for environment file paths."""

IPvAnyAddress = Union[IPv4Address, IPv6Address]
"""Type for IP addresses."""

Model Configuration

class BaseModel:
    """Base Pydantic model for configuration classes."""
    
    def dict(self, **kwargs) -> dict[str, Any]:
        """Convert model to dictionary."""
    
    def json(self, **kwargs) -> str:
        """Convert model to JSON string."""
    
    @classmethod
    def parse_obj(cls, obj: Any) -> "BaseModel":
        """Parse object into model."""
    
    @classmethod 
    def parse_file(cls, path: Union[str, Path], **kwargs) -> "BaseModel":
        """Parse file into model."""

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