forked from discordjs/discord.js
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Guild.js
1488 lines (1358 loc) · 45.6 KB
/
Guild.js
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
'use strict';
const { deprecate } = require('util');
const Base = require('./Base');
const GuildAuditLogs = require('./GuildAuditLogs');
const GuildPreview = require('./GuildPreview');
const GuildTemplate = require('./GuildTemplate');
const Integration = require('./Integration');
const Invite = require('./Invite');
const VoiceRegion = require('./VoiceRegion');
const Webhook = require('./Webhook');
const { Error, TypeError } = require('../errors');
const GuildChannelManager = require('../managers/GuildChannelManager');
const GuildEmojiManager = require('../managers/GuildEmojiManager');
const GuildMemberManager = require('../managers/GuildMemberManager');
const PresenceManager = require('../managers/PresenceManager');
const RoleManager = require('../managers/RoleManager');
const VoiceStateManager = require('../managers/VoiceStateManager');
const Collection = require('../util/Collection');
const {
ChannelTypes,
DefaultMessageNotifications,
PartialTypes,
VerificationLevels,
ExplicitContentFilterLevels,
} = require('../util/Constants');
const DataResolver = require('../util/DataResolver');
const Snowflake = require('../util/Snowflake');
const SystemChannelFlags = require('../util/SystemChannelFlags');
const Util = require('../util/Util');
/**
* Represents a guild (or a server) on Discord.
* <info>It's recommended to see if a guild is available before performing operations or reading data from it. You can
* check this with `guild.available`.</info>
* @extends {Base}
*/
class Guild extends Base {
/**
* @param {Client} client The instantiating client
* @param {Object} data The data for the guild
*/
constructor(client, data) {
super(client);
/**
* A manager of the members belonging to this guild
* @type {GuildMemberManager}
*/
this.members = new GuildMemberManager(this);
/**
* A manager of the channels belonging to this guild
* @type {GuildChannelManager}
*/
this.channels = new GuildChannelManager(this);
/**
* A manager of the roles belonging to this guild
* @type {RoleManager}
*/
this.roles = new RoleManager(this);
/**
* A manager of the presences belonging to this guild
* @type {PresenceManager}
*/
this.presences = new PresenceManager(this.client);
/**
* A manager of the voice states of this guild
* @type {VoiceStateManager}
*/
this.voiceStates = new VoiceStateManager(this);
/**
* Whether the bot has been removed from the guild
* @type {boolean}
*/
this.deleted = false;
if (!data) return;
if (data.unavailable) {
/**
* Whether the guild is available to access. If it is not available, it indicates a server outage
* @type {boolean}
*/
this.available = false;
/**
* The Unique ID of the guild, useful for comparisons
* @type {Snowflake}
*/
this.id = data.id;
} else {
this._patch(data);
if (!data.channels) this.available = false;
}
/**
* The id of the shard this Guild belongs to.
* @type {number}
*/
this.shardID = data.shardID;
}
/**
* The Shard this Guild belongs to.
* @type {WebSocketShard}
* @readonly
*/
get shard() {
return this.client.ws.shards.get(this.shardID);
}
/**
* Sets up the guild.
* @param {*} data The raw data of the guild
* @private
*/
_patch(data) {
/**
* The name of the guild
* @type {string}
*/
this.name = data.name;
/**
* The hash of the guild icon
* @type {?string}
*/
this.icon = data.icon;
/**
* The hash of the guild invite splash image
* @type {?string}
*/
this.splash = data.splash;
/**
* The hash of the guild discovery splash image
* @type {?string}
*/
this.discoverySplash = data.discovery_splash;
/**
* The region the guild is located in
* @type {string}
*/
this.region = data.region;
/**
* The full amount of members in this guild
* @type {number}
*/
this.memberCount = data.member_count || this.memberCount;
/**
* Whether the guild is "large" (has more than large_threshold members, 50 by default)
* @type {boolean}
*/
this.large = Boolean('large' in data ? data.large : this.large);
/**
* An array of enabled guild features, here are the possible values:
* * ANIMATED_ICON
* * BANNER
* * COMMERCE
* * COMMUNITY
* * DISCOVERABLE
* * FEATURABLE
* * INVITE_SPLASH
* * MEMBER_VERIFICATION_GATE_ENABLED
* * NEWS
* * PARTNERED
* * PREVIEW_ENABLED
* * RELAY_ENABLED
* * VANITY_URL
* * VERIFIED
* * VIP_REGIONS
* * WELCOME_SCREEN_ENABLED
* @typedef {string} Features
*/
/**
* An array of guild features partnered guilds have enabled
* @type {Features[]}
*/
this.features = data.features;
/**
* The ID of the application that created this guild (if applicable)
* @type {?Snowflake}
*/
this.applicationID = data.application_id;
/**
* The time in seconds before a user is counted as "away from keyboard"
* @type {?number}
*/
this.afkTimeout = data.afk_timeout;
/**
* The ID of the voice channel where AFK members are moved
* @type {?Snowflake}
*/
this.afkChannelID = data.afk_channel_id;
/**
* The ID of the system channel
* @type {?Snowflake}
*/
this.systemChannelID = data.system_channel_id;
/**
* The type of premium tier:
* * 0: NONE
* * 1: TIER_1
* * 2: TIER_2
* * 3: TIER_3
* @typedef {number} PremiumTier
*/
/**
* The premium tier on this guild
* @type {PremiumTier}
*/
this.premiumTier = data.premium_tier;
if (typeof data.premium_subscription_count !== 'undefined') {
/**
* The total number of boosts for this server
* @type {?number}
*/
this.premiumSubscriptionCount = data.premium_subscription_count;
}
if (typeof data.widget_enabled !== 'undefined') {
/**
* Whether widget images are enabled on this guild
* @type {?boolean}
*/
this.widgetEnabled = data.widget_enabled;
}
if (typeof data.widget_channel_id !== 'undefined') {
/**
* The widget channel ID, if enabled
* @type {?string}
*/
this.widgetChannelID = data.widget_channel_id;
}
/**
* The verification level of the guild
* @type {VerificationLevel}
*/
this.verificationLevel = VerificationLevels[data.verification_level];
/**
* The explicit content filter level of the guild
* @type {ExplicitContentFilterLevel}
*/
this.explicitContentFilter = ExplicitContentFilterLevels[data.explicit_content_filter];
/**
* The required MFA level for the guild
* @type {number}
*/
this.mfaLevel = data.mfa_level;
/**
* The timestamp the client user joined the guild at
* @type {number}
*/
this.joinedTimestamp = data.joined_at ? new Date(data.joined_at).getTime() : this.joinedTimestamp;
/**
* The value set for the guild's default message notifications
* @type {DefaultMessageNotifications|number}
*/
this.defaultMessageNotifications =
DefaultMessageNotifications[data.default_message_notifications] || data.default_message_notifications;
/**
* The value set for the guild's system channel flags
* @type {Readonly<SystemChannelFlags>}
*/
this.systemChannelFlags = new SystemChannelFlags(data.system_channel_flags).freeze();
if (typeof data.max_members !== 'undefined') {
/**
* The maximum amount of members the guild can have
* @type {?number}
*/
this.maximumMembers = data.max_members;
} else if (typeof this.maximumMembers === 'undefined') {
this.maximumMembers = null;
}
if (typeof data.max_presences !== 'undefined') {
/**
* The maximum amount of presences the guild can have
* <info>You will need to fetch the guild using {@link Guild#fetch} if you want to receive this parameter</info>
* @type {?number}
*/
this.maximumPresences = data.max_presences || 25000;
} else if (typeof this.maximumPresences === 'undefined') {
this.maximumPresences = null;
}
if (typeof data.approximate_member_count !== 'undefined') {
/**
* The approximate amount of members the guild has
* <info>You will need to fetch the guild using {@link Guild#fetch} if you want to receive this parameter</info>
* @type {?number}
*/
this.approximateMemberCount = data.approximate_member_count;
} else if (typeof this.approximateMemberCount === 'undefined') {
this.approximateMemberCount = null;
}
if (typeof data.approximate_presence_count !== 'undefined') {
/**
* The approximate amount of presences the guild has
* <info>You will need to fetch the guild using {@link Guild#fetch} if you want to receive this parameter</info>
* @type {?number}
*/
this.approximatePresenceCount = data.approximate_presence_count;
} else if (typeof this.approximatePresenceCount === 'undefined') {
this.approximatePresenceCount = null;
}
/**
* The vanity invite code of the guild, if any
* @type {?string}
*/
this.vanityURLCode = data.vanity_url_code;
/* eslint-disable max-len */
/**
* The use count of the vanity URL code of the guild, if any
* <info>You will need to fetch this parameter using {@link Guild#fetchVanityData} if you want to receive it</info>
* @type {?number}
*/
this.vanityURLUses = null;
/* eslint-enable max-len */
/**
* The description of the guild, if any
* @type {?string}
*/
this.description = data.description;
/**
* The hash of the guild banner
* @type {?string}
*/
this.banner = data.banner;
this.id = data.id;
this.available = !data.unavailable;
this.features = data.features || this.features || [];
/**
* The ID of the rules channel for the guild
* @type {?Snowflake}
*/
this.rulesChannelID = data.rules_channel_id;
/**
* The ID of the community updates channel for the guild
* @type {?Snowflake}
*/
this.publicUpdatesChannelID = data.public_updates_channel_id;
/**
* The preferred locale of the guild, defaults to `en-US`
* @type {string}
*/
this.preferredLocale = data.preferred_locale;
if (data.channels) {
this.channels.cache.clear();
for (const rawChannel of data.channels) {
this.client.channels.add(rawChannel, this);
}
}
if (data.roles) {
this.roles.cache.clear();
for (const role of data.roles) this.roles.add(role);
}
if (data.members) {
this.members.cache.clear();
for (const guildUser of data.members) this.members.add(guildUser);
}
if (data.owner_id) {
/**
* The user ID of this guild's owner
* @type {Snowflake}
*/
this.ownerID = data.owner_id;
}
if (data.presences) {
for (const presence of data.presences) {
this.presences.add(Object.assign(presence, { guild: this }));
}
}
if (data.voice_states) {
this.voiceStates.cache.clear();
for (const voiceState of data.voice_states) {
this.voiceStates.add(voiceState);
}
}
if (!this.emojis) {
/**
* A manager of the emojis belonging to this guild
* @type {GuildEmojiManager}
*/
this.emojis = new GuildEmojiManager(this);
if (data.emojis) for (const emoji of data.emojis) this.emojis.add(emoji);
} else if (data.emojis) {
this.client.actions.GuildEmojisUpdate.handle({
guild_id: this.id,
emojis: data.emojis,
});
}
}
/**
* The URL to this guild's banner.
* @param {ImageURLOptions} [options={}] Options for the Image URL
* @returns {?string}
*/
bannerURL({ format, size } = {}) {
if (!this.banner) return null;
return this.client.rest.cdn.Banner(this.id, this.banner, format, size);
}
/**
* The timestamp the guild was created at
* @type {number}
* @readonly
*/
get createdTimestamp() {
return Snowflake.deconstruct(this.id).timestamp;
}
/**
* The time the guild was created at
* @type {Date}
* @readonly
*/
get createdAt() {
return new Date(this.createdTimestamp);
}
/**
* The time the client user joined the guild
* @type {Date}
* @readonly
*/
get joinedAt() {
return new Date(this.joinedTimestamp);
}
/**
* If this guild is partnered
* @type {boolean}
* @readonly
*/
get partnered() {
return this.features.includes('PARTNERED');
}
/**
* If this guild is verified
* @type {boolean}
* @readonly
*/
get verified() {
return this.features.includes('VERIFIED');
}
/**
* The URL to this guild's icon.
* @param {ImageURLOptions} [options={}] Options for the Image URL
* @returns {?string}
*/
iconURL({ format, size, dynamic } = {}) {
if (!this.icon) return null;
return this.client.rest.cdn.Icon(this.id, this.icon, format, size, dynamic);
}
/**
* The acronym that shows up in place of a guild icon.
* @type {string}
* @readonly
*/
get nameAcronym() {
return this.name
.replace(/'s /g, ' ')
.replace(/\w+/g, e => e[0])
.replace(/\s/g, '');
}
/**
* The URL to this guild's invite splash image.
* @param {ImageURLOptions} [options={}] Options for the Image URL
* @returns {?string}
*/
splashURL({ format, size } = {}) {
if (!this.splash) return null;
return this.client.rest.cdn.Splash(this.id, this.splash, format, size);
}
/**
* The URL to this guild's discovery splash image.
* @param {ImageURLOptions} [options={}] Options for the Image URL
* @returns {?string}
*/
discoverySplashURL({ format, size } = {}) {
if (!this.discoverySplash) return null;
return this.client.rest.cdn.DiscoverySplash(this.id, this.discoverySplash, format, size);
}
/**
* The owner of the guild
* @type {?GuildMember}
* @readonly
*/
get owner() {
return (
this.members.cache.get(this.ownerID) ||
(this.client.options.partials.includes(PartialTypes.GUILD_MEMBER)
? this.members.add({ user: { id: this.ownerID } }, true)
: null)
);
}
/**
* AFK voice channel for this guild
* @type {?VoiceChannel}
* @readonly
*/
get afkChannel() {
return this.client.channels.cache.get(this.afkChannelID) || null;
}
/**
* System channel for this guild
* @type {?TextChannel}
* @readonly
*/
get systemChannel() {
return this.client.channels.cache.get(this.systemChannelID) || null;
}
/**
* Widget channel for this guild
* @type {?TextChannel}
* @readonly
*/
get widgetChannel() {
return this.client.channels.cache.get(this.widgetChannelID) || null;
}
/**
* Rules channel for this guild
* @type {?TextChannel}
* @readonly
*/
get rulesChannel() {
return this.client.channels.cache.get(this.rulesChannelID) || null;
}
/**
* Public updates channel for this guild
* @type {?TextChannel}
* @readonly
*/
get publicUpdatesChannel() {
return this.client.channels.cache.get(this.publicUpdatesChannelID) || null;
}
/**
* The client user as a GuildMember of this guild
* @type {?GuildMember}
* @readonly
*/
get me() {
return (
this.members.cache.get(this.client.user.id) ||
(this.client.options.partials.includes(PartialTypes.GUILD_MEMBER)
? this.members.add({ user: { id: this.client.user.id } }, true)
: null)
);
}
/**
* Fetches this guild.
* @returns {Promise<Guild>}
*/
fetch() {
return this.client.api
.guilds(this.id)
.get({ query: { with_counts: true } })
.then(data => {
this._patch(data);
return this;
});
}
/**
* An object containing information about a guild member's ban.
* @typedef {Object} BanInfo
* @property {User} user User that was banned
* @property {?string} reason Reason the user was banned
*/
/**
* Fetches information on a banned user from this guild.
* @param {UserResolvable} user The User to fetch the ban info of
* @returns {Promise<BanInfo>}
*/
fetchBan(user) {
const id = this.client.users.resolveID(user);
if (!id) throw new Error('FETCH_BAN_RESOLVE_ID');
return this.client.api
.guilds(this.id)
.bans(id)
.get()
.then(ban => ({
reason: ban.reason,
user: this.client.users.add(ban.user),
}));
}
/**
* Fetches a collection of banned users in this guild.
* @returns {Promise<Collection<Snowflake, BanInfo>>}
*/
fetchBans() {
return this.client.api
.guilds(this.id)
.bans.get()
.then(bans =>
bans.reduce((collection, ban) => {
collection.set(ban.user.id, {
reason: ban.reason,
user: this.client.users.add(ban.user),
});
return collection;
}, new Collection()),
);
}
/**
* Fetches a collection of integrations to this guild.
* Resolves with a collection mapping integrations by their ids.
* @returns {Promise<Collection<string, Integration>>}
* @example
* // Fetch integrations
* guild.fetchIntegrations()
* .then(integrations => console.log(`Fetched ${integrations.size} integrations`))
* .catch(console.error);
*/
async fetchIntegrations() {
const data = await this.client.api.guilds(this.id).integrations.get();
return data.reduce(
(collection, integration) => collection.set(integration.id, new Integration(this.client, integration, this)),
new Collection(),
);
}
/**
* Fetches a collection of templates from this guild.
* Resolves with a collection mapping templates by their codes.
* @returns {Promise<Collection<string, GuildTemplate>>}
*/
fetchTemplates() {
return this.client.api
.guilds(this.id)
.templates.get()
.then(templates =>
templates.reduce((col, data) => col.set(data.code, new GuildTemplate(this.client, data)), new Collection()),
);
}
/**
* The data for creating an integration.
* @typedef {Object} IntegrationData
* @property {string} id The integration id
* @property {string} type The integration type
*/
/**
* Creates an integration by attaching an integration object
* @param {IntegrationData} data The data for the integration
* @param {string} reason Reason for creating the integration
* @returns {Promise<Guild>}
*/
createIntegration(data, reason) {
return this.client.api
.guilds(this.id)
.integrations.post({ data, reason })
.then(() => this);
}
/**
* Creates a template for the guild.
* @param {string} name The name for the template
* @param {string} [description] The description for the template
* @returns {Promise<GuildTemplate>}
*/
createTemplate(name, description) {
return this.client.api
.guilds(this.id)
.templates.post({ data: { name, description } })
.then(data => new GuildTemplate(this.client, data));
}
/**
* Fetches a collection of invites to this guild.
* Resolves with a collection mapping invites by their codes.
* @returns {Promise<Collection<string, Invite>>}
* @example
* // Fetch invites
* guild.fetchInvites()
* .then(invites => console.log(`Fetched ${invites.size} invites`))
* .catch(console.error);
* @example
* // Fetch invite creator by their id
* guild.fetchInvites()
* .then(invites => console.log(invites.find(invite => invite.inviter.id === '84484653687267328')))
* .catch(console.error);
*/
fetchInvites() {
return this.client.api
.guilds(this.id)
.invites.get()
.then(inviteItems => {
const invites = new Collection();
for (const inviteItem of inviteItems) {
const invite = new Invite(this.client, inviteItem);
invites.set(invite.code, invite);
}
return invites;
});
}
/**
* Obtains a guild preview for this guild from Discord.
* @returns {Promise<GuildPreview>}
*/
fetchPreview() {
return this.client.api
.guilds(this.id)
.preview.get()
.then(data => new GuildPreview(this.client, data));
}
/**
* Fetches the vanity url invite code to this guild.
* Resolves with a string matching the vanity url invite code, not the full url.
* @returns {Promise<string>}
* @deprecated
* @example
* // Fetch invites
* guild.fetchVanityCode()
* .then(code => {
* console.log(`Vanity URL: https://discord.gg/${code}`);
* })
* .catch(console.error);
*/
fetchVanityCode() {
return this.fetchVanityData().then(vanity => vanity.code);
}
/**
* An object containing information about a guild's vanity invite.
* @typedef {Object} Vanity
* @property {?string} code Vanity invite code
* @property {?number} uses How many times this invite has been used
*/
/**
* Fetches the vanity url invite object to this guild.
* Resolves with an object containing the vanity url invite code and the use count
* @returns {Promise<Vanity>}
* @example
* // Fetch invite data
* guild.fetchVanityData()
* .then(res => {
* console.log(`Vanity URL: https://discord.gg/${res.code} with ${res.uses} uses`);
* })
* .catch(console.error);
*/
async fetchVanityData() {
if (!this.features.includes('VANITY_URL')) {
throw new Error('VANITY_URL');
}
const data = await this.client.api.guilds(this.id, 'vanity-url').get();
this.vanityURLUses = data.uses;
return data;
}
/**
* Fetches all webhooks for the guild.
* @returns {Promise<Collection<Snowflake, Webhook>>}
* @example
* // Fetch webhooks
* guild.fetchWebhooks()
* .then(webhooks => console.log(`Fetched ${webhooks.size} webhooks`))
* .catch(console.error);
*/
fetchWebhooks() {
return this.client.api
.guilds(this.id)
.webhooks.get()
.then(data => {
const hooks = new Collection();
for (const hook of data) hooks.set(hook.id, new Webhook(this.client, hook));
return hooks;
});
}
/**
* Fetches available voice regions.
* @returns {Promise<Collection<string, VoiceRegion>>}
*/
fetchVoiceRegions() {
return this.client.api
.guilds(this.id)
.regions.get()
.then(res => {
const regions = new Collection();
for (const region of res) regions.set(region.id, new VoiceRegion(region));
return regions;
});
}
/**
* Data for the Guild Widget object
* @typedef {Object} GuildWidget
* @property {boolean} enabled Whether the widget is enabled
* @property {?GuildChannel} channel The widget channel
*/
/**
* The Guild Widget object
* @typedef {Object} GuildWidgetData
* @property {boolean} enabled Whether the widget is enabled
* @property {?GuildChannelResolvable} channel The widget channel
*/
/**
* Fetches the guild widget.
* @returns {Promise<GuildWidget>}
* @example
* // Fetches the guild widget
* guild.fetchWidget()
* .then(widget => console.log(`The widget is ${widget.enabled ? 'enabled' : 'disabled'}`))
* .catch(console.error);
*/
async fetchWidget() {
const data = await this.client.api.guilds(this.id).widget.get();
this.widgetEnabled = data.enabled;
this.widgetChannelID = data.channel_id;
return {
enabled: data.enabled,
channel: data.channel_id ? this.channels.cache.get(data.channel_id) : null,
};
}
/**
* Fetches audit logs for this guild.
* @param {Object} [options={}] Options for fetching audit logs
* @param {Snowflake|GuildAuditLogsEntry} [options.before] Limit to entries from before specified entry
* @param {number} [options.limit] Limit number of entries
* @param {UserResolvable} [options.user] Only show entries involving this user
* @param {AuditLogAction|number} [options.type] Only show entries involving this action type
* @returns {Promise<GuildAuditLogs>}
* @example
* // Output audit log entries
* guild.fetchAuditLogs()
* .then(audit => console.log(audit.entries.first()))
* .catch(console.error);
*/
fetchAuditLogs(options = {}) {
if (options.before && options.before instanceof GuildAuditLogs.Entry) options.before = options.before.id;
if (typeof options.type === 'string') options.type = GuildAuditLogs.Actions[options.type];
return this.client.api
.guilds(this.id)
['audit-logs'].get({
query: {
before: options.before,
limit: options.limit,
user_id: this.client.users.resolveID(options.user),
action_type: options.type,
},
})
.then(data => GuildAuditLogs.build(this, data));
}
/**
* Adds a user to the guild using OAuth2. Requires the `CREATE_INSTANT_INVITE` permission.
* @param {UserResolvable} user User to add to the guild
* @param {Object} options Options for the addition
* @param {string} options.accessToken An OAuth2 access token for the user with the `guilds.join` scope granted to the
* bot's application
* @param {string} [options.nick] Nickname to give the member (requires `MANAGE_NICKNAMES`)
* @param {Collection<Snowflake, Role>|RoleResolvable[]} [options.roles] Roles to add to the member
* (requires `MANAGE_ROLES`)
* @param {boolean} [options.mute] Whether the member should be muted (requires `MUTE_MEMBERS`)
* @param {boolean} [options.deaf] Whether the member should be deafened (requires `DEAFEN_MEMBERS`)
* @returns {Promise<GuildMember>}
*/
async addMember(user, options) {
user = this.client.users.resolveID(user);
if (!user) throw new TypeError('INVALID_TYPE', 'user', 'UserResolvable');
if (this.members.cache.has(user)) return this.members.cache.get(user);
options.access_token = options.accessToken;
if (options.roles) {
const roles = [];
for (let role of options.roles instanceof Collection ? options.roles.values() : options.roles) {
role = this.roles.resolve(role);
if (!role) {
throw new TypeError('INVALID_TYPE', 'options.roles', 'Array or Collection of Roles or Snowflakes', true);
}
roles.push(role.id);
}
options.roles = roles;
}
const data = await this.client.api.guilds(this.id).members(user).put({ data: options });
// Data is an empty buffer if the member is already part of the guild.
return data instanceof Buffer ? this.members.fetch(user) : this.members.add(data);
}
/**
* The data for editing a guild.
* @typedef {Object} GuildEditData
* @property {string} [name] The name of the guild
* @property {string} [region] The region of the guild
* @property {VerificationLevel|number} [verificationLevel] The verification level of the guild
* @property {ExplicitContentFilterLevel|number} [explicitContentFilter] The level of the explicit content filter
* @property {ChannelResolvable} [afkChannel] The AFK channel of the guild
* @property {ChannelResolvable} [systemChannel] The system channel of the guild
* @property {number} [afkTimeout] The AFK timeout of the guild
* @property {Base64Resolvable} [icon] The icon of the guild
* @property {GuildMemberResolvable} [owner] The owner of the guild
* @property {Base64Resolvable} [splash] The invite splash image of the guild
* @property {Base64Resolvable} [discoverySplash] The discovery splash image of the guild
* @property {Base64Resolvable} [banner] The banner of the guild
* @property {DefaultMessageNotifications|number} [defaultMessageNotifications] The default message notifications
* @property {SystemChannelFlagsResolvable} [systemChannelFlags] The system channel flags of the guild
* @property {ChannelResolvable} [rulesChannel] The rules channel of the guild
* @property {ChannelResolvable} [publicUpdatesChannel] The community updates channel of the guild
* @property {string} [preferredLocale] The preferred locale of the guild
*/
/**
* Updates the guild with new information - e.g. a new name.
* @param {GuildEditData} data The data to update the guild with
* @param {string} [reason] Reason for editing this guild
* @returns {Promise<Guild>}
* @example
* // Set the guild name and region
* guild.edit({
* name: 'Discord Guild',
* region: 'london',
* })
* .then(updated => console.log(`New guild name ${updated} in region ${updated.region}`))
* .catch(console.error);
*/
edit(data, reason) {
const _data = {};
if (data.name) _data.name = data.name;
if (data.region) _data.region = data.region;
if (typeof data.verificationLevel !== 'undefined') {
_data.verification_level =
typeof data.verificationLevel === 'number'
? Number(data.verificationLevel)
: VerificationLevels.indexOf(data.verificationLevel);
}
if (typeof data.afkChannel !== 'undefined') {
_data.afk_channel_id = this.client.channels.resolveID(data.afkChannel);
}
if (typeof data.systemChannel !== 'undefined') {
_data.system_channel_id = this.client.channels.resolveID(data.systemChannel);
}
if (data.afkTimeout) _data.afk_timeout = Number(data.afkTimeout);