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
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
//! Main client implementation for the QQ Guild Bot API.
//!
//! This module provides the main `Client` struct that serves as the entry point
//! for bot applications, handling connections, events, and API interactions.
use crate::api::BotApi;
use crate::audio::{Audio, PublicAudio};
use crate::error::{BotError, Result};
use crate::forum::{OpenThread, Thread};
use crate::gateway::Gateway;
use crate::http::HttpClient;
use crate::intents::Intents;
use crate::interaction::Interaction;
use crate::manage::{C2CManageEvent, GroupManageEvent};
use crate::models::api::AudioAction;
use crate::models::channel::{ChannelSubType, ChannelType};
use crate::models::gateway::GatewayEvent;
use crate::models::guild::{GuildRole, GuildRoles, Member as GuildMember};
use crate::models::*;
use crate::reaction::Reaction;
use crate::token::Token;
use std::sync::Arc;
use tokio::sync::mpsc;
use tracing::{debug, error, info};
/// Event handler trait for processing gateway events.
#[async_trait::async_trait]
pub trait EventHandler: Send + Sync {
/// Called when the bot is ready and connected.
async fn ready(&self, _ctx: Context, _ready: Ready) {}
/// Called when the bot session has resumed.
async fn resumed(&self, _ctx: Context) {}
/// Called when a message is created (@ mentions).
async fn message_create(&self, _ctx: Context, _message: Message) {}
/// Called when a direct message is created.
async fn direct_message_create(&self, _ctx: Context, _message: DirectMessage) {}
/// Called when a direct message is deleted.
async fn direct_message_delete(&self, _ctx: Context, _message: DirectMessage) {}
/// Called when a group message is created.
async fn group_message_create(&self, _ctx: Context, _message: GroupMessage) {}
/// Called when a C2C message is created.
async fn c2c_message_create(&self, _ctx: Context, _message: C2CMessage) {}
/// Called when a message is deleted.
async fn message_delete(&self, _ctx: Context, _message: Message) {}
/// Called when a reaction is added to a message.
async fn message_reaction_add(&self, _ctx: Context, _reaction: Reaction) {}
/// Called when a reaction is removed from a message.
async fn message_reaction_remove(&self, _ctx: Context, _reaction: Reaction) {}
/// Called when an interaction event is created.
async fn interaction_create(&self, _ctx: Context, _interaction: Interaction) {}
/// Called when audio starts.
async fn audio_start(&self, _ctx: Context, _audio: Audio) {}
/// Called when audio finishes.
async fn audio_finish(&self, _ctx: Context, _audio: Audio) {}
/// Called when microphone is turned on.
async fn on_mic(&self, _ctx: Context, _audio: Audio) {}
/// Called when microphone is turned off.
async fn off_mic(&self, _ctx: Context, _audio: Audio) {}
/// Called when a guild is created (bot joins).
async fn guild_create(&self, _ctx: Context, _guild: Guild) {}
/// Called when a guild is updated.
async fn guild_update(&self, _ctx: Context, _guild: Guild) {}
/// Called when a guild is deleted (bot leaves).
async fn guild_delete(&self, _ctx: Context, _guild: Guild) {}
/// Called when a channel is created.
async fn channel_create(&self, _ctx: Context, _channel: Channel) {}
/// Called when a channel is updated.
async fn channel_update(&self, _ctx: Context, _channel: Channel) {}
/// Called when a channel is deleted.
async fn channel_delete(&self, _ctx: Context, _channel: Channel) {}
/// Called when a guild member is added.
async fn guild_member_add(&self, _ctx: Context, _member: Member) {}
/// Called when a guild member is updated.
async fn guild_member_update(&self, _ctx: Context, _member: Member) {}
/// Called when a guild member is removed.
async fn guild_member_remove(&self, _ctx: Context, _member: Member) {}
/// Called when a message audit passes.
async fn message_audit_pass(&self, _ctx: Context, _audit: MessageAudit) {}
/// Called when a message audit is rejected.
async fn message_audit_reject(&self, _ctx: Context, _audit: MessageAudit) {}
/// Called when a friend is added.
async fn friend_add(&self, _ctx: Context, _event: C2CManageEvent) {}
/// Called when a friend is deleted.
async fn friend_del(&self, _ctx: Context, _event: C2CManageEvent) {}
/// Called when C2C message is rejected.
async fn c2c_msg_reject(&self, _ctx: Context, _event: C2CManageEvent) {}
/// Called when C2C message is received.
async fn c2c_msg_receive(&self, _ctx: Context, _event: C2CManageEvent) {}
/// Called when robot is added to group.
async fn group_add_robot(&self, _ctx: Context, _event: GroupManageEvent) {}
/// Called when robot is deleted from group.
async fn group_del_robot(&self, _ctx: Context, _event: GroupManageEvent) {}
/// Called when group message is rejected.
async fn group_msg_reject(&self, _ctx: Context, _event: GroupManageEvent) {}
/// Called when group message is received.
async fn group_msg_receive(&self, _ctx: Context, _event: GroupManageEvent) {}
/// Called when a user enters an audio or live channel.
async fn audio_or_live_channel_member_enter(&self, _ctx: Context, _audio: PublicAudio) {}
/// Called when a user exits an audio or live channel.
async fn audio_or_live_channel_member_exit(&self, _ctx: Context, _audio: PublicAudio) {}
/// Called when a forum thread is created.
async fn forum_thread_create(&self, _ctx: Context, _thread: Thread) {}
/// Called when a forum thread is updated.
async fn forum_thread_update(&self, _ctx: Context, _thread: Thread) {}
/// Called when a forum thread is deleted.
async fn forum_thread_delete(&self, _ctx: Context, _thread: Thread) {}
/// Called when a forum post is created.
async fn forum_post_create(&self, _ctx: Context, _payload: serde_json::Value) {}
/// Called when a forum post is deleted.
async fn forum_post_delete(&self, _ctx: Context, _payload: serde_json::Value) {}
/// Called when a forum reply is created.
async fn forum_reply_create(&self, _ctx: Context, _payload: serde_json::Value) {}
/// Called when a forum reply is deleted.
async fn forum_reply_delete(&self, _ctx: Context, _payload: serde_json::Value) {}
/// Called when a forum publish audit result arrives.
async fn forum_publish_audit_result(&self, _ctx: Context, _payload: serde_json::Value) {}
/// Called when an open forum thread is created.
async fn open_forum_thread_create(&self, _ctx: Context, _thread: OpenThread) {}
/// Called when an open forum thread is updated.
async fn open_forum_thread_update(&self, _ctx: Context, _thread: OpenThread) {}
/// Called when an open forum thread is deleted.
async fn open_forum_thread_delete(&self, _ctx: Context, _thread: OpenThread) {}
/// Called when an open forum post is created.
async fn open_forum_post_create(&self, _ctx: Context, _thread: OpenThread) {}
/// Called when an open forum post is deleted.
async fn open_forum_post_delete(&self, _ctx: Context, _thread: OpenThread) {}
/// Called when an open forum reply is created.
async fn open_forum_reply_create(&self, _ctx: Context, _thread: OpenThread) {}
/// Called when an open forum reply is deleted.
async fn open_forum_reply_delete(&self, _ctx: Context, _thread: OpenThread) {}
/// Called for any unhandled events.
async fn unknown_event(&self, _ctx: Context, _event: GatewayEvent) {}
/// Called when an error occurs during event processing.
async fn error(&self, _error: BotError) {
error!("Event handler error: {}", _error);
}
}
/// Context passed to event handlers containing API access and bot information.
#[derive(Clone)]
pub struct Context {
/// API client for making requests
pub api: Arc<BotApi>,
/// Authentication token
pub token: Token,
/// Bot information
pub bot_info: Option<BotInfo>,
}
impl Context {
/// Creates a new context.
pub fn new(api: Arc<BotApi>, token: Token) -> Self {
Self {
api,
token,
bot_info: None,
}
}
/// Sets the bot information.
pub fn with_bot_info(mut self, bot_info: BotInfo) -> Self {
self.bot_info = Some(bot_info);
self
}
/// Sends a message to a channel.
///
/// # Arguments
///
/// * `channel_id` - The channel ID to send the message to
/// * `content` - Message content
///
/// # Returns
///
/// The sent message response.
pub async fn send_message(&self, channel_id: &str, content: &str) -> Result<MessageResponse> {
let params = crate::models::message::MessageParams::new_text(content);
self.api
.post_message_with_params(&self.token, channel_id, params)
.await
}
/// Sends a message with embed to a channel.
///
/// # Arguments
///
/// * `channel_id` - The channel ID to send the message to
/// * `content` - Optional message content
/// * `embed` - Embed to send
///
/// # Returns
///
/// The sent message response.
pub async fn send_message_with_embed(
&self,
channel_id: &str,
content: Option<&str>,
embed: &Embed,
) -> Result<MessageResponse> {
let params = crate::models::message::MessageParams {
content: content.map(|s| s.to_string()),
embed: Some(embed.clone()),
..Default::default()
};
self.api
.post_message_with_params(&self.token, channel_id, params)
.await
}
/// Sends a reply to a message.
///
/// # Arguments
///
/// * `channel_id` - The channel ID to send the reply to
/// * `content` - Reply content
/// * `message_id` - The message ID to reply to
///
/// # Returns
///
/// The sent message response.
pub async fn reply_message(
&self,
channel_id: &str,
content: &str,
message_id: &str,
) -> Result<MessageResponse> {
let reference = Reference {
message_id: Some(message_id.to_string()),
ignore_get_message_error: Some(true),
};
let params = crate::models::message::MessageParams {
content: Some(content.to_string()),
message_reference: Some(reference),
..Default::default()
};
self.api
.post_message_with_params(&self.token, channel_id, params)
.await
}
/// Sends a group message.
///
/// # Arguments
///
/// * `group_openid` - The group OpenID
/// * `content` - Message content
///
/// # Returns
///
/// The sent group message response.
pub async fn send_group_message(
&self,
group_openid: &str,
content: &str,
) -> Result<MessageResponse> {
let params = crate::models::message::GroupMessageParams::new_text(content);
self.api
.post_group_message_with_params(&self.token, group_openid, params)
.await
}
/// Sends a C2C (client-to-client) message.
///
/// # Arguments
///
/// * `openid` - The user's OpenID
/// * `content` - Message content
///
/// # Returns
///
/// The sent C2C message response.
pub async fn send_c2c_message(&self, openid: &str, content: &str) -> Result<MessageResponse> {
let params = crate::models::message::C2CMessageParams::new_text(content);
self.api
.post_c2c_message_with_params(&self.token, openid, params)
.await
}
/// Gets guild information.
///
/// # Arguments
///
/// * `guild_id` - The guild ID
///
/// # Returns
///
/// Guild information.
pub async fn get_guild(&self, guild_id: &str) -> Result<Guild> {
self.api.get_guild(&self.token, guild_id).await
}
/// Gets channel information.
///
/// # Arguments
///
/// * `channel_id` - The channel ID
///
/// # Returns
///
/// Channel information.
pub async fn get_channel(&self, channel_id: &str) -> Result<Channel> {
self.api.get_channel(&self.token, channel_id).await
}
/// Gets message information.
///
/// # Arguments
///
/// * `channel_id` - The channel ID
/// * `message_id` - The message ID
///
/// # Returns
///
/// The message.
pub async fn get_message(&self, channel_id: &str, message_id: &str) -> Result<Message> {
self.api
.get_message(&self.token, channel_id, message_id)
.await
}
/// Recalls (deletes) a message.
///
/// # Arguments
///
/// * `channel_id` - The channel ID
/// * `message_id` - The message ID to recall
/// * `hide_tip` - Whether to hide the recall tip
///
/// # Returns
///
/// Result indicating success or failure.
pub async fn recall_message(
&self,
channel_id: &str,
message_id: &str,
hide_tip: bool,
) -> Result<()> {
self.api
.recall_message(&self.token, channel_id, message_id, Some(hide_tip))
.await
}
/// Adds a reaction to a message.
///
/// # Arguments
///
/// * `channel_id` - The channel ID
/// * `message_id` - The message ID
/// * `emoji_type` - The emoji type (1 for system emoji, 2 for custom emoji)
/// * `emoji_id` - The emoji ID
///
/// # Returns
///
/// Result indicating success or failure.
pub async fn add_reaction(
&self,
channel_id: &str,
message_id: &str,
emoji_type: u32,
emoji_id: &str,
) -> Result<()> {
self.api
.put_reaction(&self.token, channel_id, message_id, emoji_type, emoji_id)
.await
}
/// Removes a reaction from a message.
///
/// # Arguments
///
/// * `channel_id` - The channel ID
/// * `message_id` - The message ID
/// * `emoji_type` - The emoji type (1 for system emoji, 2 for custom emoji)
/// * `emoji_id` - The emoji ID
///
/// # Returns
///
/// Result indicating success or failure.
pub async fn remove_reaction(
&self,
channel_id: &str,
message_id: &str,
emoji_type: u32,
emoji_id: &str,
) -> Result<()> {
self.api
.delete_reaction(&self.token, channel_id, message_id, emoji_type, emoji_id)
.await
}
/// Gets the current user's guilds.
///
/// # Arguments
///
/// * `guild_id` - Optional starting guild ID
/// * `limit` - Number of guilds to return (1-100, default 100)
/// * `desc` - Whether to return results in descending order
///
/// # Returns
///
/// List of guilds.
pub async fn get_guilds(
&self,
guild_id: Option<&str>,
limit: Option<u32>,
desc: Option<bool>,
) -> Result<Vec<Guild>> {
self.api
.get_guilds(&self.token, guild_id, limit, desc)
.await
}
/// Gets channels in a guild.
///
/// # Arguments
///
/// * `guild_id` - The guild ID
///
/// # Returns
///
/// List of channels.
pub async fn get_channels(&self, guild_id: &str) -> Result<Vec<Channel>> {
self.api.get_channels(&self.token, guild_id).await
}
/// Creates a new channel in a guild.
///
/// # Arguments
///
/// * `guild_id` - The guild ID
/// * `name` - Channel name
/// * `channel_type` - Channel type
/// * `sub_type` - Channel sub type
/// * `position` - Channel position
/// * `parent_id` - Parent channel ID for category channels
/// * `private_type` - Private type (0=public, 1=private, 2=voice private)
/// * `private_user_ids` - List of user IDs for private channels
/// * `speak_permission` - Speak permission (0=invalid, 1=all members, 2=members with role)
/// * `application_id` - Application ID for application channels
///
/// # Returns
///
/// The created channel.
pub async fn create_channel(
&self,
guild_id: &str,
name: &str,
channel_type: ChannelType,
sub_type: ChannelSubType,
position: Option<u32>,
parent_id: Option<&str>,
private_type: Option<u32>,
private_user_ids: Option<Vec<String>>,
speak_permission: Option<u32>,
application_id: Option<&str>,
) -> Result<Channel> {
self.api
.create_channel(
&self.token,
guild_id,
name,
channel_type,
sub_type,
position,
parent_id,
private_type,
private_user_ids,
speak_permission,
application_id,
)
.await
}
/// Gets guild roles.
///
/// # Arguments
///
/// * `guild_id` - The guild ID
///
/// # Returns
///
/// List of guild roles.
pub async fn get_guild_roles(&self, guild_id: &str) -> Result<GuildRoles> {
self.api.get_guild_roles(&self.token, guild_id).await
}
/// Creates a new guild role.
///
/// # Arguments
///
/// * `guild_id` - The guild ID
/// * `name` - Role name
/// * `color` - Role color (ARGB hex value converted to decimal)
/// * `hoist` - Whether to display separately in member list (0=no, 1=yes)
///
/// # Returns
///
/// The created guild role.
pub async fn create_guild_role(
&self,
guild_id: &str,
name: Option<&str>,
color: Option<u32>,
hoist: Option<bool>,
) -> Result<GuildRole> {
self.api
.create_guild_role(&self.token, guild_id, name, color, hoist)
.await
}
/// Updates a guild role.
///
/// # Arguments
///
/// * `guild_id` - The guild ID
/// * `role_id` - The role ID
/// * `name` - Role name
/// * `color` - Role color (ARGB hex value converted to decimal)
/// * `hoist` - Whether to display separately in member list (0=no, 1=yes)
///
/// # Returns
///
/// The updated guild role.
pub async fn update_guild_role(
&self,
guild_id: &str,
role_id: &str,
name: Option<&str>,
color: Option<u32>,
hoist: Option<bool>,
) -> Result<GuildRole> {
self.api
.update_guild_role(&self.token, guild_id, role_id, name, color, hoist)
.await
}
/// Deletes a guild role.
///
/// # Arguments
///
/// * `guild_id` - The guild ID
/// * `role_id` - The role ID
///
/// # Returns
///
/// Result indicating success or failure.
pub async fn delete_guild_role(&self, guild_id: &str, role_id: &str) -> Result<()> {
self.api
.delete_guild_role(&self.token, guild_id, role_id)
.await
}
/// Adds a role to a guild member.
///
/// # Arguments
///
/// * `guild_id` - The guild ID
/// * `user_id` - The user ID
/// * `role_id` - The role ID
/// * `channel_id` - Optional channel ID for channel-specific roles
///
/// # Returns
///
/// Result indicating success or failure.
pub async fn add_guild_role_member(
&self,
guild_id: &str,
user_id: &str,
role_id: &str,
channel_id: Option<&str>,
) -> Result<()> {
self.api
.create_guild_role_member(&self.token, guild_id, role_id, user_id, channel_id)
.await
}
/// Removes a role from a guild member.
///
/// # Arguments
///
/// * `guild_id` - The guild ID
/// * `user_id` - The user ID
/// * `role_id` - The role ID
/// * `channel_id` - Optional channel ID for channel-specific roles
///
/// # Returns
///
/// Result indicating success or failure.
pub async fn remove_guild_role_member(
&self,
guild_id: &str,
user_id: &str,
role_id: &str,
channel_id: Option<&str>,
) -> Result<()> {
self.api
.delete_guild_role_member(&self.token, guild_id, role_id, user_id, channel_id)
.await
}
/// Gets guild member information.
///
/// # Arguments
///
/// * `guild_id` - The guild ID
/// * `user_id` - The user ID
///
/// # Returns
///
/// Member information.
pub async fn get_guild_member(&self, guild_id: &str, user_id: &str) -> Result<GuildMember> {
self.api
.get_guild_member(&self.token, guild_id, user_id)
.await
}
/// Gets guild members list.
///
/// # Arguments
///
/// * `guild_id` - The guild ID
/// * `after` - Optional user ID to get members after
/// * `limit` - Number of members to return (1-400, default 1)
///
/// # Returns
///
/// List of members.
pub async fn get_guild_members(
&self,
guild_id: &str,
after: Option<&str>,
limit: Option<u32>,
) -> Result<Vec<GuildMember>> {
self.api
.get_guild_members(&self.token, guild_id, after, limit)
.await
}
/// Kicks a member from the guild.
///
/// # Arguments
///
/// * `guild_id` - The guild ID
/// * `user_id` - The user ID to kick
/// * `add_blacklist` - Whether to add user to blacklist
/// * `delete_history_msg_days` - Days of message history to delete (3, 7, 15, 30)
///
/// # Returns
///
/// Result indicating success or failure.
pub async fn kick_member(
&self,
guild_id: &str,
user_id: &str,
add_blacklist: Option<bool>,
delete_history_msg_days: Option<i32>,
) -> Result<()> {
self.api
.delete_member(
&self.token,
guild_id,
user_id,
add_blacklist,
delete_history_msg_days,
)
.await
}
/// Updates audio control in a channel.
///
/// # Arguments
///
/// * `channel_id` - The channel ID
/// * `audio_control` - Audio control data
///
/// # Returns
///
/// Result indicating success or failure.
pub async fn update_audio(&self, channel_id: &str, audio_control: &AudioAction) -> Result<()> {
self.api
.update_audio(&self.token, channel_id, audio_control)
.await
}
/// Turns on microphone in a channel.
///
/// # Arguments
///
/// * `channel_id` - The channel ID
///
/// # Returns
///
/// Result indicating success or failure.
pub async fn on_microphone(&self, channel_id: &str) -> Result<()> {
self.api.on_microphone(&self.token, channel_id).await
}
/// Turns off microphone in a channel.
///
/// # Arguments
///
/// * `channel_id` - The channel ID
///
/// # Returns
///
/// Result indicating success or failure.
pub async fn off_microphone(&self, channel_id: &str) -> Result<()> {
self.api.off_microphone(&self.token, channel_id).await
}
/// Mutes all members in a guild.
///
/// # Arguments
///
/// * `guild_id` - The guild ID
/// * `mute_end_timestamp` - Optional end timestamp
/// * `mute_seconds` - Optional duration in seconds
///
/// # Returns
///
/// Result indicating success or failure.
pub async fn mute_all(
&self,
guild_id: &str,
mute_end_timestamp: Option<&str>,
mute_seconds: Option<&str>,
) -> Result<()> {
self.api
.mute_all(&self.token, guild_id, mute_end_timestamp, mute_seconds)
.await
}
/// Cancels mute for all members in a guild.
///
/// # Arguments
///
/// * `guild_id` - The guild ID
///
/// # Returns
///
/// Result indicating success or failure.
pub async fn cancel_mute_all(&self, guild_id: &str) -> Result<()> {
self.api.cancel_mute_all(&self.token, guild_id).await
}
/// Mutes a specific member in a guild.
///
/// # Arguments
///
/// * `guild_id` - The guild ID
/// * `user_id` - The user ID to mute
/// * `mute_end_timestamp` - Optional end timestamp
/// * `mute_seconds` - Optional duration in seconds
///
/// # Returns
///
/// Result indicating success or failure.
pub async fn mute_member(
&self,
guild_id: &str,
user_id: &str,
mute_end_timestamp: Option<&str>,
mute_seconds: Option<&str>,
) -> Result<()> {
self.api
.mute_member(
&self.token,
guild_id,
user_id,
mute_end_timestamp,
mute_seconds,
)
.await
}
/// Pins a message.
///
/// # Arguments
///
/// * `channel_id` - The channel ID
/// * `message_id` - The message ID to pin
///
/// # Returns
///
/// Result indicating success or failure.
pub async fn pin_message(&self, channel_id: &str, message_id: &str) -> Result<()> {
let _ = self
.api
.put_pin(&self.token, channel_id, message_id)
.await?;
Ok(())
}
/// Unpins a message.
///
/// # Arguments
///
/// * `channel_id` - The channel ID
/// * `message_id` - The message ID to unpin
///
/// # Returns
///
/// Result indicating success or failure.
pub async fn unpin_message(&self, channel_id: &str, message_id: &str) -> Result<()> {
self.api
.delete_pin(&self.token, channel_id, message_id)
.await
}
/// Gets pinned messages in a channel.
///
/// # Arguments
///
/// * `channel_id` - The channel ID
///
/// # Returns
///
/// The pinned messages response.
pub async fn get_pins(&self, channel_id: &str) -> Result<serde_json::Value> {
self.api.get_pins(&self.token, channel_id).await
}
/// Gets channel permissions for a user.
///
/// # Arguments
///
/// * `channel_id` - The channel ID
/// * `user_id` - The user ID
///
/// # Returns
///
/// Channel permissions for the user.
pub async fn get_channel_user_permissions(
&self,
channel_id: &str,
user_id: &str,
) -> Result<ChannelPermissions> {
self.api
.get_channel_user_permissions(&self.token, channel_id, user_id)
.await
}
/// Gets channel permissions for a role.
///
/// # Arguments
///
/// * `channel_id` - The channel ID
/// * `role_id` - The role ID
///
/// # Returns
///
/// Channel permissions for the role.
pub async fn get_channel_role_permissions(
&self,
channel_id: &str,
role_id: &str,
) -> Result<ChannelPermissions> {
self.api
.get_channel_role_permissions(&self.token, channel_id, role_id)
.await
}
/// Updates a channel.
///
/// # Arguments
///
/// * `channel_id` - The channel ID
/// * `name` - Optional new name
/// * `position` - Optional new position
/// * `parent_id` - Optional new parent ID
/// * `private_type` - Optional new private type
/// * `speak_permission` - Optional new speak permission
///
/// # Returns
///
/// The updated channel.
pub async fn update_channel(
&self,
channel_id: &str,
name: Option<&str>,
position: Option<u32>,
parent_id: Option<&str>,
private_type: Option<u32>,
speak_permission: Option<u32>,
) -> Result<Channel> {
self.api
.update_channel(
&self.token,
channel_id,
name,
position,
parent_id,
private_type,
speak_permission,
)
.await
}
/// Deletes a channel.
///
/// # Arguments
///
/// * `channel_id` - The channel ID
///
/// # Returns
///
/// The deleted channel.
pub async fn delete_channel(&self, channel_id: &str) -> Result<Channel> {
self.api.delete_channel(&self.token, channel_id).await
}
/// Creates a DMS session.
///
/// # Arguments
///
/// * `recipient_id` - The recipient user ID
/// * `source_guild_id` - The source guild ID
///
/// # Returns
///
/// The created DMS session.
pub async fn create_dms(
&self,
recipient_id: &str,
source_guild_id: &str,
) -> Result<serde_json::Value> {
self.api
.create_dms(&self.token, recipient_id, source_guild_id)
.await
}
/// Sends a file to a group.
///
/// # Arguments
///
/// * `group_openid` - The group OpenID
/// * `file_type` - The file type (1=image, 2=video, 3=audio, 4=file)
/// * `url` - The file URL
/// * `srv_send_msg` - Whether to send as message
///
/// # Returns
///
/// The file upload response.
pub async fn post_group_file(
&self,
group_openid: &str,
file_type: u32,
url: &str,
srv_send_msg: Option<bool>,
) -> Result<serde_json::Value> {
self.api
.post_group_file(&self.token, group_openid, file_type, url, srv_send_msg)
.await
}
/// Sends a file to a C2C chat.
///
/// # Arguments
///
/// * `openid` - The user's OpenID
/// * `file_type` - The file type (1=image, 2=video, 3=audio, 4=file)
/// * `url` - The file URL
/// * `srv_send_msg` - Whether to send as message
///
/// # Returns
///
/// The file upload response.
pub async fn post_c2c_file(
&self,
openid: &str,
file_type: u32,
url: &str,
srv_send_msg: Option<bool>,
) -> Result<serde_json::Value> {
self.api
.post_c2c_file(&self.token, openid, file_type, url, srv_send_msg)
.await
}
}
/// Main client for the QQ Guild Bot API.
pub struct Client<H: EventHandler> {
/// Authentication token
token: Token,
/// Intent flags
intents: Intents,
/// HTTP client
http: HttpClient,
/// API client
api: Arc<BotApi>,
/// Event handler
handler: Arc<H>,
/// Whether to use sandbox environment
is_sandbox: bool,
/// Request timeout in seconds
timeout: u64,
}
impl<H: EventHandler + 'static> Client<H> {
/// Creates a new client.
///
/// # Arguments
///
/// * `token` - Authentication token
/// * `intents` - Intent flags for events to receive
/// * `handler` - Event handler implementation
/// * `is_sandbox` - Whether to use sandbox environment
///
/// # Examples
///
/// ```rust,no_run
/// use botrs::{Client, Token, Intents, EventHandler, Context};
/// use tracing::info;
///
/// struct MyHandler;
///
/// #[async_trait::async_trait]
/// impl EventHandler for MyHandler {
/// async fn message_create(&self, ctx: Context, message: botrs::Message) {
/// info!("Received message: {:?}", message.content);
/// }
/// }
///
/// #[tokio::main]
/// async fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let token = Token::new("app_id", "secret");
/// let intents = Intents::default();
/// let handler = MyHandler;
/// let client = Client::new(token, intents, handler, false)?;
/// Ok(())
/// }
/// ```
pub fn new(token: Token, intents: Intents, handler: H, is_sandbox: bool) -> Result<Self> {
let timeout = crate::DEFAULT_TIMEOUT;
let http = HttpClient::new(timeout, is_sandbox)?;
let api = Arc::new(BotApi::new(http.clone()));
Ok(Self {
token,
intents,
http,
api,
handler: Arc::new(handler),
is_sandbox,
timeout,
})
}
/// Creates a new client with custom configuration.
///
/// # Arguments
///
/// * `token` - Authentication token
/// * `intents` - Intent flags for events to receive
/// * `handler` - Event handler implementation
/// * `timeout` - Request timeout in seconds
/// * `is_sandbox` - Whether to use sandbox environment
///
/// # Returns
///
/// A new client instance.
pub fn with_config(
token: Token,
intents: Intents,
handler: H,
timeout: u64,
is_sandbox: bool,
) -> Result<Self> {
let http = HttpClient::new(timeout, is_sandbox)?;
let api = Arc::new(BotApi::new(http.clone()));
Ok(Self {
token,
intents,
http,
api,
handler: Arc::new(handler),
is_sandbox,
timeout,
})
}
/// Starts the bot and connects to the gateway.
///
/// This method will block until the bot is stopped or an error occurs.
///
/// # Returns
///
/// Result indicating success or failure.
///
/// # Examples
///
/// ```rust,no_run
/// use botrs::{Client, Token, Intents, EventHandler};
///
/// struct MyHandler;
///
/// #[async_trait::async_trait]
/// impl EventHandler for MyHandler {}
///
/// #[tokio::main]
/// async fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let token = Token::new("app_id", "secret");
/// let intents = Intents::default();
/// let handler = MyHandler;
/// let mut client = Client::new(token, intents, handler, false)?;
/// client.start().await?;
/// Ok(())
/// }
/// ```
pub async fn start(&mut self) -> Result<()> {
info!("Starting bot client");
// Validate token
self.token.validate()?;
// Get bot information
let bot_info = self.api.get_bot_info(&self.token).await?;
info!("Bot info: {} ({})", bot_info.username, bot_info.id);
// Get gateway information
let gateway_info = self.api.get_gateway(&self.token).await?;
info!("Gateway URL: {}", gateway_info.url);
// Create context
let ctx = Context::new(self.api.clone(), self.token.clone()).with_bot_info(bot_info);
// Set up event channel
let (event_sender, mut event_receiver) = mpsc::unbounded_channel();
// Create and connect gateway
let gateway = Gateway::new(
gateway_info.url,
self.token.clone(),
self.intents,
None, // TODO: Implement sharding
);
// Start gateway connection in a separate task with auto-reconnect
let gateway_task = {
let mut gateway_clone = gateway;
async move {
// Gateway now handles auto-reconnect internally
if let Err(e) = gateway_clone.connect(event_sender).await {
error!("Gateway connection failed permanently: {}", e);
}
}
};
tokio::spawn(gateway_task);
// Main event processing loop - continue running even if gateway disconnects
info!("Bot client started, waiting for events...");
while let Some(event) = event_receiver.recv().await {
if let Err(e) = self.handle_event(ctx.clone(), event).await {
self.handler.error(e).await;
}
}
info!("Bot client stopped");
Ok(())
}
/// Handles a gateway event by dispatching it to the appropriate handler method.
///
/// # Arguments
///
/// * `ctx` - Event context
/// * `event` - Gateway event to handle
///
/// # Returns
///
/// Result indicating success or failure.
async fn handle_event(&self, ctx: Context, event: GatewayEvent) -> Result<()> {
debug!("Handling event: {:?}", event.event_type);
let event_type = event.event_type.as_deref().map(str::to_ascii_uppercase);
match event_type.as_deref() {
Some("READY") => {
if let Some(data) = event.data {
match serde_json::from_value::<Ready>(data.clone()) {
Ok(ready) => {
info!("Bot is ready! Session ID: {}", ready.session_id);
self.handler.ready(ctx, ready).await;
}
Err(e) => {
error!("Failed to parse READY event: {}", e);
debug!(
"Raw event data: {}",
serde_json::to_string_pretty(&data).unwrap_or_default()
);
}
}
}
}
Some("RESUMED") => {
self.handler.resumed(ctx).await;
}
Some("AT_MESSAGE_CREATE") => {
if let Some(data) = event.data {
let event_id = event.id.unwrap_or_else(|| {
format!("AT_MESSAGE_CREATE_{}", event.sequence.unwrap_or(0))
});
let message = Message::from_data((*ctx.api).clone(), event_id, data);
self.handler.message_create(ctx, message).await;
}
}
Some("DIRECT_MESSAGE_CREATE") => {
if let Some(data) = event.data {
let event_id = event.id.unwrap_or_else(|| {
format!("DIRECT_MESSAGE_CREATE_{}", event.sequence.unwrap_or(0))
});
let message = DirectMessage::from_data((*ctx.api).clone(), event_id, data);
self.handler.direct_message_create(ctx, message).await;
}
}
Some("GROUP_AT_MESSAGE_CREATE") => {
if let Some(data) = event.data {
let event_id = event.id.unwrap_or_else(|| {
format!("GROUP_AT_MESSAGE_CREATE_{}", event.sequence.unwrap_or(0))
});
let message = GroupMessage::from_data((*ctx.api).clone(), event_id, data);
self.handler.group_message_create(ctx, message).await;
}
}
Some("C2C_MESSAGE_CREATE") => {
if let Some(data) = event.data {
let event_id = event.id.unwrap_or_else(|| {
format!("C2C_MESSAGE_CREATE_{}", event.sequence.unwrap_or(0))
});
let message = C2CMessage::from_data((*ctx.api).clone(), event_id, data);
self.handler.c2c_message_create(ctx, message).await;
}
}
Some("DIRECT_MESSAGE_DELETE") => {
if let Some(data) = event.data {
let event_id = event.id.unwrap_or_else(|| {
format!("DIRECT_MESSAGE_DELETE_{}", event.sequence.unwrap_or(0))
});
let message = DirectMessage::from_data((*ctx.api).clone(), event_id, data);
self.handler.direct_message_delete(ctx, message).await;
}
}
Some("PUBLIC_MESSAGE_DELETE") => {
if let Some(data) = event.data {
let event_id = event.id.unwrap_or_else(|| {
format!("PUBLIC_MESSAGE_DELETE_{}", event.sequence.unwrap_or(0))
});
let message = Message::from_data((*ctx.api).clone(), event_id, data);
self.handler.message_delete(ctx, message).await;
}
}
Some("MESSAGE_REACTION_ADD") => {
if let Some(data) = event.data {
let reaction = Reaction::new(ctx.api.as_ref().clone(), event.id, &data);
self.handler.message_reaction_add(ctx, reaction).await;
}
}
Some("MESSAGE_REACTION_REMOVE") => {
if let Some(data) = event.data {
let reaction = Reaction::new(ctx.api.as_ref().clone(), event.id, &data);
self.handler.message_reaction_remove(ctx, reaction).await;
}
}
Some("INTERACTION_CREATE") => {
if let Some(data) = event.data {
let interaction = Interaction::new(ctx.api.as_ref().clone(), event.id, &data);
self.handler.interaction_create(ctx, interaction).await;
}
}
Some("AUDIO_START") => {
if let Some(data) = event.data {
let audio_action = AudioAction {
guild_id: data
.get("guild_id")
.and_then(|v| v.as_str())
.map(String::from),
channel_id: data
.get("channel_id")
.and_then(|v| v.as_str())
.map(String::from),
audio_url: data
.get("audio_url")
.and_then(|v| v.as_str())
.map(String::from),
text: data.get("text").and_then(|v| v.as_str()).map(String::from),
};
let audio = Audio::new(ctx.api.as_ref().clone(), event.id, audio_action);
self.handler.audio_start(ctx, audio).await;
}
}
Some("AUDIO_FINISH") => {
if let Some(data) = event.data {
let audio_action = AudioAction {
guild_id: data
.get("guild_id")
.and_then(|v| v.as_str())
.map(String::from),
channel_id: data
.get("channel_id")
.and_then(|v| v.as_str())
.map(String::from),
audio_url: data
.get("audio_url")
.and_then(|v| v.as_str())
.map(String::from),
text: data.get("text").and_then(|v| v.as_str()).map(String::from),
};
let audio = Audio::new(ctx.api.as_ref().clone(), event.id, audio_action);
self.handler.audio_finish(ctx, audio).await;
}
}
Some("ON_MIC") => {
if let Some(data) = event.data {
let audio_action = AudioAction {
guild_id: data
.get("guild_id")
.and_then(|v| v.as_str())
.map(String::from),
channel_id: data
.get("channel_id")
.and_then(|v| v.as_str())
.map(String::from),
audio_url: data
.get("audio_url")
.and_then(|v| v.as_str())
.map(String::from),
text: data.get("text").and_then(|v| v.as_str()).map(String::from),
};
let audio = Audio::new(ctx.api.as_ref().clone(), event.id, audio_action);
self.handler.on_mic(ctx, audio).await;
}
}
Some("OFF_MIC") => {
if let Some(data) = event.data {
let audio_action = AudioAction {
guild_id: data
.get("guild_id")
.and_then(|v| v.as_str())
.map(String::from),
channel_id: data
.get("channel_id")
.and_then(|v| v.as_str())
.map(String::from),
audio_url: data
.get("audio_url")
.and_then(|v| v.as_str())
.map(String::from),
text: data.get("text").and_then(|v| v.as_str()).map(String::from),
};
let audio = Audio::new(ctx.api.as_ref().clone(), event.id, audio_action);
self.handler.off_mic(ctx, audio).await;
}
}
Some("GUILD_CREATE") => {
if let Some(data) = event.data {
let event_id = event
.id
.unwrap_or_else(|| format!("GUILD_CREATE_{}", event.sequence.unwrap_or(0)));
let guild = Guild::from_data((*ctx.api).clone(), event_id, data);
self.handler.guild_create(ctx, guild).await;
}
}
Some("GUILD_UPDATE") => {
if let Some(data) = event.data {
let event_id = event
.id
.unwrap_or_else(|| format!("GUILD_UPDATE_{}", event.sequence.unwrap_or(0)));
let guild = Guild::from_data((*ctx.api).clone(), event_id, data);
self.handler.guild_update(ctx, guild).await;
}
}
Some("GUILD_DELETE") => {
if let Some(data) = event.data {
let event_id = event
.id
.unwrap_or_else(|| format!("GUILD_DELETE_{}", event.sequence.unwrap_or(0)));
let guild = Guild::from_data((*ctx.api).clone(), event_id, data);
self.handler.guild_delete(ctx, guild).await;
}
}
Some("CHANNEL_CREATE") => {
if let Some(data) = event.data {
let event_id = event.id.unwrap_or_else(|| {
format!("CHANNEL_CREATE_{}", event.sequence.unwrap_or(0))
});
let channel = Channel::from_data((*ctx.api).clone(), event_id, data);
self.handler.channel_create(ctx, channel).await;
}
}
Some("CHANNEL_UPDATE") => {
if let Some(data) = event.data {
let event_id = event.id.unwrap_or_else(|| {
format!("CHANNEL_UPDATE_{}", event.sequence.unwrap_or(0))
});
let channel = Channel::from_data((*ctx.api).clone(), event_id, data);
self.handler.channel_update(ctx, channel).await;
}
}
Some("CHANNEL_DELETE") => {
if let Some(data) = event.data {
let event_id = event.id.unwrap_or_else(|| {
format!("CHANNEL_DELETE_{}", event.sequence.unwrap_or(0))
});
let channel = Channel::from_data((*ctx.api).clone(), event_id, data);
self.handler.channel_delete(ctx, channel).await;
}
}
Some("GUILD_MEMBER_ADD") => {
if let Some(data) = event.data {
match serde_json::from_value::<Member>(data.clone()) {
Ok(member) => {
self.handler.guild_member_add(ctx, member).await;
}
Err(e) => {
error!("Failed to parse GUILD_MEMBER_ADD event: {}", e);
debug!(
"Raw event data: {}",
serde_json::to_string_pretty(&data).unwrap_or_default()
);
}
}
}
}
Some("GUILD_MEMBER_UPDATE") => {
if let Some(data) = event.data {
match serde_json::from_value::<Member>(data.clone()) {
Ok(member) => {
self.handler.guild_member_update(ctx, member).await;
}
Err(e) => {
error!("Failed to parse GUILD_MEMBER_UPDATE event: {}", e);
debug!(
"Raw event data: {}",
serde_json::to_string_pretty(&data).unwrap_or_default()
);
}
}
}
}
Some("GUILD_MEMBER_REMOVE") => {
if let Some(data) = event.data {
match serde_json::from_value::<Member>(data.clone()) {
Ok(member) => {
self.handler.guild_member_remove(ctx, member).await;
}
Err(e) => {
error!("Failed to parse GUILD_MEMBER_REMOVE event: {}", e);
debug!(
"Raw event data: {}",
serde_json::to_string_pretty(&data).unwrap_or_default()
);
}
}
}
}
Some("MESSAGE_AUDIT_PASS") => {
if let Some(data) = event.data {
let event_id = event.id.unwrap_or_else(|| {
format!("MESSAGE_AUDIT_PASS_{}", event.sequence.unwrap_or(0))
});
let audit = MessageAudit::from_data((*ctx.api).clone(), event_id, data);
self.handler.message_audit_pass(ctx, audit).await;
}
}
Some("MESSAGE_AUDIT_REJECT") => {
if let Some(data) = event.data {
let event_id = event.id.unwrap_or_else(|| {
format!("MESSAGE_AUDIT_REJECT_{}", event.sequence.unwrap_or(0))
});
let audit = MessageAudit::from_data((*ctx.api).clone(), event_id, data);
self.handler.message_audit_reject(ctx, audit).await;
}
}
Some("FRIEND_ADD") => {
if let Some(data) = event.data {
let event_id = event.id.clone().or_else(|| {
data.get("id")
.and_then(|v| v.as_str())
.map(|s| s.to_string())
});
let mut data_map = std::collections::HashMap::new();
if let serde_json::Value::Object(obj) = &data {
for (k, v) in obj {
data_map.insert(k.clone(), v.clone());
}
}
let event = C2CManageEvent::new(ctx.api.as_ref().clone(), event_id, &data_map);
self.handler.friend_add(ctx, event).await;
}
}
Some("FRIEND_DEL") => {
if let Some(data) = event.data {
let event_id = event.id.clone().or_else(|| {
data.get("id")
.and_then(|v| v.as_str())
.map(|s| s.to_string())
});
let mut data_map = std::collections::HashMap::new();
if let serde_json::Value::Object(obj) = &data {
for (k, v) in obj {
data_map.insert(k.clone(), v.clone());
}
}
let event = C2CManageEvent::new(ctx.api.as_ref().clone(), event_id, &data_map);
self.handler.friend_del(ctx, event).await;
}
}
Some("C2C_MSG_REJECT") => {
if let Some(data) = event.data {
let event_id = event.id.clone().or_else(|| {
data.get("id")
.and_then(|v| v.as_str())
.map(|s| s.to_string())
});
let mut data_map = std::collections::HashMap::new();
if let serde_json::Value::Object(obj) = &data {
for (k, v) in obj {
data_map.insert(k.clone(), v.clone());
}
}
let event = C2CManageEvent::new(ctx.api.as_ref().clone(), event_id, &data_map);
self.handler.c2c_msg_reject(ctx, event).await;
}
}
Some("C2C_MSG_RECEIVE") => {
if let Some(data) = event.data {
let event_id = event.id.clone().or_else(|| {
data.get("id")
.and_then(|v| v.as_str())
.map(|s| s.to_string())
});
let mut data_map = std::collections::HashMap::new();
if let serde_json::Value::Object(obj) = &data {
for (k, v) in obj {
data_map.insert(k.clone(), v.clone());
}
}
let event = C2CManageEvent::new(ctx.api.as_ref().clone(), event_id, &data_map);
self.handler.c2c_msg_receive(ctx, event).await;
}
}
Some("GROUP_ADD_ROBOT") => {
if let Some(data) = event.data {
let event_id = event.id.clone().or_else(|| {
data.get("id")
.and_then(|v| v.as_str())
.map(|s| s.to_string())
});
let mut data_map = std::collections::HashMap::new();
if let serde_json::Value::Object(obj) = &data {
for (k, v) in obj {
data_map.insert(k.clone(), v.clone());
}
}
let event =
GroupManageEvent::new(ctx.api.as_ref().clone(), event_id, &data_map);
self.handler.group_add_robot(ctx, event).await;
}
}
Some("GROUP_DEL_ROBOT") => {
if let Some(data) = event.data {
let event_id = event.id.clone().or_else(|| {
data.get("id")
.and_then(|v| v.as_str())
.map(|s| s.to_string())
});
let mut data_map = std::collections::HashMap::new();
if let serde_json::Value::Object(obj) = &data {
for (k, v) in obj {
data_map.insert(k.clone(), v.clone());
}
}
let event =
GroupManageEvent::new(ctx.api.as_ref().clone(), event_id, &data_map);
self.handler.group_del_robot(ctx, event).await;
}
}
Some("GROUP_MSG_REJECT") => {
if let Some(data) = event.data {
let event_id = event.id.clone().or_else(|| {
data.get("id")
.and_then(|v| v.as_str())
.map(|s| s.to_string())
});
let mut data_map = std::collections::HashMap::new();
if let serde_json::Value::Object(obj) = &data {
for (k, v) in obj {
data_map.insert(k.clone(), v.clone());
}
}
let event =
GroupManageEvent::new(ctx.api.as_ref().clone(), event_id, &data_map);
self.handler.group_msg_reject(ctx, event).await;
}
}
Some("GROUP_MSG_RECEIVE") => {
if let Some(data) = event.data {
let event_id = event.id.clone().or_else(|| {
data.get("id")
.and_then(|v| v.as_str())
.map(|s| s.to_string())
});
let mut data_map = std::collections::HashMap::new();
if let serde_json::Value::Object(obj) = &data {
for (k, v) in obj {
data_map.insert(k.clone(), v.clone());
}
}
let event =
GroupManageEvent::new(ctx.api.as_ref().clone(), event_id, &data_map);
self.handler.group_msg_receive(ctx, event).await;
}
}
Some("AUDIO_OR_LIVE_CHANNEL_MEMBER_ENTER") => {
if let Some(data) = event.data {
let audio = PublicAudio::new(ctx.api.as_ref().clone(), data);
self.handler
.audio_or_live_channel_member_enter(ctx, audio)
.await;
}
}
Some("AUDIO_OR_LIVE_CHANNEL_MEMBER_EXIT") => {
if let Some(data) = event.data {
let audio = PublicAudio::new(ctx.api.as_ref().clone(), data);
self.handler
.audio_or_live_channel_member_exit(ctx, audio)
.await;
}
}
Some("FORUM_THREAD_CREATE") => {
if let Some(data) = event.data {
let thread = Thread::new(ctx.api.as_ref().clone(), event.id, &data);
self.handler.forum_thread_create(ctx, thread).await;
}
}
Some("FORUM_THREAD_UPDATE") => {
if let Some(data) = event.data {
let thread = Thread::new(ctx.api.as_ref().clone(), event.id, &data);
self.handler.forum_thread_update(ctx, thread).await;
}
}
Some("FORUM_THREAD_DELETE") => {
if let Some(data) = event.data {
let thread = Thread::new(ctx.api.as_ref().clone(), event.id, &data);
self.handler.forum_thread_delete(ctx, thread).await;
}
}
Some("FORUM_POST_CREATE") => {
if let Some(data) = event.data {
self.handler.forum_post_create(ctx, data).await;
}
}
Some("FORUM_POST_DELETE") => {
if let Some(data) = event.data {
self.handler.forum_post_delete(ctx, data).await;
}
}
Some("FORUM_REPLY_CREATE") => {
if let Some(data) = event.data {
self.handler.forum_reply_create(ctx, data).await;
}
}
Some("FORUM_REPLY_DELETE") => {
if let Some(data) = event.data {
self.handler.forum_reply_delete(ctx, data).await;
}
}
Some("FORUM_PUBLISH_AUDIT_RESULT") => {
if let Some(data) = event.data {
self.handler.forum_publish_audit_result(ctx, data).await;
}
}
Some("OPEN_FORUM_THREAD_CREATE") => {
if let Some(data) = event.data {
let mut thread = OpenThread::new(ctx.api.as_ref().clone(), &data);
thread.event_id = event.id;
self.handler.open_forum_thread_create(ctx, thread).await;
}
}
Some("OPEN_FORUM_THREAD_UPDATE") => {
if let Some(data) = event.data {
let mut thread = OpenThread::new(ctx.api.as_ref().clone(), &data);
thread.event_id = event.id;
self.handler.open_forum_thread_update(ctx, thread).await;
}
}
Some("OPEN_FORUM_THREAD_DELETE") => {
if let Some(data) = event.data {
let mut thread = OpenThread::new(ctx.api.as_ref().clone(), &data);
thread.event_id = event.id;
self.handler.open_forum_thread_delete(ctx, thread).await;
}
}
Some("OPEN_FORUM_POST_CREATE") => {
if let Some(data) = event.data {
let mut thread = OpenThread::new(ctx.api.as_ref().clone(), &data);
thread.event_id = event.id;
self.handler.open_forum_post_create(ctx, thread).await;
}
}
Some("OPEN_FORUM_POST_DELETE") => {
if let Some(data) = event.data {
let mut thread = OpenThread::new(ctx.api.as_ref().clone(), &data);
thread.event_id = event.id;
self.handler.open_forum_post_delete(ctx, thread).await;
}
}
Some("OPEN_FORUM_REPLY_CREATE") => {
if let Some(data) = event.data {
let mut thread = OpenThread::new(ctx.api.as_ref().clone(), &data);
thread.event_id = event.id;
self.handler.open_forum_reply_create(ctx, thread).await;
}
}
Some("OPEN_FORUM_REPLY_DELETE") => {
if let Some(data) = event.data {
let mut thread = OpenThread::new(ctx.api.as_ref().clone(), &data);
thread.event_id = event.id;
self.handler.open_forum_reply_delete(ctx, thread).await;
}
}
_ => {
debug!("Unknown event type: {:?}", event.event_type);
self.handler.unknown_event(ctx, event).await;
}
}
Ok(())
}
/// Gets a reference to the API client.
pub fn api(&self) -> &BotApi {
&self.api
}
/// Gets a reference to the HTTP client.
pub fn http(&self) -> &HttpClient {
&self.http
}
/// Gets the intents being used.
pub fn intents(&self) -> Intents {
self.intents
}
/// Returns true if using sandbox environment.
pub fn is_sandbox(&self) -> bool {
self.is_sandbox
}
/// Shuts down the client and cleans up resources.
pub async fn shutdown(&self) {
info!("Shutting down bot client");
self.api.close().await;
}
}
impl<H: EventHandler> std::fmt::Debug for Client<H> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Client")
.field("intents", &self.intents)
.field("is_sandbox", &self.is_sandbox)
.field("timeout", &self.timeout)
.finish()
}
}