botrs 0.3.0

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
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
//! Guild-related data models for the QQ Guild Bot API.
//!
//! This module contains guild types that correspond to the Python botpy implementation.

use crate::models::{HasId, HasName, Snowflake, Timestamp, channel::Channel};
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use std::collections::HashMap;

fn insert_query_param(query: &mut HashMap<String, String>, key: &str, value: &Option<String>) {
    if let Some(value) = value.as_ref().filter(|value| !value.is_empty()) {
        query.insert(key.to_string(), value.clone());
    }
}

mod role_hoist_serde {
    use super::*;

    pub fn serialize<S>(value: &Option<bool>, serializer: S) -> std::result::Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        match value {
            Some(value) => serializer.serialize_some(&u32::from(*value)),
            None => serializer.serialize_none(),
        }
    }

    pub fn deserialize<'de, D>(deserializer: D) -> std::result::Result<Option<bool>, D::Error>
    where
        D: Deserializer<'de>,
    {
        let value = Option::<serde_json::Value>::deserialize(deserializer)?;
        Ok(value.and_then(|value| match value {
            serde_json::Value::Bool(value) => Some(value),
            serde_json::Value::Number(value) => value.as_u64().map(|value| value != 0),
            _ => None,
        }))
    }
}

/// Represents a guild (server) in the QQ Guild system.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Guild {
    /// The guild's unique ID
    pub id: Option<Snowflake>,
    /// The guild's name
    pub name: Option<String>,
    /// The guild's icon hash
    pub icon: Option<String>,
    /// The ID of the guild owner
    pub owner_id: Option<Snowflake>,
    /// Whether the current user is the owner of this guild
    pub is_owner: Option<bool>,
    /// The number of members in this guild
    pub member_count: Option<u32>,
    /// The maximum number of members for this guild
    pub max_members: Option<u32>,
    /// The guild's description
    pub description: Option<String>,
    /// When the current user joined this guild
    pub joined_at: Option<Timestamp>,
}

impl Guild {
    /// Creates a new guild.
    pub fn new() -> Self {
        Self {
            id: None,
            name: None,
            icon: None,
            owner_id: None,
            is_owner: None,
            member_count: None,
            max_members: None,
            description: None,
            joined_at: None,
        }
    }

    /// Creates a new guild from API data.
    pub fn from_data(_api: crate::api::BotApi, id: String, data: serde_json::Value) -> Self {
        Self {
            id: Some(id),
            name: data.get("name").and_then(|v| v.as_str()).map(String::from),
            icon: data.get("icon").and_then(|v| v.as_str()).map(String::from),
            owner_id: data
                .get("owner_id")
                .and_then(|v| v.as_str())
                .map(String::from),
            is_owner: data.get("is_owner").and_then(|v| v.as_bool()),
            member_count: data
                .get("member_count")
                .and_then(|v| v.as_u64())
                .map(|v| v as u32),
            max_members: data
                .get("max_members")
                .and_then(|v| v.as_u64())
                .map(|v| v as u32),
            description: data
                .get("description")
                .and_then(|v| v.as_str())
                .map(String::from),
            joined_at: data
                .get("joined_at")
                .and_then(|v| v.as_str())
                .and_then(|s| chrono::DateTime::parse_from_rfc3339(s).ok())
                .map(|dt| dt.with_timezone(&chrono::Utc)),
        }
    }

    /// Gets the guild's icon URL if it has one.
    pub fn icon_url(&self) -> Option<String> {
        self.icon.as_ref().map(|hash| {
            format!(
                "https://groupprofile.qq.com/groupicon/{}/{}",
                self.id.as_ref().unwrap_or(&String::new()),
                hash
            )
        })
    }

    /// Returns true if the current user owns this guild.
    pub fn is_owned_by_current_user(&self) -> bool {
        self.is_owner.unwrap_or(false)
    }

    /// Gets the guild's member count.
    pub fn get_member_count(&self) -> u32 {
        self.member_count.unwrap_or(0)
    }

    /// Gets the guild's maximum member count.
    pub fn get_max_members(&self) -> u32 {
        self.max_members.unwrap_or(0)
    }

    /// Returns true if the guild has reached its member limit.
    pub fn is_at_member_limit(&self) -> bool {
        match (self.member_count, self.max_members) {
            (Some(current), Some(max)) => current >= max,
            _ => false,
        }
    }

    /// Gets the guild's display name (same as name for guilds).
    pub fn display_name(&self) -> Option<&str> {
        self.name.as_deref()
    }

    /// Returns true if the guild has a description.
    pub fn has_description(&self) -> bool {
        self.description
            .as_ref()
            .is_some_and(|desc| !desc.is_empty())
    }
}

impl Default for Guild {
    fn default() -> Self {
        Self::new()
    }
}

impl HasId for Guild {
    fn id(&self) -> Option<&Snowflake> {
        self.id.as_ref()
    }
}

impl HasName for Guild {
    fn name(&self) -> &str {
        self.name.as_deref().unwrap_or("")
    }
}

/// Guild roles response wrapper.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct GuildRoles {
    /// Guild ID
    pub guild_id: Option<Snowflake>,
    /// List of roles in the guild
    pub roles: Vec<GuildRole>,
    /// Number of roles
    pub role_num_limit: Option<String>,
}

impl GuildRoles {
    /// Creates a new guild roles wrapper.
    pub fn new(roles: Vec<GuildRole>) -> Self {
        Self {
            guild_id: None,
            roles,
            role_num_limit: None,
        }
    }
}

/// Represents a role ID.
pub type RoleId = Snowflake;
/// Botgo-compatible role ID alias.
pub type RoleID = RoleId;
/// Default role color used by botgo when creating or updating roles.
pub const DEFAULT_ROLE_COLOR: u32 = 4_278_245_297;

/// Botgo-compatible role update info body.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
pub struct UpdateRoleInfo {
    pub name: String,
    pub color: u32,
    pub hoist: u32,
}

/// Represents a role in a guild.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct GuildRole {
    /// The role's unique ID
    pub id: Option<Snowflake>,
    /// The role's name
    pub name: Option<String>,
    /// The role's color (ARGB hex as decimal)
    pub color: Option<u32>,
    /// Whether this role is displayed separately in the member list
    #[serde(with = "role_hoist_serde", default)]
    pub hoist: Option<bool>,
    /// The number of members with this role
    pub number: Option<u32>,
    /// The number of online members with this role
    pub member_limit: Option<u32>,
}

impl GuildRole {
    fn default_color() -> u32 {
        DEFAULT_ROLE_COLOR
    }

    fn hoist_value(&self) -> u32 {
        self.hoist.map(u32::from).unwrap_or(0)
    }
}

/// Filter identifying which role fields are being updated.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct UpdateRoleFilter {
    pub name: u32,
    pub color: u32,
    pub hoist: u32,
}

impl Default for UpdateRoleFilter {
    fn default() -> Self {
        Self {
            name: 1,
            color: 1,
            hoist: 1,
        }
    }
}

/// Botgo-compatible role update body.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct UpdateRole {
    pub guild_id: String,
    pub filter: UpdateRoleFilter,
    #[serde(rename = "info")]
    pub update: GuildRole,
}

impl UpdateRole {
    /// Creates a role update body with botgo-compatible defaults.
    pub fn new(guild_id: impl Into<String>, mut role: GuildRole) -> Self {
        if role.color.unwrap_or(0) == 0 {
            role.color = Some(GuildRole::default_color());
        }
        role.hoist = Some(role.is_hoisted());
        Self {
            guild_id: guild_id.into(),
            filter: UpdateRoleFilter::default(),
            update: role,
        }
    }
}

/// Result returned from role create/update APIs.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct UpdateResult {
    pub role_id: Option<Snowflake>,
    pub guild_id: Option<Snowflake>,
    pub role: Option<GuildRole>,
}

impl GuildRole {
    /// Creates a new role.
    pub fn new() -> Self {
        Self {
            id: None,
            name: None,
            color: None,
            hoist: None,
            number: None,
            member_limit: None,
        }
    }

    /// Returns true if this role is hoisted (displayed separately).
    pub fn is_hoisted(&self) -> bool {
        self.hoist.unwrap_or(false)
    }

    /// Converts the role to the numeric hoist value expected by the API.
    pub fn hoist_as_u32(&self) -> u32 {
        self.hoist_value()
    }

    /// Gets the role's color as a hex value.
    pub fn color_hex(&self) -> Option<String> {
        self.color.map(|c| format!("#{c:06X}"))
    }

    /// Gets the number of members with this role.
    pub fn member_count(&self) -> u32 {
        self.number.unwrap_or(0)
    }

    /// Gets the member limit for this role.
    pub fn get_member_limit(&self) -> u32 {
        self.member_limit.unwrap_or(0)
    }

    /// Returns true if the role has reached its member limit.
    pub fn is_at_member_limit(&self) -> bool {
        match (self.number, self.member_limit) {
            (Some(current), Some(limit)) => current >= limit,
            _ => false,
        }
    }
}

impl Default for GuildRole {
    fn default() -> Self {
        Self::new()
    }
}

impl HasId for GuildRole {
    fn id(&self) -> Option<&Snowflake> {
        self.id.as_ref()
    }
}

impl HasName for GuildRole {
    fn name(&self) -> &str {
        self.name.as_deref().unwrap_or("")
    }
}

/// Represents a role in a guild (legacy type alias).
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Role {
    /// The role's unique ID
    pub id: Option<Snowflake>,
    /// The role's name
    pub name: Option<String>,
    /// The role's color (ARGB hex as decimal)
    pub color: Option<u32>,
    /// Whether this role is displayed separately in the member list
    pub hoist: Option<bool>,
    /// The number of members with this role
    pub number: Option<u32>,
    /// The number of online members with this role
    pub member_limit: Option<u32>,
}

impl Role {
    /// Creates a new role.
    pub fn new() -> Self {
        Self {
            id: None,
            name: None,
            color: None,
            hoist: None,
            number: None,
            member_limit: None,
        }
    }

    /// Returns true if this role is hoisted (displayed separately).
    pub fn is_hoisted(&self) -> bool {
        self.hoist.unwrap_or(false)
    }

    /// Gets the role's color as a hex value.
    pub fn color_hex(&self) -> Option<String> {
        self.color.map(|c| format!("#{c:06X}"))
    }

    /// Gets the number of members with this role.
    pub fn member_count(&self) -> u32 {
        self.number.unwrap_or(0)
    }

    /// Gets the member limit for this role.
    pub fn get_member_limit(&self) -> u32 {
        self.member_limit.unwrap_or(0)
    }

    /// Returns true if the role has reached its member limit.
    pub fn is_at_member_limit(&self) -> bool {
        match (self.number, self.member_limit) {
            (Some(current), Some(limit)) => current >= limit,
            _ => false,
        }
    }
}

impl Default for Role {
    fn default() -> Self {
        Self::new()
    }
}

impl HasId for Role {
    fn id(&self) -> Option<&Snowflake> {
        self.id.as_ref()
    }
}

impl HasName for Role {
    fn name(&self) -> &str {
        self.name.as_deref().unwrap_or("")
    }
}

// Type alias for backward compatibility
pub type Roles = Vec<Role>;

/// Pager for guild member list requests.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
pub struct GuildMembersPager {
    /// Read members after this user ID
    #[serde(skip_serializing_if = "Option::is_none")]
    pub after: Option<String>,
    /// Page size
    #[serde(skip_serializing_if = "Option::is_none")]
    pub limit: Option<String>,
}

impl GuildMembersPager {
    /// Creates a new guild members pager.
    pub fn new(after: impl Into<String>, limit: impl ToString) -> Self {
        Self {
            after: Some(after.into()),
            limit: Some(limit.to_string()),
        }
    }

    /// Converts the pager to botgo-compatible query parameters.
    pub fn query_params(&self) -> HashMap<String, String> {
        let mut query = HashMap::new();
        insert_query_param(&mut query, "limit", &self.limit);
        insert_query_param(&mut query, "after", &self.after);
        query
    }
}

/// Pager for guild role member list requests.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
pub struct GuildRoleMembersPager {
    /// Start index from the previous response's `next` value
    #[serde(skip_serializing_if = "Option::is_none")]
    pub start_index: Option<String>,
    /// Page size
    #[serde(skip_serializing_if = "Option::is_none")]
    pub limit: Option<String>,
}

impl GuildRoleMembersPager {
    /// Creates a new guild role members pager.
    pub fn new(start_index: impl Into<String>, limit: impl ToString) -> Self {
        Self {
            start_index: Some(start_index.into()),
            limit: Some(limit.to_string()),
        }
    }

    /// Converts the pager to botgo-compatible query parameters.
    pub fn query_params(&self) -> HashMap<String, String> {
        let mut query = HashMap::new();
        insert_query_param(&mut query, "limit", &self.limit);
        insert_query_param(&mut query, "start_index", &self.start_index);
        query
    }
}

/// Pager for current-user guild list requests.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
pub struct GuildPager {
    /// Read guilds before this guild ID.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub before: Option<String>,
    /// Read guilds after this guild ID. Takes precedence over `before`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub after: Option<String>,
    /// Page size.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub limit: Option<String>,
}

impl GuildPager {
    /// Creates an empty guild pager.
    pub fn new() -> Self {
        Self::default()
    }

    pub fn with_after(mut self, after: impl Into<String>) -> Self {
        self.after = Some(after.into());
        self
    }

    pub fn with_before(mut self, before: impl Into<String>) -> Self {
        self.before = Some(before.into());
        self
    }

    pub fn with_limit(mut self, limit: impl ToString) -> Self {
        self.limit = Some(limit.to_string());
        self
    }

    /// Converts the pager to botgo-compatible query parameters.
    pub fn query_params(&self) -> HashMap<String, String> {
        let mut query = HashMap::new();
        insert_query_param(&mut query, "limit", &self.limit);
        insert_query_param(&mut query, "after", &self.after);
        if !query.contains_key("after") {
            insert_query_param(&mut query, "before", &self.before);
        }
        query
    }
}

/// Response returned by the guild role members endpoint.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
pub struct GuildRoleMembers {
    /// Role members in the current page
    #[serde(default)]
    pub data: Vec<Member>,
    /// Cursor for the next page
    #[serde(default)]
    pub next: String,
}

/// Body used when adding or deleting a member role.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
pub struct MemberAddRoleBody {
    /// Channel object for channel administrator roles.
    pub channel: Option<Channel>,
}

impl MemberAddRoleBody {
    /// Creates a body without a channel.
    pub fn new() -> Self {
        Self { channel: None }
    }

    /// Creates a body for a channel-specific role.
    pub fn with_channel_id(channel_id: impl Into<String>) -> Self {
        let mut channel = Channel::new();
        channel.id = Some(channel_id.into());
        Self {
            channel: Some(channel),
        }
    }
}

/// Supported history deletion windows when removing a guild member.
pub type DeleteHistoryMsgDay = i32;

pub const NO_DELETE: DeleteHistoryMsgDay = 0;
pub const DELETE_THREE_DAYS: DeleteHistoryMsgDay = 3;
pub const DELETE_SEVEN_DAYS: DeleteHistoryMsgDay = 7;
pub const DELETE_FIFTEEN_DAYS: DeleteHistoryMsgDay = 15;
pub const DELETE_THIRTY_DAYS: DeleteHistoryMsgDay = 30;
pub const DELETE_ALL: DeleteHistoryMsgDay = -1;
#[allow(non_upper_case_globals)]
pub const NoDelete: DeleteHistoryMsgDay = NO_DELETE;
#[allow(non_upper_case_globals)]
pub const DeleteThreeDays: DeleteHistoryMsgDay = DELETE_THREE_DAYS;
#[allow(non_upper_case_globals)]
pub const DeleteSevenDays: DeleteHistoryMsgDay = DELETE_SEVEN_DAYS;
#[allow(non_upper_case_globals)]
pub const DeleteFifteenDays: DeleteHistoryMsgDay = DELETE_FIFTEEN_DAYS;
#[allow(non_upper_case_globals)]
pub const DeleteThirtyDays: DeleteHistoryMsgDay = DELETE_THIRTY_DAYS;
#[allow(non_upper_case_globals)]
pub const DeleteAll: DeleteHistoryMsgDay = DELETE_ALL;

pub type MemberDeleteOpts = MemberDeleteOptions;

/// Additional options for deleting a guild member.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct MemberDeleteOptions {
    /// Whether to add the member to the guild blacklist
    pub add_blacklist: bool,
    /// How many days of history to retract
    pub delete_history_msg_days: DeleteHistoryMsgDay,
}

impl MemberDeleteOptions {
    /// Creates delete options with official defaults.
    pub fn new() -> Self {
        Self::default()
    }

    /// Sets whether the member should also be added to the blacklist.
    pub fn with_add_blacklist(mut self, add_blacklist: bool) -> Self {
        self.add_blacklist = add_blacklist;
        self
    }

    /// Sets the history deletion window.
    pub fn with_delete_history_msg_days(mut self, days: DeleteHistoryMsgDay) -> Self {
        self.delete_history_msg_days = normalize_delete_history_msg_days(days);
        self
    }
}

impl Default for MemberDeleteOptions {
    fn default() -> Self {
        Self {
            add_blacklist: false,
            delete_history_msg_days: NO_DELETE,
        }
    }
}

pub type MemberDeleteOption = Box<dyn FnOnce(&mut MemberDeleteOptions) + Send>;

#[allow(non_snake_case)]
pub fn WithAddBlackList(add_blacklist: bool) -> MemberDeleteOption {
    Box::new(move |options| {
        options.add_blacklist = add_blacklist;
    })
}

#[allow(non_snake_case)]
pub fn WithDeleteHistoryMsg(days: DeleteHistoryMsgDay) -> MemberDeleteOption {
    Box::new(move |options| {
        options.delete_history_msg_days = normalize_delete_history_msg_days(days);
    })
}

/// Normalizes history deletion days to the official supported values.
pub fn normalize_delete_history_msg_days(days: DeleteHistoryMsgDay) -> DeleteHistoryMsgDay {
    match days {
        DELETE_THREE_DAYS | DELETE_SEVEN_DAYS | DELETE_FIFTEEN_DAYS | DELETE_THIRTY_DAYS
        | DELETE_ALL => days,
        _ => NO_DELETE,
    }
}

/// Body for guild mute endpoints.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
pub struct UpdateGuildMute {
    /// Mute end timestamp in seconds
    #[serde(skip_serializing_if = "Option::is_none")]
    pub mute_end_timestamp: Option<String>,
    /// Mute duration in seconds
    #[serde(skip_serializing_if = "Option::is_none")]
    pub mute_seconds: Option<String>,
    /// User IDs for batch mute
    #[serde(skip_serializing_if = "Option::is_none")]
    pub user_ids: Option<Vec<String>>,
}

impl UpdateGuildMute {
    /// Creates a mute request body.
    pub fn new(mute_end_timestamp: Option<&str>, mute_seconds: Option<&str>) -> Self {
        Self {
            mute_end_timestamp: mute_end_timestamp.map(String::from),
            mute_seconds: mute_seconds.map(String::from),
            user_ids: None,
        }
    }

    /// Creates a batch mute request body.
    pub fn new_multi(
        user_ids: Vec<String>,
        mute_end_timestamp: Option<&str>,
        mute_seconds: Option<&str>,
    ) -> Self {
        Self {
            mute_end_timestamp: mute_end_timestamp.map(String::from),
            mute_seconds: mute_seconds.map(String::from),
            user_ids: Some(user_ids),
        }
    }

    /// Creates a request body that cancels mute.
    pub fn cancel() -> Self {
        Self {
            mute_end_timestamp: Some("0".to_string()),
            mute_seconds: Some("0".to_string()),
            user_ids: None,
        }
    }

    /// Creates a request body that cancels mute for multiple users.
    pub fn cancel_multi(user_ids: Vec<String>) -> Self {
        Self {
            mute_end_timestamp: Some("0".to_string()),
            mute_seconds: Some("0".to_string()),
            user_ids: Some(user_ids),
        }
    }
}

/// Response for batch guild mute.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
pub struct UpdateGuildMuteResponse {
    /// Successfully muted user IDs
    #[serde(default)]
    pub user_ids: Vec<String>,
}

/// Represents a member of a guild.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Member {
    /// Guild ID
    pub guild_id: Option<Snowflake>,
    /// The user information
    pub user: Option<crate::models::User>,
    /// The member's nickname in the guild
    pub nick: Option<String>,
    /// The member's roles in the guild
    pub roles: Option<Vec<Snowflake>>,
    /// When the member joined the guild
    pub joined_at: Option<Timestamp>,
    /// Operator user ID
    pub op_user_id: Option<Snowflake>,
}

impl Member {
    /// Creates a new member.
    pub fn new() -> Self {
        Self {
            guild_id: None,
            user: None,
            nick: None,
            roles: None,
            joined_at: None,
            op_user_id: None,
        }
    }

    /// Gets the member's display name (nickname or username).
    pub fn display_name(&self) -> Option<&str> {
        self.nick
            .as_deref()
            .or_else(|| self.user.as_ref().map(|u| u.username.as_str()))
    }

    /// Gets the member's username.
    pub fn username(&self) -> Option<&str> {
        self.user.as_ref().map(|u| u.username.as_str())
    }

    /// Gets the member's user ID.
    pub fn user_id(&self) -> Option<&Snowflake> {
        self.user.as_ref().map(|u| &u.id)
    }

    /// Returns true if the member is a bot.
    pub fn is_bot(&self) -> bool {
        self.user.as_ref().is_some_and(|u| u.is_bot())
    }

    /// Gets the member's roles.
    pub fn role_ids(&self) -> &[Snowflake] {
        self.roles.as_deref().unwrap_or(&[])
    }

    /// Returns true if the member has a specific role.
    pub fn has_role(&self, role_id: &str) -> bool {
        self.role_ids().iter().any(|id| id == role_id)
    }
}

impl Default for Member {
    fn default() -> Self {
        Self::new()
    }
}

impl HasId for Member {
    fn id(&self) -> Option<&Snowflake> {
        self.user_id()
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_guild_creation() {
        let guild = Guild::new();
        assert!(guild.id.is_none());
        assert!(guild.name.is_none());
        assert!(!guild.is_owned_by_current_user());
        assert_eq!(guild.get_member_count(), 0);
        assert_eq!(guild.get_max_members(), 0);
    }

    #[test]
    fn test_guild_with_data() {
        let mut guild = Guild::new();
        guild.id = Some("123456789".to_string());
        guild.name = Some("Test Guild".to_string());
        guild.is_owner = Some(true);
        guild.member_count = Some(100);
        guild.max_members = Some(500);
        guild.description = Some("A test guild".to_string());

        assert_eq!(guild.id(), Some(&"123456789".to_string()));
        assert_eq!(guild.name(), "Test Guild");
        assert!(guild.is_owned_by_current_user());
        assert_eq!(guild.get_member_count(), 100);
        assert_eq!(guild.get_max_members(), 500);
        assert!(!guild.is_at_member_limit());
        assert!(guild.has_description());
        assert_eq!(guild.display_name(), Some("Test Guild"));
    }

    #[test]
    fn test_member_limit() {
        let mut guild = Guild::new();
        guild.member_count = Some(500);
        guild.max_members = Some(500);
        assert!(guild.is_at_member_limit());

        guild.member_count = Some(499);
        assert!(!guild.is_at_member_limit());

        guild.member_count = Some(501);
        assert!(guild.is_at_member_limit());
    }

    #[test]
    fn test_icon_url() {
        let mut guild = Guild::new();
        assert!(guild.icon_url().is_none());

        guild.id = Some("123456789".to_string());
        guild.icon = Some("abc123".to_string());
        let url = guild.icon_url().unwrap();
        assert!(url.contains("123456789"));
        assert!(url.contains("abc123"));
    }

    #[test]
    fn test_role_creation() {
        let role = Role::new();
        assert!(role.id.is_none());
        assert!(role.name.is_none());
        assert!(!role.is_hoisted());
        assert_eq!(role.member_count(), 0);
    }

    #[test]
    fn test_role_with_data() {
        let mut role = Role::new();
        role.id = Some("role123".to_string());
        role.name = Some("Admin".to_string());
        role.color = Some(0xFF0000);
        role.hoist = Some(true);
        role.number = Some(5);
        role.member_limit = Some(10);

        assert_eq!(role.id(), Some(&"role123".to_string()));
        assert_eq!(role.name(), "Admin");
        assert_eq!(role.color_hex(), Some("#FF0000".to_string()));
        assert!(role.is_hoisted());
        assert_eq!(role.member_count(), 5);
        assert_eq!(role.get_member_limit(), 10);
        assert!(!role.is_at_member_limit());
    }

    #[test]
    fn test_member_creation() {
        let member = Member::new();
        assert!(member.user.is_none());
        assert!(member.nick.is_none());
        assert_eq!(member.role_ids().len(), 0);
    }

    #[test]
    fn test_member_with_roles() {
        let mut member = Member::new();
        member.roles = Some(vec!["role1".to_string(), "role2".to_string()]);

        assert!(member.has_role("role1"));
        assert!(member.has_role("role2"));
        assert!(!member.has_role("role3"));
        assert_eq!(member.role_ids().len(), 2);
    }
}