0
# Adapters & Drivers
1
2
Base classes and interfaces for implementing protocol adapters and runtime drivers. These components provide the foundation for connecting NoneBot2 to different messaging platforms and runtime environments.
3
4
## Capabilities
5
6
### Adapter Base Class
7
8
Base class for implementing protocol adapters that connect NoneBot2 to messaging platforms.
9
10
```python { .api }
11
class Adapter(abc.ABC):
12
"""Protocol adapter base class for connecting to messaging platforms."""
13
14
def __init__(self, driver: Driver, **kwargs: Any):
15
"""
16
Initialize adapter with driver instance.
17
18
Parameters:
19
- driver: Driver instance
20
- **kwargs: Additional adapter-specific configuration
21
"""
22
23
@abc.abstractmethod
24
def get_name(self) -> str:
25
"""
26
Get adapter name.
27
28
Returns:
29
str: Unique adapter name
30
"""
31
32
def bot_connect(self, bot: Bot) -> None:
33
"""
34
Handle bot connection event.
35
36
Parameters:
37
- bot: Bot instance that connected
38
"""
39
40
def bot_disconnect(self, bot: Bot) -> None:
41
"""
42
Handle bot disconnection event.
43
44
Parameters:
45
- bot: Bot instance that disconnected
46
"""
47
48
def setup_http_server(self, setup: HTTPServerSetup) -> None:
49
"""
50
Setup HTTP server for receiving webhooks.
51
52
Parameters:
53
- setup: HTTP server setup configuration
54
"""
55
56
def setup_websocket_server(self, setup: WebSocketServerSetup) -> None:
57
"""
58
Setup WebSocket server for receiving connections.
59
60
Parameters:
61
- setup: WebSocket server setup configuration
62
"""
63
64
async def request(self, setup: Request) -> Response:
65
"""
66
Make HTTP request.
67
68
Parameters:
69
- setup: Request configuration
70
71
Returns:
72
Response: HTTP response
73
"""
74
75
async def websocket(self, setup: Request) -> AsyncGenerator[WebSocket, None]:
76
"""
77
Create WebSocket connection.
78
79
Parameters:
80
- setup: WebSocket request configuration
81
82
Yields:
83
WebSocket: WebSocket connection
84
"""
85
```
86
87
### Bot Base Class
88
89
Base class for bot implementations that handle messages and API calls.
90
91
```python { .api }
92
class Bot(abc.ABC):
93
"""Bot base class for handling messages and API calls."""
94
95
def __init__(self, adapter: Adapter, self_id: str):
96
"""
97
Initialize bot instance.
98
99
Parameters:
100
- adapter: Adapter instance that created this bot
101
- self_id: Bot's unique identifier
102
"""
103
104
async def call_api(self, api: str, **data: Any) -> Any:
105
"""
106
Call bot API method.
107
108
Parameters:
109
- api: API method name
110
- **data: API method parameters
111
112
Returns:
113
Any: API call result
114
115
Raises:
116
ApiNotAvailable: If API is not available
117
ActionFailed: If API call fails
118
NetworkError: If network error occurs
119
"""
120
121
def __getattr__(self, name: str) -> _ApiCall:
122
"""
123
Dynamic API call access.
124
125
Parameters:
126
- name: API method name
127
128
Returns:
129
_ApiCall: API call wrapper
130
"""
131
132
@property
133
def type(self) -> str:
134
"""
135
Get adapter name.
136
137
Returns:
138
str: Adapter name
139
"""
140
141
@property
142
def config(self) -> Config:
143
"""
144
Get global configuration.
145
146
Returns:
147
Config: Global configuration instance
148
"""
149
```
150
151
### Event Base Class
152
153
Base class for platform events with required abstract methods.
154
155
```python { .api }
156
class Event(abc.ABC, BaseModel):
157
"""Event base class for platform events."""
158
159
@abc.abstractmethod
160
def get_type(self) -> str:
161
"""
162
Get event type.
163
164
Returns:
165
str: Event type string
166
"""
167
168
@abc.abstractmethod
169
def get_event_name(self) -> str:
170
"""
171
Get event name.
172
173
Returns:
174
str: Event name string
175
"""
176
177
@abc.abstractmethod
178
def get_event_description(self) -> str:
179
"""
180
Get event description.
181
182
Returns:
183
str: Human-readable event description
184
"""
185
186
@abc.abstractmethod
187
def get_user_id(self) -> str:
188
"""
189
Get user ID from event.
190
191
Returns:
192
str: User identifier
193
"""
194
195
@abc.abstractmethod
196
def get_session_id(self) -> str:
197
"""
198
Get session ID from event.
199
200
Returns:
201
str: Session identifier
202
"""
203
204
@abc.abstractmethod
205
def get_message(self) -> Message:
206
"""
207
Get message content from event.
208
209
Returns:
210
Message: Message object
211
"""
212
213
@abc.abstractmethod
214
def is_tome(self) -> bool:
215
"""
216
Check if event is directed to bot.
217
218
Returns:
219
bool: True if directed to bot
220
"""
221
222
def get_plaintext(self) -> str:
223
"""
224
Get plain text from message.
225
226
Returns:
227
str: Plain text content
228
"""
229
230
def get_log_string(self) -> str:
231
"""
232
Get log string representation.
233
234
Returns:
235
str: Log string
236
"""
237
```
238
239
### Driver Base Class
240
241
Base class for runtime drivers that manage bot lifecycle and connections.
242
243
```python { .api }
244
class Driver(abc.ABC):
245
"""Base driver class for managing bot runtime."""
246
247
@property
248
@abc.abstractmethod
249
def type(self) -> str:
250
"""
251
Get driver type.
252
253
Returns:
254
str: Driver type string
255
"""
256
257
@property
258
@abc.abstractmethod
259
def logger(self) -> loguru.Logger:
260
"""
261
Get driver logger.
262
263
Returns:
264
loguru.Logger: Logger instance
265
"""
266
267
@abc.abstractmethod
268
def run(self, *args, **kwargs) -> None:
269
"""
270
Run the driver.
271
272
Parameters:
273
- *args: Runtime arguments
274
- **kwargs: Runtime keyword arguments
275
"""
276
277
def on_startup(self, func: _LIFESPAN_FUNC) -> _LIFESPAN_FUNC:
278
"""
279
Register startup handler.
280
281
Parameters:
282
- func: Startup handler function
283
284
Returns:
285
_LIFESPAN_FUNC: Handler function
286
"""
287
288
def on_shutdown(self, func: _LIFESPAN_FUNC) -> _LIFESPAN_FUNC:
289
"""
290
Register shutdown handler.
291
292
Parameters:
293
- func: Shutdown handler function
294
295
Returns:
296
_LIFESPAN_FUNC: Handler function
297
"""
298
```
299
300
### Driver Mixins
301
302
Mixin classes that add specific capabilities to drivers.
303
304
```python { .api }
305
class Mixin(abc.ABC):
306
"""Base mixin class for extending driver capabilities."""
307
308
class ForwardMixin(Mixin):
309
"""Mixin for forward connection support (bot connects to platform)."""
310
311
class ReverseMixin(Mixin):
312
"""Mixin for reverse connection support (platform connects to bot)."""
313
314
class ASGIMixin(Mixin):
315
"""Mixin for ASGI server support."""
316
317
@property
318
@abc.abstractmethod
319
def server_app(self) -> Any:
320
"""
321
Get server application object.
322
323
Returns:
324
Any: Server app (FastAPI, Quart, etc.)
325
"""
326
327
@property
328
@abc.abstractmethod
329
def asgi(self) -> Any:
330
"""
331
Get ASGI application.
332
333
Returns:
334
Any: ASGI application
335
"""
336
337
class HTTPClientMixin(Mixin):
338
"""Mixin for HTTP client support."""
339
340
@abc.abstractmethod
341
async def request(self, setup: Request) -> Response:
342
"""
343
Make HTTP request.
344
345
Parameters:
346
- setup: Request configuration
347
348
Returns:
349
Response: HTTP response
350
"""
351
352
class WebSocketClientMixin(Mixin):
353
"""Mixin for WebSocket client support."""
354
355
@abc.abstractmethod
356
async def websocket(self, setup: Request) -> AsyncGenerator[WebSocket, None]:
357
"""
358
Create WebSocket connection.
359
360
Parameters:
361
- setup: WebSocket request configuration
362
363
Yields:
364
WebSocket: WebSocket connection
365
"""
366
```
367
368
### Composite Driver Classes
369
370
Pre-composed driver classes combining base driver with common mixins.
371
372
```python { .api }
373
class ForwardDriver(Driver, ForwardMixin):
374
"""Driver with forward connection capability."""
375
376
class ReverseDriver(Driver, ReverseMixin):
377
"""Driver with reverse connection capability."""
378
```
379
380
### HTTP & WebSocket Models
381
382
Data models for HTTP and WebSocket communication.
383
384
```python { .api }
385
class Request:
386
"""HTTP/WebSocket request model."""
387
388
method: str
389
url: URL
390
headers: dict[str, str]
391
cookies: Cookies
392
content: bytes
393
timeout: Optional[Timeout]
394
395
class Response:
396
"""HTTP response model."""
397
398
status_code: int
399
headers: dict[str, str]
400
content: bytes
401
402
def json(self) -> Any:
403
"""Parse response as JSON."""
404
405
def text(self) -> str:
406
"""Get response as text."""
407
408
class WebSocket:
409
"""WebSocket connection model."""
410
411
async def accept(self) -> None:
412
"""Accept WebSocket connection."""
413
414
async def close(self, code: int = 1000, reason: str = "") -> None:
415
"""Close WebSocket connection."""
416
417
async def receive(self) -> Union[str, bytes]:
418
"""Receive message from WebSocket."""
419
420
async def send(self, data: Union[str, bytes]) -> None:
421
"""Send message to WebSocket."""
422
423
class URL:
424
"""URL model for HTTP requests."""
425
426
scheme: str
427
host: str
428
port: Optional[int]
429
path: str
430
query: dict[str, str]
431
432
class Cookies:
433
"""Cookie management model."""
434
435
def get(self, key: str) -> Optional[str]:
436
"""Get cookie value."""
437
438
def set(self, key: str, value: str, **kwargs) -> None:
439
"""Set cookie value."""
440
441
class Timeout:
442
"""Request timeout configuration."""
443
444
connect: Optional[float]
445
read: Optional[float]
446
write: Optional[float]
447
total: Optional[float]
448
```
449
450
### Driver Utilities
451
452
Utility functions for working with drivers.
453
454
```python { .api }
455
def combine_driver(driver: type[Driver], *mixins: type[Mixin]) -> type[Driver]:
456
"""
457
Combine driver class with mixin classes.
458
459
Parameters:
460
- driver: Base driver class
461
- *mixins: Mixin classes to combine
462
463
Returns:
464
type[Driver]: Combined driver class
465
"""
466
```
467
468
Usage example:
469
470
```python
471
from nonebot.drivers import Driver, ASGIMixin, HTTPClientMixin, combine_driver
472
473
# Create custom driver class
474
class MyDriver(Driver):
475
@property
476
def type(self):
477
return "my_driver"
478
479
@property
480
def logger(self):
481
return loguru.logger
482
483
def run(self, *args, **kwargs):
484
print("Running my driver")
485
486
# Combine with mixins
487
MyASGIDriver = combine_driver(MyDriver, ASGIMixin, HTTPClientMixin)
488
489
# Use combined driver
490
driver = MyASGIDriver()
491
```
492
493
## Types
494
495
### Message Types
496
497
```python { .api }
498
class Message(abc.ABC, List[MessageSegment]):
499
"""Message base class extending list of message segments."""
500
501
def __str__(self) -> str:
502
"""Get string representation."""
503
504
def __add__(self, other) -> "Message":
505
"""Concatenate messages."""
506
507
def extract_plain_text(self) -> str:
508
"""Extract plain text from message."""
509
510
class MessageSegment(abc.ABC, BaseModel):
511
"""Message segment base class for message components."""
512
513
type: str
514
"""Segment type."""
515
516
data: dict[str, Any]
517
"""Segment data."""
518
519
def __str__(self) -> str:
520
"""Get string representation."""
521
522
def is_text(self) -> bool:
523
"""Check if segment is text."""
524
525
class MessageTemplate(abc.ABC):
526
"""Message template base class for templated messages."""
527
528
def format(self, **kwargs) -> Message:
529
"""Format template with arguments."""
530
```
531
532
### Server Setup Types
533
534
```python { .api }
535
class HTTPServerSetup:
536
"""HTTP server setup configuration."""
537
538
path: URL
539
method: str
540
name: str
541
542
class WebSocketServerSetup:
543
"""WebSocket server setup configuration."""
544
545
path: URL
546
name: str
547
548
class HTTPClientSession:
549
"""HTTP client session for making requests."""
550
551
async def request(self, setup: Request) -> Response:
552
"""Make HTTP request."""
553
554
async def websocket(self, setup: Request) -> AsyncGenerator[WebSocket, None]:
555
"""Create WebSocket connection."""
556
```
557
558
### Type Aliases
559
560
```python { .api }
561
HTTPVersion = Literal["1.0", "1.1", "2.0"]
562
"""HTTP version type."""
563
564
_LIFESPAN_FUNC = Callable[[], Awaitable[None]]
565
"""Lifespan function type."""
566
567
_ApiCall = Callable[..., Awaitable[Any]]
568
"""API call wrapper type."""
569
```