hubbub 0.10.1

Discord self-bot library for rust
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
use crate::context::{Context, Response};
use crate::error::Error;
use crate::types::timestamp::Timestamp;
use crate::types::user::{AvatarDecorationData, User};

use anyhow::Result;
use http::Method;
use serde::{Deserialize, Serialize};
use serde_json::{json, Value};
use serde_repr::{Deserialize_repr, Serialize_repr};
use tokio::sync::MutexGuard;

use super::{
    channel::{welcome_screen::WelcomeScreen, Channel},
    common::Emoji,
    role::Role,
    sticker::Sticker,
    Snowflake,
};

#[derive(Serialize_repr, Deserialize_repr, Debug, Eq, PartialEq, Clone)]
#[repr(u8)]
pub enum MFALevel {
    None = 0,     // dont
    Elevated = 1, // need 2FA for moderation
}

#[derive(Serialize_repr, Deserialize_repr, Debug, Eq, PartialEq, Clone)]
#[repr(u8)]
pub enum NSFWLevel {
    Default = 0,
    Explicit = 1,
    Safe = 2,
    AgeRestricted = 3,
}

#[derive(Serialize_repr, Deserialize_repr, Debug, Eq, PartialEq, Clone)]
#[repr(u8)]
pub enum VerificationLevel {
    None = 0,     // unrestricted
    Low = 1,      // verified email
    Medium = 2,   // registered for > 5min
    High = 3,     // member of server > 10min
    VeryHigh = 4, // verified phone #
}

#[derive(Serialize_repr, Deserialize_repr, Debug, Eq, PartialEq, Clone)]
#[repr(u8)]
pub enum MessageNotificationLevel {
    AllMessages = 0,
    OnlyMentions = 1,
}

#[derive(Serialize_repr, Deserialize_repr, Debug, Eq, PartialEq, Clone)]
#[repr(u8)]
pub enum ExplicitContentFilterLevel {
    Disabled = 0, // no members get scanned
    MembersWithoutRoles = 1,
    AllMembers = 2,
}

#[derive(Debug)]
#[repr(u8)]
pub enum SystemChannelFlags {
    SuppressJoinNotifications = 1 << 0,
    SuppressPremiumSubscriptions = 1 << 1,
    SuppressGuildReminders = 1 << 2,
    SuppressJoinReplies = 1 << 3,
    SuppressRoleSubPurchases = 1 << 4,
    SuppressRoleSubPurchaseReplies = 1 << 5,
}

#[derive(Deserialize, Serialize, Debug, Clone)]
pub struct Guild {
    pub id: Snowflake,
    pub name: String,

    pub owner_id: Snowflake,

    pub icon: Option<String>,
    pub icon_hash: Option<String>,

    #[serde(rename = "vanity_url_code")]
    pub vanity_invite: Option<String>,

    pub description: Option<String>,
    pub banner: Option<String>, // banner hash

    #[serde(rename = "discovery_splash")]
    pub splash_discovery: Option<String>,
    pub splash: Option<String>,

    #[serde(rename = "preferred_locale")]
    pub locale: String,

    pub mfa_level: MFALevel,
    pub nsfw_level: NSFWLevel,
    pub verification_level: VerificationLevel,
    #[serde(rename = "default_message_notifications")]
    pub default_notification_level: MessageNotificationLevel,
    #[serde(rename = "explicit_content_filter")]
    pub explicit_content_filter_level: ExplicitContentFilterLevel,

    pub roles: Option<Vec<Role>>,
    pub emojis: Option<Vec<Emoji>>,
    pub stickers: Option<Vec<Sticker>>,
    pub features: Vec<String>,

    // wtf is this used for
    pub application_id: Option<Snowflake>,

    pub welcome_screen: Option<WelcomeScreen>,

    pub public_updates_channel_id: Option<Snowflake>,
    pub safety_alerts_channel_id: Option<Snowflake>,
    pub system_channel_id: Option<Snowflake>,
    pub rules_channel_id: Option<Snowflake>,
    pub system_channel_flags: u8,

    pub afk_channel_id: Option<Snowflake>,
    pub afk_timeout: i32, // in seconds

    pub widget_channel_id: Option<Snowflake>,
    pub widget_enabled: Option<bool>,

    pub max_presences: Option<u64>, // almost always null
    pub max_members: Option<u64>,

    #[serde(rename = "premium_tier")]
    pub boost_tier: u8, // 0..=3
    #[serde(rename = "premium_subscription_count")]
    pub boosts: Option<u64>,
    #[serde(rename = "premium_progress_bar_enabled")]
    pub boost_bar_enabled: bool,

    pub max_video_channel_users: u64,
    pub max_stage_video_channel_users: u64,

    // if using "Get current user guilds" endpoint
    pub owner: Option<bool>,
    pub permissions: Option<String>,

    // these need "with_counts" enabled
    pub member_count: Option<u64>,
    pub presence_count: Option<u64>,
}

impl Guild {
    pub fn icon_url(&self) -> Option<String> {
        self.icon_hash
            .as_ref()
            .map(|hash| format!("https://cdn.discordapp.com/icons/{}/{}.png", self.id, hash))
    }

    pub fn banner_url(&self) -> Option<String> {
        self.banner.as_ref().map(|hash| {
            format!(
                "https://cdn.discordapp.com/banners/{}/{}.png",
                self.id, hash
            )
        })
    }

    pub fn splash_url(&self) -> Option<String> {
        self.splash.as_ref().map(|hash| {
            format!(
                "https://cdn.discordapp.com/splashes/{}/{}.png",
                self.id, hash
            )
        })
    }

    pub fn discovery_splash_url(&self) -> Option<String> {
        self.splash_discovery.as_ref().map(|hash| {
            format!(
                "https://cdn.discordapp.com/splashes/{}/{}.png",
                self.id, hash
            )
        })
    }

    pub async fn fetch_guild(
        ctx: &mut MutexGuard<'_, Context>,
        id: Snowflake,
    ) -> Result<Response> {
        ctx.request(Method::GET, &format!("/v9/guilds/{}", id), None)
            .await
    }

    // Very rarely likely to work
    pub async fn delete_guild(self, ctx: &mut MutexGuard<'_, Context>) -> Result<Response> {
        ctx.request(
            Method::DELETE,
            &format!("/v9/guilds/{}", self.id),
            None,
        )
        .await
    }

    /**
     * Channels
     */

    pub async fn fetch_channels_static(
        ctx: &mut MutexGuard<'_, Context>,
        id: Snowflake,
    ) -> Result<Response> {
        ctx.request(
            Method::GET,
            &format!("/v9/guilds/{}/channels", id),
            None,
        )
        .await
    }
    pub async fn fetch_channels(
        &self,
        ctx: &mut MutexGuard<'_, Context>,
    ) -> Result<Response> {
        Self::fetch_channels_static(ctx, self.id).await
    }

    pub async fn create_channel_static(
        ctx: &mut MutexGuard<'_, Context>,
        id: Snowflake,
        channel: Value,
    ) -> Result<Response> {
        ctx.request(
            Method::POST,
            &format!("/v9/guilds/{}/channels", id),
            Some(channel),
        )
        .await
    }
    pub async fn create_channel(
        &self,
        ctx: &mut MutexGuard<'_, Context>,
        channel: Value,
    ) -> Result<Response> {
        Self::create_channel_static(ctx, self.id, channel).await
    }

    /**
     * Members
     */

    pub async fn fetch_members_static(
        ctx: &mut MutexGuard<'_, Context>,
        id: Snowflake,
        limit: u64,
    ) -> Result<Response> {
        if limit == 0 || limit > 1000 {
            return Err(
                Error::InvalidApiRequest("limit must be between 1 and 1000".to_string()).into(),
            );
        }
        ctx.request(
            Method::GET,
            &format!("/v9/guilds/{}/members?limit={}", id, limit),
            None,
        )
        .await
    }
    pub async fn fetch_members(
        &self,
        ctx: &mut MutexGuard<'_, Context>,
        limit: u64,
    ) -> Result<Response> {
        Self::fetch_members_static(ctx, self.id, limit).await
    }

    pub async fn fetch_member_static(
        ctx: &mut MutexGuard<'_, Context>,
        id: Snowflake,
        user_id: Snowflake,
    ) -> Result<Response> {
        ctx.request(
            Method::GET,
            &format!("/v9/guilds/{}/members/{}", id, user_id),
            None,
        )
        .await
    }
    pub async fn fetch_member(
        &self,
        ctx: &mut MutexGuard<'_, Context>,
        user_id: Snowflake,
    ) -> Result<Response> {
        Self::fetch_member_static(ctx, self.id, user_id).await
    }

    pub async fn search_members_static(
        ctx: &mut MutexGuard<'_, Context>,
        id: Snowflake,
        query: String,
        limit: u64,
    ) -> Result<Response> {
        if limit == 0 || limit > 1000 {
            return Err(
                Error::InvalidApiRequest("limit must be between 1 and 1000".to_string()).into(),
            );
        }
        ctx.request(
            Method::GET,
            &format!(
                "/v9/guilds/{}/members/search?query={}&limit={}",
                id, query, limit
            ),
            None,
        )
        .await
    }
    pub async fn search_members(
        &self,
        ctx: &mut MutexGuard<'_, Context>,
        query: String,
        limit: u64,
    ) -> Result<Response> {
        Self::search_members_static(ctx, self.id, query, limit).await
    }

    pub async fn edit_member_static(
        ctx: &mut MutexGuard<'_, Context>,
        id: Snowflake,
        user_id: Snowflake,
        member: Value,
    ) -> Result<Response> {
        ctx.request(
            Method::PATCH,
            &format!("/v9/guilds/{}/members/{}", id, user_id),
            Some(member),
        )
        .await
    }
    pub async fn edit_member(
        &self,
        ctx: &mut MutexGuard<'_, Context>,
        user_id: Snowflake,
        member: Value,
    ) -> Result<Response> {
        Self::edit_member_static(ctx, self.id, user_id, member).await
    }

    pub async fn kick_member_static(
        ctx: &mut MutexGuard<'_, Context>,
        id: Snowflake,
        user_id: Snowflake,
    ) -> Result<Response> {
        ctx.request(
            Method::DELETE,
            &format!("/v9/guilds/{}/members/{}", id, user_id),
            None,
        )
        .await
    }
    pub async fn kick_member(
        &self,
        ctx: &mut MutexGuard<'_, Context>,
        user_id: Snowflake,
    ) -> Result<Response> {
        Self::kick_member_static(ctx, self.id, user_id).await
    }

    /**
     * Bans
     */

    pub async fn ban_member_static(
        ctx: &mut MutexGuard<'_, Context>,
        id: Snowflake,
        user_id: Snowflake,
    ) -> Result<Response> {
        ctx.request(
            Method::PUT,
            &format!("/v9/guilds/{}/bans/{}", id, user_id),
            None,
        )
        .await
    }
    pub async fn ban_member(
        &self,
        ctx: &mut MutexGuard<'_, Context>,
        user_id: Snowflake,
    ) -> Result<Response> {
        Self::ban_member_static(ctx, self.id, user_id).await
    }

    pub async fn unban_member_static(
        ctx: &mut MutexGuard<'_, Context>,
        id: Snowflake,
        user_id: Snowflake,
    ) -> Result<Response> {
        ctx.request(
            Method::DELETE,
            &format!("/v9/guilds/{}/bans/{}", id, user_id),
            None,
        )
        .await
    }
    pub async fn unban_member(
        &self,
        ctx: &mut MutexGuard<'_, Context>,
        user_id: Snowflake,
    ) -> Result<Response> {
        Self::unban_member_static(ctx, self.id, user_id).await
    }

    pub async fn get_bans_static(
        ctx: &mut MutexGuard<'_, Context>,
        id: Snowflake,
    ) -> Result<Response> {
        ctx.request(Method::GET, &format!("/v9/guilds/{}/bans", id), None)
            .await
    }
    pub async fn get_bans(&self, ctx: &mut MutexGuard<'_, Context>) -> Result<Response> {
        Self::get_bans_static(ctx, self.id).await
    }

    pub async fn get_ban_static(
        ctx: &mut MutexGuard<'_, Context>,
        id: Snowflake,
        user_id: Snowflake,
    ) -> Result<Response> {
        ctx.request(
            Method::GET,
            &format!("/v9/guilds/{}/bans/{}", id, user_id),
            None,
        )
        .await
    }
    pub async fn get_ban(
        &self,
        ctx: &mut MutexGuard<'_, Context>,
        user_id: Snowflake,
    ) -> Result<Response> {
        Self::get_ban_static(ctx, self.id, user_id).await
    }

    /**
     * Roles
     */

    pub async fn fetch_roles_static(
        ctx: &mut MutexGuard<'_, Context>,
        id: Snowflake,
    ) -> Result<Response> {
        ctx.request(Method::GET, &format!("/v9/guilds/{}/roles", id), None)
            .await
    }
    pub async fn fetch_roles(&self, ctx: &mut MutexGuard<'_, Context>) -> Result<Response> {
        Self::fetch_roles_static(ctx, self.id).await
    }

    pub async fn create_role_static(
        ctx: &mut MutexGuard<'_, Context>,
        id: Snowflake,
        role: Value,
    ) -> Result<Response> {
        ctx.request(
            Method::POST,
            &format!("/v9/guilds/{}/roles", id),
            Some(role),
        )
        .await
    }
    pub async fn create_role(
        &self,
        ctx: &mut MutexGuard<'_, Context>,
        role: Value,
    ) -> Result<Response> {
        Self::create_role_static(ctx, self.id, role).await
    }

    pub async fn edit_role_static(
        ctx: &mut MutexGuard<'_, Context>,
        id: Snowflake,
        role_id: Snowflake,
        role: Value,
    ) -> Result<Response> {
        ctx.request(
            Method::PATCH,
            &format!("/v9/guilds/{}/roles/{}", id, role_id),
            Some(role),
        )
        .await
    }
    pub async fn edit_role(
        &self,
        ctx: &mut MutexGuard<'_, Context>,
        role_id: Snowflake,
        role: Value,
    ) -> Result<Response> {
        Self::edit_role_static(ctx, self.id, role_id, role).await
    }

    pub async fn delete_role_static(
        ctx: &mut MutexGuard<'_, Context>,
        id: Snowflake,
        role_id: Snowflake,
    ) -> Result<Response> {
        ctx.request(
            Method::DELETE,
            &format!("/v9/guilds/{}/roles/{}", id, role_id),
            None,
        )
        .await
    }
    pub async fn delete_role(
        &self,
        ctx: &mut MutexGuard<'_, Context>,
        role_id: Snowflake,
    ) -> Result<Response> {
        Self::delete_role_static(ctx, self.id, role_id).await
    }

    pub async fn edit_role_positions_static(
        ctx: &mut MutexGuard<'_, Context>,
        id: Snowflake,
        roles: Value,
    ) -> Result<Response> {
        ctx.request(
            Method::PATCH,
            &format!("/v9/guilds/{}/roles", id),
            Some(roles),
        )
        .await
    }
    pub async fn edit_role_positions(
        &self,
        ctx: &mut MutexGuard<'_, Context>,
        roles: Value,
    ) -> Result<Response> {
        Self::edit_role_positions_static(ctx, self.id, roles).await
    }

    /**
     * Misc.
     */

    pub async fn fetch_invites_static(
        ctx: &mut MutexGuard<'_, Context>,
        id: Snowflake,
    ) -> Result<Response> {
        ctx.request(
            Method::GET,
            &format!("/v9/guilds/{}/invites", id),
            None,
        )
        .await
    }
    pub async fn fetch_invites(
        &self,
        ctx: &mut MutexGuard<'_, Context>,
    ) -> Result<Response> {
        Self::fetch_invites_static(ctx, self.id).await
    }

    pub async fn fetch_welcome_screen_static(
        ctx: &mut MutexGuard<'_, Context>,
        id: Snowflake,
    ) -> Result<Response> {
        ctx.request(
            Method::GET,
            &format!("/v9/guilds/{}/welcome-screen", id),
            None,
        )
        .await
    }
    pub async fn fetch_welcome_screen(
        &self,
        ctx: &mut MutexGuard<'_, Context>,
    ) -> Result<Response> {
        Self::fetch_welcome_screen_static(ctx, self.id).await
    }

    pub async fn fetch_onboarding_static(
        ctx: &mut MutexGuard<'_, Context>,
        id: Snowflake,
    ) -> Result<Response> {
        ctx.request(
            Method::GET,
            &format!("/v9/guilds/{}/onboarding", id),
            None,
        )
        .await
    }
    pub async fn fetch_onboarding(
        &self,
        ctx: &mut MutexGuard<'_, Context>,
    ) -> Result<Response> {
        Self::fetch_onboarding_static(ctx, self.id).await
    }

    pub async fn fetch_vanity_url_static(
        ctx: &mut MutexGuard<'_, Context>,
        id: Snowflake,
    ) -> Result<Response> {
        ctx.request(
            Method::GET,
            &format!("/v9/guilds/{}/vanity-url", id),
            None,
        )
        .await
    }
    pub async fn fetch_vanity_url(
        &self,
        ctx: &mut MutexGuard<'_, Context>,
    ) -> Result<Response> {
        Self::fetch_vanity_url_static(ctx, self.id).await
    }
}

#[derive(Deserialize, Serialize, Debug, Clone)]
pub struct CachedGuild {
    pub id: Snowflake,
    pub joined_at: Timestamp,

    pub properties: Guild, // Partial

    pub large: bool,
    pub lazy: bool,

    pub member_count: u64,
    #[serde(rename = "premium_subscription_count")]
    pub boosts: u64,

    #[serde(skip)]
    pub activity_instances: Option<()>, // TODO
    #[serde(skip)]
    pub application_command_counts: Option<()>, // TODO

    #[serde(skip)]
    pub stage_instances: Vec<()>, // TODO
    pub channels: Vec<Channel>,
    pub threads: Vec<Channel>,
    pub stickers: Vec<Sticker>,
    pub emojis: Vec<Emoji>,
    pub roles: Vec<Role>,

    pub data_mode: String,

    #[serde(skip)]
    pub guild_scheduled_events: Vec<()>, // TODO

    pub version: u64,
}

impl CachedGuild {
    pub async fn into_guild(self, ctx: &mut MutexGuard<'_, Context>) -> Result<Guild> {
        Ok(serde_json::from_value(
            Guild::fetch_guild(ctx, self.id).await?.body,
        )?)
    }
}

#[derive(Serialize_repr, Deserialize_repr, Debug)]
#[repr(u8)]
pub enum GuildMemberFlags {
    DidRejoin = 1 << 0,
    CompletedOnboarding = 1 << 1,
    BypassesVerification = 1 << 2,
    StartedOnboarding = 1 << 3,
}

#[derive(Deserialize, Serialize, Debug, Clone)]
pub struct GuildMember {
    pub user: Option<User>,
    pub nick: Option<String>,
    pub avatar: Option<String>,
    pub roles: Vec<Snowflake>,
    pub joined_at: Timestamp,
    pub premium_since: Option<Timestamp>,
    pub deaf: bool,
    pub mute: bool,
    pub flags: u8,
    pub pending: bool,
    pub permissions: String,
    pub communication_disabled_until: Option<Timestamp>,
    pub avatar_decoration_data: Option<AvatarDecorationData>,
}

#[derive(Deserialize, Serialize, Debug, Clone)]
pub struct GuildMemberEditBuilder {
    value: Value,
}

impl GuildMemberEditBuilder {
    pub fn new() -> Self {
        Self { value: json!({}) }
    }

    pub fn set_nick(&mut self, nick: String) {
        self.value["nick"] = json!(nick);
    }

    pub fn set_roles(&mut self, roles: Vec<Snowflake>) {
        self.value["roles"] = json!(roles);
    }

    pub fn set_deaf(&mut self, deaf: bool) {
        self.value["deaf"] = json!(deaf);
    }

    pub fn set_mute(&mut self, mute: bool) {
        self.value["mute"] = json!(mute);
    }

    pub fn set_voice_channel(&mut self, channel_id: Snowflake) {
        self.value["channel_id"] = json!(channel_id);
    }

    pub fn set_timeout(&mut self, timeout: Option<String>) {
        self.value["communication_disabled_until"] = json!(timeout);
    }

    pub fn build(self) -> Value {
        self.value
    }
}