or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

adapters-drivers.mdbot-management.mdconfiguration.mddependencies-parameters.mdevent-handlers.mdframework-control.mdindex.mdmessage-matching.mdplugin-system.md

event-handlers.mddocs/

0

# Event Handlers

1

2

Create event responders that react to different types of platform events and messages. Event handlers are the foundation for building interactive bot functionality.

3

4

## Capabilities

5

6

### Base Event Handler

7

8

Create handlers for any type of event with custom rules and permissions.

9

10

```python { .api }

11

def on(

12

type: str = "",

13

rule: Optional[Rule] = None,

14

permission: Optional[Permission] = None,

15

handlers: Optional[list[_Handler]] = None,

16

temp: bool = False,

17

expire_time: Optional[Union[datetime, timedelta]] = None,

18

priority: int = 1,

19

block: bool = False,

20

state: Optional[T_State] = None

21

) -> type[Matcher]:

22

"""

23

Create a basic event responder.

24

25

Parameters:

26

- type: Event type to match

27

- rule: Rule for matching events

28

- permission: Permission for handling events

29

- handlers: List of handler functions

30

- temp: Whether this is a temporary matcher

31

- expire_time: When temporary matcher expires

32

- priority: Handler priority (lower = higher priority)

33

- block: Whether to block further handler execution

34

- state: Initial state data

35

36

Returns:

37

type[Matcher]: Matcher class for this event handler

38

"""

39

```

40

41

Usage example:

42

43

```python

44

import nonebot

45

from nonebot import on

46

from nonebot.adapters import Bot, Event

47

48

# Create a handler for any event

49

any_event = on()

50

51

@any_event.handle()

52

async def handle_any_event(bot: Bot, event: Event):

53

print(f"Received event: {event.get_type()}")

54

55

# Create a handler with specific rule

56

from nonebot.rule import keyword

57

58

keyword_handler = on(rule=keyword("help"))

59

60

@keyword_handler.handle()

61

async def handle_help(bot: Bot, event: Event):

62

await bot.send(event, "This is help information")

63

```

64

65

### Message Events

66

67

Handle incoming messages from users.

68

69

```python { .api }

70

def on_message(

71

rule: Optional[Rule] = None,

72

permission: Optional[Permission] = None,

73

handlers: Optional[list[_Handler]] = None,

74

temp: bool = False,

75

expire_time: Optional[Union[datetime, timedelta]] = None,

76

priority: int = 1,

77

block: bool = False,

78

state: Optional[T_State] = None

79

) -> type[Matcher]:

80

"""

81

Create a message event handler.

82

83

Parameters:

84

- rule: Rule for matching messages

85

- permission: Permission for handling messages

86

- handlers: List of handler functions

87

- temp: Whether this is a temporary matcher

88

- expire_time: When temporary matcher expires

89

- priority: Handler priority (lower = higher priority)

90

- block: Whether to block further handler execution

91

- state: Initial state data

92

93

Returns:

94

type[Matcher]: Matcher class for message events

95

"""

96

```

97

98

Usage example:

99

100

```python

101

import nonebot

102

from nonebot import on_message

103

from nonebot.adapters import Bot, Event

104

105

# Handle all messages

106

message_handler = on_message()

107

108

@message_handler.handle()

109

async def handle_message(bot: Bot, event: Event):

110

message_text = event.get_plaintext()

111

await bot.send(event, f"You said: {message_text}")

112

113

# Handle messages with specific permission

114

from nonebot.permission import SUPERUSER

115

116

admin_messages = on_message(permission=SUPERUSER)

117

118

@admin_messages.handle()

119

async def handle_admin_message(bot: Bot, event: Event):

120

await bot.send(event, "Admin command received")

121

```

122

123

### Notice Events

124

125

Handle platform notifications (user joins/leaves, group changes, etc.).

126

127

```python { .api }

128

def on_notice(

129

rule: Optional[Rule] = None,

130

permission: Optional[Permission] = None,

131

handlers: Optional[list[_Handler]] = None,

132

temp: bool = False,

133

expire_time: Optional[Union[datetime, timedelta]] = None,

134

priority: int = 1,

135

block: bool = False,

136

state: Optional[T_State] = None

137

) -> type[Matcher]:

138

"""

139

Create a notice event handler.

140

141

Parameters:

142

- rule: Rule for matching notices

143

- permission: Permission for handling notices

144

- handlers: List of handler functions

145

- temp: Whether this is a temporary matcher

146

- expire_time: When temporary matcher expires

147

- priority: Handler priority (lower = higher priority)

148

- block: Whether to block further handler execution

149

- state: Initial state data

150

151

Returns:

152

type[Matcher]: Matcher class for notice events

153

"""

154

```

155

156

Usage example:

157

158

```python

159

import nonebot

160

from nonebot import on_notice

161

from nonebot.adapters import Bot, Event

162

163

# Handle all notices

164

notice_handler = on_notice()

165

166

@notice_handler.handle()

167

async def handle_notice(bot: Bot, event: Event):

168

notice_type = event.get_event_name()

169

print(f"Notice received: {notice_type}")

170

171

# Handle with priority

172

priority_notice = on_notice(priority=5)

173

174

@priority_notice.handle()

175

async def handle_priority_notice(bot: Bot, event: Event):

176

await bot.send(event, "High priority notice handler")

177

```

178

179

### Request Events

180

181

Handle platform requests (friend requests, group invitations, etc.).

182

183

```python { .api }

184

def on_request(

185

rule: Optional[Rule] = None,

186

permission: Optional[Permission] = None,

187

handlers: Optional[list[_Handler]] = None,

188

temp: bool = False,

189

expire_time: Optional[Union[datetime, timedelta]] = None,

190

priority: int = 1,

191

block: bool = False,

192

state: Optional[T_State] = None

193

) -> type[Matcher]:

194

"""

195

Create a request event handler.

196

197

Parameters:

198

- rule: Rule for matching requests

199

- permission: Permission for handling requests

200

- handlers: List of handler functions

201

- temp: Whether this is a temporary matcher

202

- expire_time: When temporary matcher expires

203

- priority: Handler priority (lower = higher priority)

204

- block: Whether to block further handler execution

205

- state: Initial state data

206

207

Returns:

208

type[Matcher]: Matcher class for request events

209

"""

210

```

211

212

Usage example:

213

214

```python

215

import nonebot

216

from nonebot import on_request

217

from nonebot.adapters import Bot, Event

218

219

# Handle all requests

220

request_handler = on_request()

221

222

@request_handler.handle()

223

async def handle_request(bot: Bot, event: Event):

224

request_type = event.get_event_name()

225

user_id = event.get_user_id()

226

print(f"Request from {user_id}: {request_type}")

227

```

228

229

### Meta Events

230

231

Handle platform meta events (heartbeat, lifecycle events, etc.).

232

233

```python { .api }

234

def on_metaevent(

235

rule: Optional[Rule] = None,

236

permission: Optional[Permission] = None,

237

handlers: Optional[list[_Handler]] = None,

238

temp: bool = False,

239

expire_time: Optional[Union[datetime, timedelta]] = None,

240

priority: int = 1,

241

block: bool = False,

242

state: Optional[T_State] = None

243

) -> type[Matcher]:

244

"""

245

Create a meta event handler.

246

247

Parameters:

248

- rule: Rule for matching meta events

249

- permission: Permission for handling meta events

250

- handlers: List of handler functions

251

- temp: Whether this is a temporary matcher

252

- expire_time: When temporary matcher expires

253

- priority: Handler priority (lower = higher priority)

254

- block: Whether to block further handler execution

255

- state: Initial state data

256

257

Returns:

258

type[Matcher]: Matcher class for meta events

259

"""

260

```

261

262

Usage example:

263

264

```python

265

import nonebot

266

from nonebot import on_metaevent

267

from nonebot.adapters import Bot, Event

268

269

# Handle meta events

270

meta_handler = on_metaevent()

271

272

@meta_handler.handle()

273

async def handle_meta(bot: Bot, event: Event):

274

meta_type = event.get_event_name()

275

print(f"Meta event: {meta_type}")

276

277

# Handle heartbeat specifically

278

from nonebot.rule import is_type

279

280

heartbeat = on_metaevent(rule=is_type("heartbeat"))

281

282

@heartbeat.handle()

283

async def handle_heartbeat(bot: Bot, event: Event):

284

print("Bot heartbeat received")

285

```

286

287

### Event Type Matching

288

289

Handle events of specific types using event class matching.

290

291

```python { .api }

292

def on_type(

293

types: Union[type[Event], tuple[type[Event], ...]],

294

rule: Optional[Rule] = None,

295

permission: Optional[Permission] = None,

296

handlers: Optional[list[_Handler]] = None,

297

temp: bool = False,

298

expire_time: Optional[Union[datetime, timedelta]] = None,

299

priority: int = 1,

300

block: bool = False,

301

state: Optional[T_State] = None

302

) -> type[Matcher]:

303

"""

304

Create handler for specific event types.

305

306

Parameters:

307

- types: Event type class or tuple of event type classes

308

- rule: Additional rule for matching events

309

- permission: Permission for handling events

310

- handlers: List of handler functions

311

- temp: Whether this is a temporary matcher

312

- expire_time: When temporary matcher expires

313

- priority: Handler priority (lower = higher priority)

314

- block: Whether to block further handler execution

315

- state: Initial state data

316

317

Returns:

318

type[Matcher]: Matcher class for specific event types

319

"""

320

```

321

322

Usage example:

323

324

```python

325

import nonebot

326

from nonebot import on_type

327

from nonebot.adapters import Bot, Event

328

from nonebot.adapters.console import MessageEvent as ConsoleMessageEvent

329

330

# Handle specific event type

331

console_messages = on_type(ConsoleMessageEvent)

332

333

@console_messages.handle()

334

async def handle_console_message(bot: Bot, event: ConsoleMessageEvent):

335

print(f"Console message: {event.get_plaintext()}")

336

337

# Handle multiple event types

338

from nonebot.adapters.console import NoticeEvent as ConsoleNoticeEvent

339

340

multi_type_handler = on_type((ConsoleMessageEvent, ConsoleNoticeEvent))

341

342

@multi_type_handler.handle()

343

async def handle_multiple_types(bot: Bot, event: Event):

344

if isinstance(event, ConsoleMessageEvent):

345

await bot.send(event, "Received console message")

346

elif isinstance(event, ConsoleNoticeEvent):

347

print("Received console notice")

348

```

349

350

## Types

351

352

### Core Types

353

354

```python { .api }

355

T_State = dict[Any, Any]

356

T_Handler = _DependentCallable[Any]

357

358

class Matcher:

359

"""Event matcher class for handling events."""

360

361

def handle(self) -> Callable[[T_Handler], T_Handler]:

362

"""Register primary handler."""

363

364

def got(self, key: str, prompt: Optional[Union[str, Message, MessageSegment, MessageTemplate]] = None) -> Callable[[T_Handler], T_Handler]:

365

"""Register handler for getting argument."""

366

367

def send(self, message: Union[str, Message, MessageSegment, MessageTemplate]) -> Callable[[T_Handler], T_Handler]:

368

"""Send message and continue."""

369

370

def pause(self, prompt: Optional[Union[str, Message, MessageSegment, MessageTemplate]] = None) -> Callable[[T_Handler], T_Handler]:

371

"""Pause execution and wait for next message."""

372

373

def reject(self, prompt: Optional[Union[str, Message, MessageSegment, MessageTemplate]] = None) -> Callable[[T_Handler], T_Handler]:

374

"""Reject current input and retry."""

375

376

def finish(self, message: Optional[Union[str, Message, MessageSegment, MessageTemplate]] = None) -> Callable[[T_Handler], T_Handler]:

377

"""Send message and finish execution."""

378

```

379

380

### Permission Types

381

382

```python { .api }

383

class Permission:

384

"""Permission checker for handlers."""

385

386

class User:

387

"""User-based permission checker."""

388

```

389

390

### Rule Types

391

392

```python { .api }

393

class Rule:

394

"""Rule for matching events."""

395

```