0
# Dependencies & Parameters
1
2
Dependency injection system for accessing framework components, event data, and parsed parameters in handlers. This system provides type-safe access to bot functionality and event information.
3
4
## Capabilities
5
6
### Dependency Injection
7
8
Core dependency injection functionality for handler parameters.
9
10
```python { .api }
11
def Depends(dependency: _DEPENDENCY_TYPE) -> Any:
12
"""
13
Declare a dependency for handler parameter injection.
14
15
Parameters:
16
- dependency: Dependency callable or function
17
18
Returns:
19
Any: Dependency result
20
"""
21
```
22
23
Usage example:
24
25
```python
26
from nonebot import on_command
27
from nonebot.params import Depends
28
from nonebot.adapters import Bot, Event
29
30
async def get_user_info(event: Event) -> dict:
31
"""Custom dependency that extracts user information."""
32
return {
33
"user_id": event.get_user_id(),
34
"session_id": event.get_session_id()
35
}
36
37
# Use dependency in handler
38
cmd = on_command("profile")
39
40
@cmd.handle()
41
async def handle_profile(
42
bot: Bot,
43
event: Event,
44
user_info: dict = Depends(get_user_info)
45
):
46
await bot.send(event, f"User ID: {user_info['user_id']}")
47
```
48
49
### Event Information Parameters
50
51
Access basic event information and metadata.
52
53
```python { .api }
54
def EventType() -> str:
55
"""
56
Get the event type.
57
58
Returns:
59
str: Event type string
60
"""
61
```
62
63
```python { .api }
64
def EventMessage() -> Any:
65
"""
66
Get the event message object.
67
68
Returns:
69
Any: Message object from the event
70
"""
71
```
72
73
```python { .api }
74
def EventPlainText() -> str:
75
"""
76
Get the plain text content of the event message.
77
78
Returns:
79
str: Plain text message content
80
"""
81
```
82
83
```python { .api }
84
def EventToMe() -> bool:
85
"""
86
Check if the event is directed to the bot.
87
88
Returns:
89
bool: True if event is directed to bot, False otherwise
90
"""
91
```
92
93
Usage example:
94
95
```python
96
from nonebot import on_message
97
from nonebot.params import EventType, EventMessage, EventPlainText, EventToMe
98
from nonebot.adapters import Bot, Event
99
100
handler = on_message()
101
102
@handler.handle()
103
async def handle_message(
104
bot: Bot,
105
event: Event,
106
event_type: str = EventType(),
107
message: Any = EventMessage(),
108
plain_text: str = EventPlainText(),
109
to_me: bool = EventToMe()
110
):
111
await bot.send(event, f"Type: {event_type}")
112
await bot.send(event, f"Text: {plain_text}")
113
if to_me:
114
await bot.send(event, "This message was directed to me!")
115
```
116
117
### Command Parameters
118
119
Access command-related information and arguments.
120
121
```python { .api }
122
def Command() -> tuple[str, ...]:
123
"""
124
Get the command tuple that triggered this handler.
125
126
Returns:
127
tuple[str, ...]: Command parts as tuple
128
"""
129
```
130
131
```python { .api }
132
def RawCommand() -> str:
133
"""
134
Get the raw command text.
135
136
Returns:
137
str: Raw command text
138
"""
139
```
140
141
```python { .api }
142
def CommandArg() -> Any:
143
"""
144
Get the arguments passed to the command.
145
146
Returns:
147
Any: Command arguments (usually Message object)
148
"""
149
```
150
151
```python { .api }
152
def CommandStart() -> str:
153
"""
154
Get the command prefix that was used.
155
156
Returns:
157
str: Command prefix character
158
"""
159
```
160
161
```python { .api }
162
def CommandWhitespace() -> str:
163
"""
164
Get the whitespace between command and arguments.
165
166
Returns:
167
str: Whitespace string
168
"""
169
```
170
171
Usage example:
172
173
```python
174
from nonebot import on_command
175
from nonebot.params import Command, RawCommand, CommandArg, CommandStart
176
from nonebot.adapters import Bot, Event
177
178
cmd = on_command("weather")
179
180
@cmd.handle()
181
async def handle_weather(
182
bot: Bot,
183
event: Event,
184
command: tuple[str, ...] = Command(),
185
raw_cmd: str = RawCommand(),
186
args: Any = CommandArg(),
187
prefix: str = CommandStart()
188
):
189
city = args.extract_plain_text().strip()
190
await bot.send(event, f"Command: {command}")
191
await bot.send(event, f"Raw: {raw_cmd}")
192
await bot.send(event, f"Prefix: {prefix}")
193
await bot.send(event, f"Weather for: {city}")
194
```
195
196
### Shell Command Parameters
197
198
Access parsed shell command arguments.
199
200
```python { .api }
201
def ShellCommandArgs() -> Any:
202
"""
203
Get parsed shell command arguments as Namespace.
204
205
Returns:
206
Any: Parsed arguments (argparse.Namespace)
207
"""
208
```
209
210
```python { .api }
211
def ShellCommandArgv() -> Any:
212
"""
213
Get raw shell command argument list.
214
215
Returns:
216
Any: Raw argument list
217
"""
218
```
219
220
Usage example:
221
222
```python
223
from nonebot import on_shell_command
224
from nonebot.params import ShellCommandArgs, ShellCommandArgv
225
from nonebot.rule import ArgumentParser
226
from nonebot.adapters import Bot, Event
227
228
# Create argument parser
229
parser = ArgumentParser()
230
parser.add_argument("--name", type=str, required=True)
231
parser.add_argument("--count", type=int, default=1)
232
parser.add_argument("--verbose", "-v", action="store_true")
233
234
greet = on_shell_command("greet", parser=parser)
235
236
@greet.handle()
237
async def handle_greet(
238
bot: Bot,
239
event: Event,
240
args: Any = ShellCommandArgs(),
241
argv: Any = ShellCommandArgv()
242
):
243
name = args.name
244
count = args.count
245
verbose = args.verbose
246
247
if verbose:
248
await bot.send(event, f"Raw arguments: {argv}")
249
250
for i in range(count):
251
await bot.send(event, f"Hello, {name}!")
252
```
253
254
### Regular Expression Parameters
255
256
Access regex match results and captured groups.
257
258
```python { .api }
259
def RegexMatched() -> Match[str]:
260
"""
261
Get the regex match result.
262
263
Returns:
264
Match[str]: Regular expression match object
265
"""
266
```
267
268
```python { .api }
269
def RegexStr(*groups: Union[str, int]) -> Union[str, tuple[Union[str, Any], ...], Any]:
270
"""
271
Get specific regex groups by index or name.
272
273
Parameters:
274
- *groups: Group indices or names to extract
275
276
Returns:
277
Union[str, tuple, Any]: Single group string or tuple of groups
278
"""
279
```
280
281
```python { .api }
282
def RegexGroup() -> tuple[Any, ...]:
283
"""
284
Get all regex groups as tuple.
285
286
Returns:
287
tuple[Any, ...]: All captured groups
288
"""
289
```
290
291
```python { .api }
292
def RegexDict() -> dict[str, Any]:
293
"""
294
Get named regex groups as dictionary.
295
296
Returns:
297
dict[str, Any]: Named captured groups
298
"""
299
```
300
301
Usage example:
302
303
```python
304
from nonebot import on_regex
305
from nonebot.params import RegexMatched, RegexStr, RegexGroup, RegexDict
306
from nonebot.adapters import Bot, Event
307
308
# Match pattern with named groups
309
pattern = r"(?P<command>\w+)\s+(?P<number>\d+)"
310
handler = on_regex(pattern)
311
312
@handler.handle()
313
async def handle_regex(
314
bot: Bot,
315
event: Event,
316
matched: Match = RegexMatched(),
317
command: str = RegexStr("command"),
318
number: str = RegexStr("number"),
319
groups: tuple = RegexGroup(),
320
group_dict: dict = RegexDict()
321
):
322
await bot.send(event, f"Full match: {matched.group()}")
323
await bot.send(event, f"Command: {command}")
324
await bot.send(event, f"Number: {number}")
325
await bot.send(event, f"All groups: {groups}")
326
await bot.send(event, f"Named groups: {group_dict}")
327
```
328
329
### Text Matching Parameters
330
331
Access matched text from various text matching handlers.
332
333
```python { .api }
334
def Startswith() -> str:
335
"""
336
Get the text that matched startswith pattern.
337
338
Returns:
339
str: Matched startswith text
340
"""
341
```
342
343
```python { .api }
344
def Endswith() -> str:
345
"""
346
Get the text that matched endswith pattern.
347
348
Returns:
349
str: Matched endswith text
350
"""
351
```
352
353
```python { .api }
354
def Fullmatch() -> str:
355
"""
356
Get the text that matched fullmatch pattern.
357
358
Returns:
359
str: Matched fullmatch text
360
"""
361
```
362
363
```python { .api }
364
def Keyword() -> str:
365
"""
366
Get the keyword that was matched.
367
368
Returns:
369
str: Matched keyword
370
"""
371
```
372
373
Usage example:
374
375
```python
376
from nonebot import on_startswith, on_keyword
377
from nonebot.params import Startswith, Keyword
378
from nonebot.adapters import Bot, Event
379
380
# Startswith handler
381
starts_handler = on_startswith("prefix")
382
383
@starts_handler.handle()
384
async def handle_starts(
385
bot: Bot,
386
event: Event,
387
matched_text: str = Startswith()
388
):
389
await bot.send(event, f"Matched prefix: {matched_text}")
390
391
# Keyword handler
392
keyword_handler = on_keyword("help", "assist", "support")
393
394
@keyword_handler.handle()
395
async def handle_keyword(
396
bot: Bot,
397
event: Event,
398
keyword: str = Keyword()
399
):
400
await bot.send(event, f"Detected keyword: {keyword}")
401
```
402
403
### Conversation State Parameters
404
405
Access conversation state and received events.
406
407
```python { .api }
408
def Received(id: Optional[str] = None, default: Any = None) -> Any:
409
"""
410
Get received event by ID.
411
412
Parameters:
413
- id: Event ID to retrieve, None for any event
414
- default: Default value if event not found
415
416
Returns:
417
Any: Received event or default value
418
"""
419
```
420
421
```python { .api }
422
def LastReceived(default: Any = None) -> Any:
423
"""
424
Get the last received event.
425
426
Parameters:
427
- default: Default value if no event received
428
429
Returns:
430
Any: Last received event or default value
431
"""
432
```
433
434
```python { .api }
435
def ReceivePromptResult(id: Optional[str] = None) -> Any:
436
"""
437
Get the result of a receive prompt.
438
439
Parameters:
440
- id: Prompt ID, None for latest
441
442
Returns:
443
Any: Prompt result
444
"""
445
```
446
447
```python { .api }
448
def PausePromptResult() -> Any:
449
"""
450
Get the result of a pause prompt.
451
452
Returns:
453
Any: Pause prompt result
454
"""
455
```
456
457
Usage example:
458
459
```python
460
from nonebot import on_command
461
from nonebot.params import Received, LastReceived
462
from nonebot.adapters import Bot, Event
463
464
multi_step = on_command("setup")
465
466
@multi_step.handle()
467
async def handle_setup(bot: Bot, event: Event):
468
await bot.send(event, "What's your name?")
469
470
@multi_step.got("name")
471
async def got_name(bot: Bot, event: Event):
472
name = event.get_plaintext().strip()
473
await bot.send(event, f"Hello {name}! What's your age?")
474
475
@multi_step.got("age")
476
async def got_age(
477
bot: Bot,
478
event: Event,
479
name_event: Event = Received("name"),
480
last_event: Event = LastReceived()
481
):
482
name = name_event.get_plaintext().strip()
483
age = event.get_plaintext().strip()
484
await bot.send(event, f"Nice to meet you, {name} ({age} years old)!")
485
```
486
487
## Types
488
489
### Parameter Classes
490
491
```python { .api }
492
class Param(abc.ABC, FieldInfo):
493
"""Base class for dependency injection parameters."""
494
495
def _solve(self, **kwargs) -> Any:
496
"""Solve parameter value (abstract method)."""
497
498
def _check(self, **kwargs) -> None:
499
"""Pre-check parameter (optional)."""
500
501
class Dependent[R](Generic[R]):
502
"""Dependency injection container."""
503
504
call: _DependentCallable[R]
505
"""Callable object."""
506
507
params: tuple[ModelField, ...]
508
"""Named parameters."""
509
510
parameterless: tuple[Param, ...]
511
"""Parameterless parameters."""
512
513
def __call__(self, **kwargs) -> R:
514
"""Execute dependent."""
515
516
def solve(self, **params) -> dict[str, Any]:
517
"""Solve parameter values."""
518
```
519
520
### Framework Parameter Classes
521
522
```python { .api }
523
class BotParam(Param):
524
"""Bot parameter injection."""
525
526
class EventParam(Param):
527
"""Event parameter injection."""
528
529
class StateParam(Param):
530
"""State parameter injection."""
531
532
class MatcherParam(Param):
533
"""Matcher parameter injection."""
534
535
class ExceptionParam(Param):
536
"""Exception parameter injection."""
537
538
class DependParam(Param):
539
"""Sub-dependency parameter injection."""
540
541
class DefaultParam(Param):
542
"""Default parameter injection."""
543
```
544
545
### Argument Parameters
546
547
```python { .api }
548
class Arg(Param):
549
"""Handler argument parameter."""
550
551
class ArgStr(Param):
552
"""Handler string argument parameter."""
553
554
class ArgPlainText(Param):
555
"""Handler plain text argument parameter."""
556
557
class ArgPromptResult(Param):
558
"""Argument prompt result parameter."""
559
```