botrs 0.2.8

A Rust QQ Bot framework based on QQ Guild Bot API
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
# EventHandler API Reference

The `EventHandler` trait defines how your bot responds to events from the QQ Guild gateway. You implement this trait to handle messages, guild changes, member updates, and other events.

## Overview

```rust
use botrs::{Context, EventHandler};

#[async_trait::async_trait]
pub trait EventHandler: Send + Sync {
    // Event handler methods...
}
```

All event handler methods are optional - you only need to implement the events your bot cares about. Each method receives a `Context` parameter providing access to the API client and authentication token.

## Core Events

### `ready`

Called when the bot successfully connects and is ready to receive events.

```rust
async fn ready(&self, ctx: Context, ready: Ready) {}
```

#### Parameters

- `ctx`: Context containing API client and token
- `ready`: Information about the bot user and session

#### Example

```rust
async fn ready(&self, _ctx: Context, ready: Ready) {
    println!("Bot is ready! Logged in as: {}", ready.user.username);
    println!("Session ID: {}", ready.session_id);
    println!("Connected to {} guilds", ready.guilds.len());
}
```

### `error`

Called when an error occurs during event processing.

```rust
async fn error(&self, error: BotError) {}
```

#### Parameters

- `error`: The error that occurred

#### Example

```rust
async fn error(&self, error: BotError) {
    eprintln!("Event handler error: {}", error);
    
    match error {
        BotError::Network(_) => {
            // Handle network errors
        }
        BotError::RateLimited(info) => {
            println!("Rate limited for {} seconds", info.retry_after);
        }
        _ => {}
    }
}
```

## Message Events

### `message_create`

Called when a message is created that mentions your bot (@mentions in guild channels).

```rust
async fn message_create(&self, ctx: Context, message: Message) {}
```

#### Parameters

- `ctx`: Context for API access
- `message`: The message that was created

#### Example

```rust
async fn message_create(&self, ctx: Context, message: Message) {
    // Ignore bot messages
    if message.is_from_bot() {
        return;
    }
    
    let content = match &message.content {
        Some(content) => content,
        None => return,
    };
    
    if content.starts_with("!echo ") {
        let echo_text = &content[6..];
        let _ = message.reply(&ctx.api, &ctx.token, echo_text).await;
    }
}
```

### `direct_message_create`

Called when a direct message is created.

```rust
async fn direct_message_create(&self, ctx: Context, message: DirectMessage) {}
```

#### Parameters

- `ctx`: Context for API access
- `message`: The direct message

#### Example

```rust
async fn direct_message_create(&self, ctx: Context, message: DirectMessage) {
    if let Some(content) = &message.content {
        println!("Direct message from {}: {}", 
                 message.author.as_ref()
                     .and_then(|a| a.username.as_deref())
                     .unwrap_or("Unknown"), 
                 content);
        
        // Echo back the message
        let _ = message.reply(&ctx.api, &ctx.token, &format!("You said: {}", content)).await;
    }
}
```

### `group_message_create`

Called when a group message is created.

```rust
async fn group_message_create(&self, ctx: Context, message: GroupMessage) {}
```

#### Parameters

- `ctx`: Context for API access
- `message`: The group message

#### Example

```rust
async fn group_message_create(&self, ctx: Context, message: GroupMessage) {
    if let Some(content) = &message.content {
        if content == "!groupinfo" {
            let info = format!("Group ID: {}", message.group_openid.as_deref().unwrap_or("Unknown"));
            let _ = message.reply(&ctx.api, &ctx.token, &info).await;
        }
    }
}
```

### `c2c_message_create`

Called when a C2C (client-to-client) message is created.

```rust
async fn c2c_message_create(&self, ctx: Context, message: C2CMessage) {}
```

#### Parameters

- `ctx`: Context for API access
- `message`: The C2C message

#### Example

```rust
async fn c2c_message_create(&self, ctx: Context, message: C2CMessage) {
    if let Some(content) = &message.content {
        println!("C2C message: {}", content);
        // Handle private conversation messages
    }
}
```

### `message_delete`

Called when a message is deleted.

```rust
async fn message_delete(&self, ctx: Context, message: Message) {}
```

#### Parameters

- `ctx`: Context for API access
- `message`: Information about the deleted message

#### Example

```rust
async fn message_delete(&self, _ctx: Context, message: Message) {
    println!("Message deleted in channel {}", 
             message.channel_id.as_deref().unwrap_or("Unknown"));
}
```

## Guild Events

### `guild_create`

Called when the bot joins a guild or when a guild becomes available.

```rust
async fn guild_create(&self, ctx: Context, guild: Guild) {}
```

#### Parameters

- `ctx`: Context for API access
- `guild`: The guild information

#### Example

```rust
async fn guild_create(&self, _ctx: Context, guild: Guild) {
    println!("Joined guild: {} (ID: {})", 
             guild.name.as_deref().unwrap_or("Unknown"),
             guild.id.as_deref().unwrap_or("Unknown"));
}
```

### `guild_update`

Called when a guild is updated.

```rust
async fn guild_update(&self, ctx: Context, guild: Guild) {}
```

### `guild_delete`

Called when the bot leaves a guild or when a guild becomes unavailable.

```rust
async fn guild_delete(&self, ctx: Context, guild: Guild) {}
```

## Channel Events

### `channel_create`

Called when a channel is created.

```rust
async fn channel_create(&self, ctx: Context, channel: Channel) {}
```

#### Example

```rust
async fn channel_create(&self, _ctx: Context, channel: Channel) {
    println!("New channel created: {} (Type: {:?})", 
             channel.name.as_deref().unwrap_or("Unnamed"),
             channel.type_);
}
```

### `channel_update`

Called when a channel is updated.

```rust
async fn channel_update(&self, ctx: Context, channel: Channel) {}
```

### `channel_delete`

Called when a channel is deleted.

```rust
async fn channel_delete(&self, ctx: Context, channel: Channel) {}
```

## Member Events

### `guild_member_add`

Called when a member joins a guild.

```rust
async fn guild_member_add(&self, ctx: Context, member: Member) {}
```

#### Example

```rust
async fn guild_member_add(&self, ctx: Context, member: Member) {
    if let Some(user) = &member.user {
        println!("New member joined: {}", 
                 user.username.as_deref().unwrap_or("Unknown"));
        
        // Send welcome message to a specific channel
        if let Some(welcome_channel) = get_welcome_channel() {
            let welcome_msg = format!("Welcome to the server, {}!", 
                                    user.username.as_deref().unwrap_or("friend"));
            let params = MessageParams::new_text(&welcome_msg);
            let _ = ctx.api.post_message_with_params(&ctx.token, &welcome_channel, params).await;
        }
    }
}
```

### `guild_member_update`

Called when a guild member is updated.

```rust
async fn guild_member_update(&self, ctx: Context, member: Member) {}
```

### `guild_member_remove`

Called when a member leaves a guild.

```rust
async fn guild_member_remove(&self, ctx: Context, member: Member) {}
```

## Audit Events

### `message_audit_pass`

Called when a message passes audit review.

```rust
async fn message_audit_pass(&self, ctx: Context, audit: MessageAudit) {}
```

### `message_audit_reject`

Called when a message is rejected by audit review.

```rust
async fn message_audit_reject(&self, ctx: Context, audit: MessageAudit) {}
```

## Management Events

### Friend Management

```rust
async fn friend_add(&self, ctx: Context, event: C2CManageEvent) {}
async fn friend_del(&self, ctx: Context, event: C2CManageEvent) {}
async fn c2c_msg_reject(&self, ctx: Context, event: C2CManageEvent) {}
async fn c2c_msg_receive(&self, ctx: Context, event: C2CManageEvent) {}
```

### Group Management

```rust
async fn group_add_robot(&self, ctx: Context, event: GroupManageEvent) {}
async fn group_del_robot(&self, ctx: Context, event: GroupManageEvent) {}
async fn group_msg_reject(&self, ctx: Context, event: GroupManageEvent) {}
async fn group_msg_receive(&self, ctx: Context, event: GroupManageEvent) {}
```

## Implementation Examples

### Basic Event Handler

```rust
use botrs::{Context, EventHandler, Message, Ready};

struct MyBot;

#[async_trait::async_trait]
impl EventHandler for MyBot {
    async fn ready(&self, _ctx: Context, ready: Ready) {
        println!("Bot {} is ready!", ready.user.username);
    }
    
    async fn message_create(&self, ctx: Context, message: Message) {
        if message.is_from_bot() {
            return;
        }
        
        if let Some(content) = &message.content {
            match content.as_str() {
                "!ping" => {
                    let _ = message.reply(&ctx.api, &ctx.token, "Pong!").await;
                }
                "!help" => {
                    let help_text = "Available commands: !ping, !help";
                    let _ = message.reply(&ctx.api, &ctx.token, help_text).await;
                }
                _ => {}
            }
        }
    }
}
```

### Advanced Event Handler with State

```rust
use std::sync::Arc;
use tokio::sync::RwLock;
use std::collections::HashMap;

struct StatefulBot {
    user_data: Arc<RwLock<HashMap<String, UserData>>>,
}

struct UserData {
    message_count: u64,
    last_seen: chrono::DateTime<chrono::Utc>,
}

#[async_trait::async_trait]
impl EventHandler for StatefulBot {
    async fn message_create(&self, ctx: Context, message: Message) {
        if let Some(author) = &message.author {
            if let Some(user_id) = &author.id {
                let mut user_data = self.user_data.write().await;
                let entry = user_data.entry(user_id.clone()).or_insert(UserData {
                    message_count: 0,
                    last_seen: chrono::Utc::now(),
                });
                
                entry.message_count += 1;
                entry.last_seen = chrono::Utc::now();
                
                if let Some(content) = &message.content {
                    if content == "!stats" {
                        let stats = format!("You have sent {} messages", entry.message_count);
                        let _ = message.reply(&ctx.api, &ctx.token, &stats).await;
                    }
                }
            }
        }
    }
}
```

### Error Handling

```rust
#[async_trait::async_trait]
impl EventHandler for MyBot {
    async fn message_create(&self, ctx: Context, message: Message) {
        if let Some(content) = &message.content {
            if content == "!error_test" {
                match message.reply(&ctx.api, &ctx.token, "Test reply").await {
                    Ok(_) => println!("Reply sent successfully"),
                    Err(e) => eprintln!("Failed to send reply: {}", e),
                }
            }
        }
    }
    
    async fn error(&self, error: BotError) {
        match error {
            BotError::RateLimited(info) => {
                println!("Rate limited for {} seconds", info.retry_after);
            }
            BotError::Network(e) => {
                eprintln!("Network error: {}", e);
            }
            _ => {
                eprintln!("Unexpected error: {}", error);
            }
        }
    }
}
```

## Best Practices

### Performance

- Keep event handlers lightweight - offload heavy work to background tasks
- Use `tokio::spawn` for CPU-intensive operations
- Avoid blocking operations in event handlers

```rust
async fn message_create(&self, ctx: Context, message: Message) {
    if let Some(content) = &message.content {
        if content.starts_with("!heavy_task") {
            // Spawn background task for heavy processing
            let api = ctx.api.clone();
            let token = ctx.token.clone();
            let channel_id = message.channel_id.clone();
            
            tokio::spawn(async move {
                // Heavy processing here
                let result = perform_heavy_computation().await;
                
                let params = MessageParams::new_text(&result);
                if let Some(channel) = channel_id {
                    let _ = api.post_message_with_params(&token, &channel, params).await;
                }
            });
        }
    }
}
```

### Error Recovery

- Always handle errors gracefully
- Log errors for debugging
- Provide fallback responses when possible

```rust
async fn message_create(&self, ctx: Context, message: Message) {
    match self.process_message(&ctx, &message).await {
        Ok(_) => {}
        Err(e) => {
            eprintln!("Error processing message: {}", e);
            
            // Send error message to user
            let error_msg = "Sorry, something went wrong processing your request.";
            let _ = message.reply(&ctx.api, &ctx.token, error_msg).await;
        }
    }
}
```

## See Also

- [`Context`]./context.md - API access in event handlers
- [`Client`]./client.md - Main bot client
- [`Message Types`]./models/messages.md - Message data structures
- [`Error Types`]./error-types.md - Error handling