0
# Configuration
1
2
Configuration classes and utilities for setting up the NoneBot2 framework environment and behavior. The configuration system supports environment variables, config files, and programmatic configuration.
3
4
## Capabilities
5
6
### Environment Configuration
7
8
Manage runtime environment settings.
9
10
```python { .api }
11
class Env(BaseSettings):
12
"""Runtime environment configuration."""
13
14
environment: str = "prod"
15
"""Current environment name (prod, dev, test, etc.)."""
16
17
def __init__(self, **kwargs):
18
"""Initialize environment configuration."""
19
```
20
21
Usage example:
22
23
```python
24
from nonebot.config import Env
25
26
# Get current environment
27
env = Env()
28
print(f"Current environment: {env.environment}")
29
30
# Set environment via environment variable
31
# export ENVIRONMENT=development
32
env = Env()
33
print(f"Environment: {env.environment}") # "development"
34
```
35
36
### Main Configuration
37
38
Core NoneBot2 framework configuration with all runtime settings.
39
40
```python { .api }
41
class Config(BaseSettings):
42
"""Main NoneBot configuration with all framework settings."""
43
44
# Driver Configuration
45
driver: str = "~fastapi"
46
"""Driver specification string."""
47
48
# Server Configuration
49
host: IPvAnyAddress = IPv4Address("127.0.0.1")
50
"""Server host address."""
51
52
port: int = 8080
53
"""Server port number (1-65535)."""
54
55
# Logging Configuration
56
log_level: Union[int, str] = "INFO"
57
"""Logging level (DEBUG, INFO, WARNING, ERROR, CRITICAL)."""
58
59
# API Configuration
60
api_timeout: Optional[float] = 30.0
61
"""API request timeout in seconds."""
62
63
# Bot Configuration
64
superusers: set[str] = set()
65
"""Bot superuser IDs with administrative privileges."""
66
67
nickname: set[str] = set()
68
"""Bot nicknames for @-mentions."""
69
70
# Command Configuration
71
command_start: set[str] = {"/"}
72
"""Command prefix characters."""
73
74
command_sep: set[str] = {"."}
75
"""Command separator characters for sub-commands."""
76
77
# Session Configuration
78
session_expire_timeout: timedelta = timedelta(minutes=2)
79
"""Session timeout duration."""
80
81
def __init__(self, **kwargs):
82
"""Initialize configuration with custom values."""
83
```
84
85
Usage example:
86
87
```python
88
from nonebot.config import Config
89
from datetime import timedelta
90
91
# Create configuration with defaults
92
config = Config()
93
94
# Create configuration with custom values
95
config = Config(
96
driver="~fastapi+~httpx+~websockets",
97
host="0.0.0.0",
98
port=8080,
99
log_level="DEBUG",
100
superusers={"12345", "67890"},
101
nickname={"bot", "助手"},
102
command_start={"/", "!", "#"},
103
command_sep={".", " "},
104
session_expire_timeout=timedelta(minutes=5),
105
api_timeout=60.0
106
)
107
108
print(f"Driver: {config.driver}")
109
print(f"Host: {config.host}")
110
print(f"Port: {config.port}")
111
print(f"Superusers: {config.superusers}")
112
```
113
114
### Base Settings Class
115
116
Foundation class for all configuration with environment variable support.
117
118
```python { .api }
119
class BaseSettings(BaseModel):
120
"""Base class for settings with environment variable support."""
121
122
def __init__(
123
self,
124
_env_file: Optional[DOTENV_TYPE] = None,
125
_env_file_encoding: Optional[str] = None,
126
_env_nested_delimiter: Optional[str] = None,
127
_secrets_dir: Optional[Union[Path, str]] = None,
128
**values: Any
129
):
130
"""
131
Initialize settings with environment file and custom values.
132
133
Parameters:
134
- _env_file: Environment file path(s)
135
- _env_file_encoding: Environment file encoding
136
- _env_nested_delimiter: Delimiter for nested environment variables
137
- _secrets_dir: Directory containing secret files
138
- **values: Custom configuration values
139
"""
140
141
def _settings_build_values(
142
self,
143
init_kwargs: dict[str, Any],
144
_env_file: Optional[DOTENV_TYPE] = None,
145
_env_file_encoding: Optional[str] = None,
146
_env_nested_delimiter: Optional[str] = None,
147
_secrets_dir: Optional[Union[Path, str]] = None,
148
) -> dict[str, Any]:
149
"""Build configuration values from multiple sources."""
150
```
151
152
Usage example:
153
154
```python
155
from nonebot.config import BaseSettings
156
from pydantic import Field
157
158
# Create custom configuration class
159
class MyBotConfig(BaseSettings):
160
bot_name: str = "MyBot"
161
debug_mode: bool = False
162
max_users: int = Field(default=100, ge=1, le=10000)
163
164
class Config:
165
env_prefix = "MYBOT_"
166
167
# Load from environment variables
168
# export MYBOT_BOT_NAME="SuperBot"
169
# export MYBOT_DEBUG_MODE=true
170
# export MYBOT_MAX_USERS=500
171
172
config = MyBotConfig()
173
print(f"Bot Name: {config.bot_name}") # "SuperBot"
174
print(f"Debug Mode: {config.debug_mode}") # True
175
print(f"Max Users: {config.max_users}") # 500
176
177
# Load from .env file
178
config = MyBotConfig(_env_file=".env.local")
179
180
# Override with custom values
181
config = MyBotConfig(
182
bot_name="CustomBot",
183
debug_mode=True,
184
_env_file=".env"
185
)
186
```
187
188
## Configuration Examples
189
190
### Environment File Configuration
191
192
Create `.env` files for different environments:
193
194
**.env.development:**
195
```bash
196
ENVIRONMENT=development
197
DRIVER=~fastapi+~httpx+~websockets
198
HOST=127.0.0.1
199
PORT=8080
200
LOG_LEVEL=DEBUG
201
SUPERUSERS=["12345"]
202
COMMAND_START=["/", "!"]
203
API_TIMEOUT=30.0
204
```
205
206
**.env.production:**
207
```bash
208
ENVIRONMENT=production
209
DRIVER=~fastapi+~httpx
210
HOST=0.0.0.0
211
PORT=80
212
LOG_LEVEL=INFO
213
SUPERUSERS=["admin123"]
214
COMMAND_START=["/"]
215
API_TIMEOUT=10.0
216
```
217
218
### Programmatic Configuration
219
220
```python
221
import nonebot
222
from nonebot.config import Config
223
from datetime import timedelta
224
225
# Configuration for development
226
dev_config = Config(
227
driver="~fastapi+~httpx+~websockets",
228
host="127.0.0.1",
229
port=8080,
230
log_level="DEBUG",
231
superusers={"developer123"},
232
nickname={"dev-bot", "开发机器人"},
233
command_start={"/", "!", "#"},
234
session_expire_timeout=timedelta(minutes=10),
235
api_timeout=60.0
236
)
237
238
# Initialize NoneBot with custom config
239
nonebot.init(**dev_config.dict())
240
241
# Configuration for production
242
prod_config = Config(
243
driver="~fastapi+~httpx",
244
host="0.0.0.0",
245
port=80,
246
log_level="WARNING",
247
superusers={"admin123", "admin456"},
248
nickname={"bot"},
249
command_start={"/"},
250
session_expire_timeout=timedelta(minutes=2),
251
api_timeout=30.0
252
)
253
```
254
255
### Plugin-Specific Configuration
256
257
```python
258
from pydantic import BaseModel, Field
259
from nonebot import get_plugin_config
260
261
# Define plugin configuration schema
262
class WeatherPluginConfig(BaseModel):
263
api_key: str = Field(..., description="Weather API key")
264
default_city: str = Field("Beijing", description="Default city")
265
timeout: int = Field(30, ge=1, le=300, description="Request timeout")
266
cache_ttl: int = Field(3600, ge=0, description="Cache TTL in seconds")
267
268
class Config:
269
env_prefix = "WEATHER_"
270
271
# Get plugin configuration
272
config = get_plugin_config(WeatherPluginConfig)
273
274
# Use configuration
275
async def get_weather(city: str = None):
276
city = city or config.default_city
277
# Use config.api_key, config.timeout, etc.
278
```
279
280
## Types
281
282
### Configuration Types
283
284
```python { .api }
285
DOTENV_TYPE = Union[Path, str, list[Union[Path, str]], tuple[Union[Path, str], ...]]
286
"""Type for environment file paths."""
287
288
IPvAnyAddress = Union[IPv4Address, IPv6Address]
289
"""Type for IP addresses."""
290
```
291
292
### Model Configuration
293
294
```python { .api }
295
class BaseModel:
296
"""Base Pydantic model for configuration classes."""
297
298
def dict(self, **kwargs) -> dict[str, Any]:
299
"""Convert model to dictionary."""
300
301
def json(self, **kwargs) -> str:
302
"""Convert model to JSON string."""
303
304
@classmethod
305
def parse_obj(cls, obj: Any) -> "BaseModel":
306
"""Parse object into model."""
307
308
@classmethod
309
def parse_file(cls, path: Union[str, Path], **kwargs) -> "BaseModel":
310
"""Parse file into model."""
311
```