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.00
# NoneBot2
1
2
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.
3
4
## Package Information
5
6
- **Package Name**: nonebot2
7
- **Language**: Python
8
- **Installation**: `pip install nonebot2`
9
10
## Core Imports
11
12
```python
13
import nonebot
14
```
15
16
Common pattern for framework setup:
17
18
```python
19
import nonebot
20
from nonebot import on_command, on_message, get_driver
21
from nonebot.adapters import Bot, Event
22
```
23
24
## Basic Usage
25
26
```python
27
import nonebot
28
from nonebot import on_command
29
from nonebot.adapters import Bot, Event
30
from nonebot.params import CommandArg
31
from nonebot.typing import T_State
32
33
# Initialize NoneBot
34
nonebot.init()
35
36
# Create a simple command handler
37
hello = on_command("hello")
38
39
@hello.handle()
40
async def handle_hello(bot: Bot, event: Event, state: T_State, args=CommandArg()):
41
message = args.extract_plain_text().strip()
42
if message:
43
await bot.send(event, f"Hello, {message}!")
44
else:
45
await bot.send(event, "Hello, world!")
46
47
# Run the bot
48
if __name__ == "__main__":
49
nonebot.run()
50
```
51
52
## Architecture
53
54
NoneBot2 uses an event-driven architecture with several key components:
55
56
- **Driver**: Core runtime that handles connections and lifecycle management
57
- **Adapters**: Protocol implementations for different platforms (QQ, Telegram, etc.)
58
- **Bots**: Platform-specific instances that send/receive messages
59
- **Events**: Structured data representing user interactions and platform events
60
- **Matchers**: Event handlers that process specific types of events based on rules
61
- **Plugins**: Modular components containing related matchers and functionality
62
- **Dependencies**: Injection system for accessing framework components and parameters
63
64
This design enables maximum reusability across messaging platforms while maintaining type safety and extensibility through a comprehensive plugin ecosystem.
65
66
## Capabilities
67
68
### Framework Control
69
70
Core functions for initializing, configuring, and running the NoneBot2 framework, including global state management.
71
72
```python { .api }
73
def init(*, _env_file: Optional[DOTENV_TYPE] = None, **kwargs: Any) -> None: ...
74
def run(*args: Any, **kwargs: Any) -> None: ...
75
def get_driver() -> Driver: ...
76
```
77
78
[Framework Control](./framework-control.md)
79
80
### Bot Management
81
82
Functions for accessing and managing bot instances connected to the framework.
83
84
```python { .api }
85
def get_bot(self_id: Optional[str] = None) -> Bot: ...
86
def get_bots() -> dict[str, Bot]: ...
87
def get_adapter(name: Union[str, type[Adapter]]) -> Adapter: ...
88
def get_adapters() -> dict[str, Adapter]: ...
89
```
90
91
[Bot Management](./bot-management.md)
92
93
### Event Handlers
94
95
Create event responders that react to different types of platform events and messages.
96
97
```python { .api }
98
def on(type: str = "", rule: Optional[Rule] = None, **kwargs) -> type[Matcher]: ...
99
def on_message(**kwargs) -> type[Matcher]: ...
100
def on_notice(**kwargs) -> type[Matcher]: ...
101
def on_request(**kwargs) -> type[Matcher]: ...
102
def on_metaevent(**kwargs) -> type[Matcher]: ...
103
def on_type(types: Union[type[Event], tuple[type[Event], ...]], **kwargs) -> type[Matcher]: ...
104
```
105
106
[Event Handlers](./event-handlers.md)
107
108
### Message Matching
109
110
Specialized handlers for matching and responding to specific message patterns and commands.
111
112
```python { .api }
113
def on_command(cmd: Union[str, tuple[str, ...]], **kwargs) -> type[Matcher]: ...
114
def on_shell_command(
115
cmd: Union[str, tuple[str, ...]],
116
rule: Optional[Union[Rule, T_RuleChecker]] = None,
117
aliases: Optional[set[Union[str, tuple[str, ...]]]] = None,
118
parser: Optional[ArgumentParser] = None,
119
**kwargs
120
) -> type[Matcher]: ...
121
def on_startswith(msg: Union[str, tuple[str, ...]], **kwargs) -> type[Matcher]: ...
122
def on_endswith(msg: Union[str, tuple[str, ...]], **kwargs) -> type[Matcher]: ...
123
def on_fullmatch(msg: Union[str, tuple[str, ...]], **kwargs) -> type[Matcher]: ...
124
def on_keyword(*keywords: str, **kwargs) -> type[Matcher]: ...
125
def on_regex(pattern: Union[str, re.Pattern[str]], **kwargs) -> type[Matcher]: ...
126
```
127
128
[Message Matching](./message-matching.md)
129
130
### Plugin System
131
132
Functions for loading, managing, and configuring plugins that extend framework functionality.
133
134
```python { .api }
135
def load_plugin(module_path: Union[str, Path]) -> Optional[Plugin]: ...
136
def load_plugins(*plugin_dir: str) -> set[Plugin]: ...
137
def load_all_plugins(module_path: Iterable[str], plugin_dir: Iterable[str]) -> set[Plugin]: ...
138
def load_from_json(file_path: str, encoding: str = "utf-8") -> set[Plugin]: ...
139
def load_from_toml(file_path: str, encoding: str = "utf-8") -> set[Plugin]: ...
140
def load_builtin_plugin(name: str) -> Optional[Plugin]: ...
141
def load_builtin_plugins(*plugins: str) -> set[Plugin]: ...
142
def get_plugin(plugin_id: str) -> Optional[Plugin]: ...
143
def get_plugin_by_module_name(module_name: str) -> Optional[Plugin]: ...
144
def get_loaded_plugins() -> set[Plugin]: ...
145
def get_available_plugin_names() -> set[str]: ...
146
def get_plugin_config(config: type[C]) -> C: ...
147
def require(name: str) -> ModuleType: ...
148
149
class CommandGroup:
150
def __init__(self, cmd: Union[str, tuple[str, ...]], prefix_aliases: bool = False, **kwargs): ...
151
def command(self, cmd: Union[str, tuple[str, ...]], **kwargs) -> type[Matcher]: ...
152
def shell_command(self, cmd: Union[str, tuple[str, ...]], **kwargs) -> type[Matcher]: ...
153
154
class MatcherGroup:
155
def __init__(self, **kwargs): ...
156
def on(self, **kwargs) -> type[Matcher]: ...
157
def on_message(self, **kwargs) -> type[Matcher]: ...
158
def on_command(self, cmd: Union[str, tuple[str, ...]], **kwargs) -> type[Matcher]: ...
159
# ... other event handler methods
160
```
161
162
[Plugin System](./plugin-system.md)
163
164
### Configuration
165
166
Configuration classes and utilities for setting up the framework environment and behavior.
167
168
```python { .api }
169
class Config(BaseSettings):
170
driver: str = "~fastapi"
171
host: IPvAnyAddress = IPv4Address("127.0.0.1")
172
port: int = Field(default=8080, ge=1, le=65535)
173
log_level: Union[int, str] = "INFO"
174
api_timeout: Optional[float] = 30.0
175
superusers: set[str] = set()
176
nickname: set[str] = set()
177
command_start: set[str] = {"/"}
178
command_sep: set[str] = {"."}
179
session_expire_timeout: timedelta = timedelta(minutes=2)
180
181
class Env(BaseSettings):
182
environment: str = "prod"
183
```
184
185
[Configuration](./configuration.md)
186
187
### Dependencies & Parameters
188
189
Dependency injection system for accessing framework components, event data, and parsed parameters in handlers.
190
191
```python { .api }
192
def Depends(dependency: _DEPENDENCY_TYPE) -> Any: ...
193
def EventType() -> str: ...
194
def EventMessage() -> Any: ...
195
def EventPlainText() -> str: ...
196
def EventToMe() -> bool: ...
197
def Command() -> tuple[str, ...]: ...
198
def CommandArg() -> Any: ...
199
def CommandStart() -> str: ...
200
def RawCommand() -> str: ...
201
def ShellCommandArgs() -> Any: ...
202
def ShellCommandArgv() -> Any: ...
203
def RegexMatched() -> Match[str]: ...
204
205
class Arg(Param): ...
206
class ArgPlainText(Param): ...
207
class ArgStr(Param): ...
208
```
209
210
[Dependencies & Parameters](./dependencies-parameters.md)
211
212
### Adapters & Drivers
213
214
Base classes and interfaces for implementing protocol adapters and runtime drivers.
215
216
```python { .api }
217
class Adapter(abc.ABC):
218
def get_name(self) -> str: ...
219
def bot_connect(self, bot: Bot) -> None: ...
220
# ... additional methods
221
222
class Driver(abc.ABC):
223
def run(self, *args, **kwargs) -> None: ...
224
# ... additional methods
225
```
226
227
[Adapters & Drivers](./adapters-drivers.md)
228
229
## Exception Handling
230
231
NoneBot2 provides a comprehensive exception hierarchy for handling different types of errors and control flow:
232
233
```python { .api }
234
class NoneBotException(Exception): ...
235
236
# Rule Exception
237
class ParserExit(NoneBotException): ...
238
239
# Processor Exceptions
240
class ProcessException(NoneBotException): ...
241
class IgnoredException(ProcessException): ...
242
class SkippedException(ProcessException): ...
243
class TypeMisMatch(SkippedException): ...
244
class MockApiException(ProcessException): ...
245
class StopPropagation(ProcessException): ...
246
247
# Matcher Exceptions
248
class MatcherException(NoneBotException): ...
249
class PausedException(MatcherException): ...
250
class RejectedException(MatcherException): ...
251
class FinishedException(MatcherException): ...
252
253
# Adapter Exceptions
254
class AdapterException(NoneBotException): ...
255
class NoLogException(AdapterException): ...
256
class ApiNotAvailable(AdapterException): ...
257
class NetworkError(AdapterException): ...
258
class ActionFailed(AdapterException): ...
259
260
# Driver Exceptions
261
class DriverException(NoneBotException): ...
262
class WebSocketClosed(DriverException): ...
263
```
264
265
Exception hierarchy organized by purpose:
266
- **Control Flow**: `FinishedException`, `PausedException`, `RejectedException` - Control handler execution
267
- **Processing**: `IgnoredException`, `SkippedException`, `StopPropagation` - Control event processing
268
- **API/Network**: `ApiNotAvailable`, `ActionFailed`, `NetworkError` - Handle API and network issues
269
- **Parsing**: `ParserExit`, `TypeMisMatch` - Handle parsing and type errors
270
- **Connection**: `WebSocketClosed` - Handle connection issues
271
272
## Types
273
274
### Core Types
275
276
```python { .api }
277
T_State = dict[Any, Any]
278
T_Handler = _DependentCallable[Any]
279
T_RuleChecker = _DependentCallable[bool]
280
T_PermissionChecker = _DependentCallable[bool]
281
C = TypeVar("C") # Configuration type variable
282
```
283
284
### Rule and Parser Types
285
286
```python { .api }
287
from collections.abc import Iterable
288
from datetime import timedelta
289
from ipaddress import IPv4Address
290
from typing import TypeVar
291
from pydantic import Field, BaseSettings
292
from pydantic.networks import IPvAnyAddress
293
from nonebot.rule import Rule, ArgumentParser
294
```
295
296
### Configuration Types
297
298
```python { .api }
299
DOTENV_TYPE = Union[Path, str, list[Union[Path, str]], tuple[Union[Path, str], ...]]
300
```
301
302
### Hook Types
303
304
```python { .api }
305
T_BotConnectionHook = _DependentCallable[Any]
306
T_BotDisconnectionHook = _DependentCallable[Any]
307
T_CallingAPIHook = _DependentCallable[Any]
308
T_CalledAPIHook = _DependentCallable[Any]
309
```