This repository has been archived by the owner on Jul 11, 2024. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 70
/
guild.go
1848 lines (1582 loc) · 56.8 KB
/
guild.go
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
package disgord
import (
"context"
"errors"
"fmt"
"math"
"net/http"
"strconv"
"github.com/andersfylling/disgord/json"
"github.com/andersfylling/disgord/internal/endpoint"
"github.com/andersfylling/disgord/internal/httd"
)
// NOTE! Credit for defining the Permission consts in a clean way goes to DiscordGo.
// This is pretty much a copy from their project. I would have made it a dependency if
// the consts were in a isolated sub-pkg. Note that in respect to their license, Disgord
// has no affiliation with DiscordGo.
//
// Source code reference:
// https://github.com/bwmarrin/discordgo/blob/8325a6bf6dd6c91ed4040a1617b07287b8fb0eba/structs.go#L854
// PermissionBit is used to define the permission bit(s) which are set.
type PermissionBit uint64
var _ json.Unmarshaler = (*PermissionBit)(nil)
var _ json.Marshaler = (*PermissionBit)(nil)
func (b *PermissionBit) MarshalJSON() ([]byte, error) {
str := strconv.FormatUint(uint64(*b), 10)
return []byte(strconv.Quote(str)), nil
}
func (b *PermissionBit) UnmarshalJSON(bytes []byte) error {
sb := string(bytes)
str, err := strconv.Unquote(sb)
if err != nil {
return fmt.Errorf("PermissionBit#UnmarshalJSON - unable to unquote bytes{%s}: %w", sb, err)
}
v, err := strconv.ParseUint(str, 10, 64)
if err != nil {
return fmt.Errorf("PermissionBit#UnmarshalJSON - parsing string to uint64 failed: %w", err)
}
*b = PermissionBit(v)
return nil
}
// Contains is used to check if the permission bits contains the bits specified.
func (b PermissionBit) Contains(Bits PermissionBit) bool {
return (b & Bits) == Bits
}
// Constants for the different bit offsets of text channel permissions
const (
PermissionReadMessages PermissionBit = 1 << (iota + 10)
PermissionSendMessages
PermissionSendTTSMessages
PermissionManageMessages
PermissionEmbedLinks
PermissionAttachFiles
PermissionReadMessageHistory
PermissionMentionEveryone
PermissionUseExternalEmojis
PermissionViewGuildInsights
)
// Constants for the different bit offsets of voice permissions
const (
PermissionVoiceConnect PermissionBit = 1 << (iota + 20)
PermissionVoiceSpeak
PermissionVoiceMuteMembers
PermissionVoiceDeafenMembers
PermissionVoiceMoveMembers
PermissionVoiceUseVAD
PermissionVoicePrioritySpeaker PermissionBit = 1 << (iota + 2)
PermissionVoiceStream
)
// Constants for general management.
const (
PermissionChangeNickname PermissionBit = 1 << (iota + 26)
PermissionManageNicknames
PermissionManageRoles
PermissionManageWebhooks
PermissionManageEmojis
_
_
PermissionManageEvents
PermissionManageThreads
PermissionCreatePublicThreads
PermissionCreatePrivateThreads
PermissionUseExternalStickers
PermissionSendMessagesInThreads
PermissionUseEmbeddedActivites
// This is technically called MODERATE_MEMBERS in the docs, but I think that would make it confusing, as managing roles
// and banning and stuff could also be moderating
PermissionTimeoutMembers
)
// Constants for the different bit offsets of general permissions
const (
PermissionCreateInstantInvite PermissionBit = 1 << iota
PermissionKickMembers
PermissionBanMembers
PermissionAdministrator
PermissionManageChannels
PermissionManageServer
PermissionAddReactions
PermissionViewAuditLogs
_
PermissionViewChannel
PermissionTextAll = PermissionReadMessages |
PermissionSendMessages |
PermissionSendTTSMessages |
PermissionManageMessages |
PermissionEmbedLinks |
PermissionAttachFiles |
PermissionReadMessageHistory |
PermissionMentionEveryone |
PermissionUseExternalEmojis |
PermissionViewGuildInsights |
PermissionUseExternalStickers | PermissionUseSlashCommands
PermissionVoiceAll = PermissionVoiceConnect |
PermissionVoiceSpeak |
PermissionVoiceMuteMembers |
PermissionVoiceDeafenMembers |
PermissionVoiceMoveMembers |
PermissionVoiceUseVAD |
PermissionVoicePrioritySpeaker |
PermissionVoiceStream |
PermissionUseEmbeddedActivites
PermissionChannelAll = PermissionTextAll |
PermissionCreateInstantInvite |
PermissionAddReactions |
PermissionViewAuditLogs |
PermissionViewChannel |
PermissionSendMessagesInThreads |
PermissionCreatePublicThreads |
PermissionCreatePrivateThreads
// I don't really think changing your own nickname counts as management but I don't want to create a whole new catergory.
// Also idk if some sort of system was being followed when doing this or if it's just based on opinion
PermissionManagementAll = PermissionManageRoles |
PermissionManageChannels | PermissionKickMembers |
PermissionBanMembers |
PermissionManageServer |
PermissionAdministrator |
PermissionChangeNickname |
PermissionManageNicknames |
PermissionManageWebhooks |
PermissionManageEmojis |
PermissionManageEvents |
PermissionManageThreads |
PermissionTimeoutMembers
PermissionAll = PermissionTextAll |
PermissionVoiceAll |
PermissionChannelAll |
PermissionManagementAll
)
const (
PermissionUseSlashCommands PermissionBit = 2147483648
// Down here cause according to discord docs: "(This permission is under active development and may be changed or removed.)"
PermissionRequestToSpeak PermissionBit = 1 << 32
)
// GuildUnavailable is a partial Guild object.
type GuildUnavailable struct {
ID Snowflake `json:"id"`
Unavailable bool `json:"unavailable"` // ?*|
}
// Guild Guilds in Discord represent an isolated collection of Users and Channels,
//
// and are often referred to as "servers" in the UI.
//
// https://discord.com/developers/docs/resources/guild#guild-object
// Fields with `*` are only sent within the GUILD_CREATE event
// reviewed: 2018-08-25
type Guild struct {
ID Snowflake `json:"id"`
ApplicationID Snowflake `json:"application_id"` // |?
Name string `json:"name"`
Icon string `json:"icon"` // |?, icon hash
Splash string `json:"splash"` // |?, image hash
Owner bool `json:"owner,omitempty"` // ?|
OwnerID Snowflake `json:"owner_id"`
Permissions PermissionBit `json:"permissions,omitempty"` // ?|, permission flags for connected user `/users/@me/guilds`
Region string `json:"region"`
AfkChannelID Snowflake `json:"afk_channel_id"` // |?
AfkTimeout uint `json:"afk_timeout"`
VerificationLevel VerificationLvl `json:"verification_level"`
DefaultMessageNotifications DefaultMessageNotificationLvl `json:"default_message_notifications"`
ExplicitContentFilter ExplicitContentFilterLvl `json:"explicit_content_filter"`
Roles []*Role `json:"roles"`
Emojis []*Emoji `json:"emojis"`
Features []string `json:"features"`
MFALevel MFALvl `json:"mfa_level"`
WidgetEnabled bool `json:"widget_enabled,omit_empty"` // |
WidgetChannelID Snowflake `json:"widget_channel_id,omit_empty"` // |?
SystemChannelID Snowflake `json:"system_channel_id,omitempty"` // |?
DiscoverySplash string `json:"discovery_splash,omitempty"`
VanityUrl string `json:"vanity_url_code,omitempty"`
Description string `json:"description,omitempty"`
Banner string `json:"banner,omitempty"`
PremiumTier PremiumTier `json:"premium_tier"`
PremiumSubscriptionCount uint `json:"premium_subscription_count,omitempty"`
// JoinedAt must be a pointer, as we can't hide non-nil structs
JoinedAt *Time `json:"joined_at,omitempty"` // ?*|
Large bool `json:"large,omitempty"` // ?*|
Unavailable bool `json:"unavailable"` // ?*| omitempty?
MemberCount uint `json:"member_count,omitempty"` // ?*|
VoiceStates []*VoiceState `json:"voice_states,omitempty"` // ?*|
Members []*Member `json:"members,omitempty"` // ?*|
Channels []*Channel `json:"channels,omitempty"` // ?*|
Presences []*UserPresence `json:"presences,omitempty"` // ?*|
}
var _ Reseter = (*Guild)(nil)
var _ fmt.Stringer = (*Guild)(nil)
var _ Copier = (*Guild)(nil)
var _ DeepCopier = (*Guild)(nil)
var _ internalUpdater = (*Guild)(nil)
func (g *Guild) String() string {
return g.Name + "{" + g.ID.String() + "}"
}
func (g *Guild) updateInternals() {
for i := range g.Roles {
g.Roles[i].guildID = g.ID
}
for i := range g.Channels {
g.Channels[i].GuildID = g.ID
}
for i := range g.Members {
g.Members[i].GuildID = g.ID
g.Members[i].updateInternals()
}
}
// GetMemberWithHighestSnowflake finds the member with the highest snowflake value.
func (g *Guild) GetMemberWithHighestSnowflake() *Member {
if len(g.Members) == 0 {
return nil
}
highest := g.Members[0]
for _, member := range g.Members {
if member.User.ID > highest.User.ID {
highest = member
}
}
return highest
}
// sortChannels Only while in lock
func (g *Guild) sortChannels() {
Sort(g.Channels, SortByID)
}
// AddChannel adds a channel to the Guild object. Note that this method does not interact with Discord.
func (g *Guild) AddChannel(c *Channel) error {
g.Channels = append(g.Channels, c)
g.sortChannels()
return nil
}
// DeleteChannel removes a channel from the Guild object. Note that this method does not interact with Discord.
func (g *Guild) DeleteChannel(c *Channel) error {
return g.DeleteChannelByID(c.ID)
}
// DeleteChannelByID removes a channel from the Guild object. Note that this method does not interact with Discord.
func (g *Guild) DeleteChannelByID(ID Snowflake) error {
index := -1
for i, c := range g.Channels {
if c.ID == ID {
index = i
}
}
if index == -1 {
return errors.New("channel with Snowflake{" + ID.String() + "} does not exist in cacheLink")
}
// delete the entry
copy(g.Channels[index:], g.Channels[index+1:])
g.Channels[len(g.Channels)-1] = nil // or the zero value of T
g.Channels = g.Channels[:len(g.Channels)-1]
return nil
}
func (g *Guild) hasMember(id Snowflake) bool {
for i := len(g.Members) - 1; i >= 0; i-- {
if g.Members[i].UserID == id {
return true
}
}
return false
}
func (g *Guild) addMembers(members ...*Member) {
// TODO: implement sorting for faster searching later
g.Members = append(g.Members, members...)
}
// AddMembers adds multiple members to the Guild object. Note that this method does not interact with Discord.
func (g *Guild) AddMembers(members []*Member) {
// Reduces allocations
membersToAdd := members[:0]
for _, member := range members {
// TODO: Check for UserID.IsZero()
if !g.hasMember(member.UserID) {
membersToAdd = append(membersToAdd, member)
}
}
g.addMembers(membersToAdd...)
}
// AddMember adds a member to the Guild object. Note that this method does not interact with Discord.
func (g *Guild) AddMember(member *Member) error {
// TODO: Check for UserID.IsZero()
if !g.hasMember(member.UserID) {
g.addMembers(member)
}
return nil
}
// GetMembersCountEstimate estimates the number of members in a guild without fetching everyone.
// There is no proper way to get this number, so a invite is created and the estimate
// is read from there. The invite is then deleted again.
func (g *Guild) GetMembersCountEstimate(ctx context.Context, s Session) (estimate int, err error) {
var channelID Snowflake
if len(g.Channels) == 0 {
channels, err := s.Guild(g.ID).WithContext(ctx).GetChannels()
if err != nil {
return 0, err
}
for i := range channels {
channelID = channels[i].ID
// prefer the main channel
if channelID == g.ID {
break
}
}
// TODO: update g.Channels
}
if channelID.IsZero() {
return 0, ErrMissingChannelID
}
invite, err := s.Channel(channelID).WithContext(ctx).CreateInvite(&CreateInvite{
MaxAge: 1,
})
if err != nil {
return 0, err
}
_, _ = s.Invite(invite.Code).WithContext(ctx).Delete() // delete if possible
return invite.ApproximateMemberCount, nil
}
// AddRole adds a role to the Guild object. Note that this does not interact with Discord.
func (g *Guild) AddRole(role *Role) error {
// TODO: implement sorting for faster searching later
role.guildID = g.ID
g.Roles = append(g.Roles, role)
return nil
}
// Member return a member by his/her userid
func (g *Guild) Member(id Snowflake) (*Member, error) {
for _, member := range g.Members {
if member.UserID == id {
return member, nil
}
}
return nil, errors.New("member not found in guild")
}
// MembersByName retrieve a slice of members with same username or nickname
// Will skip checking username of members missing user data.
// The user data might be missing due to cache misses.
func (g *Guild) MembersByName(name string) (members []*Member) {
for _, member := range g.Members {
if member.Nick == name || (member.User != nil && member.User.Username == name) {
members = append(members, member)
}
}
return
}
// Role retrieve a role based on role id
func (g *Guild) Role(id Snowflake) (*Role, error) {
for _, role := range g.Roles {
if role.ID == id {
return role, nil
}
}
return nil, errors.New("role not found in guild")
}
// DeleteRoleByID remove a role from the guild struct
func (g *Guild) DeleteRoleByID(ID Snowflake) {
index := -1
for i, r := range g.Roles {
if r.ID == ID {
index = i
break
}
}
if index != -1 {
// delete the entry
g.Roles[index] = g.Roles[len(g.Roles)-1]
g.Roles[len(g.Roles)-1] = nil
g.Roles = g.Roles[:len(g.Roles)-1]
}
}
// RoleByName retrieves a slice of roles with same name
func (g *Guild) RoleByName(name string) ([]*Role, error) {
var roles []*Role
for _, role := range g.Roles {
if role.Name == name {
roles = append(roles, role)
}
}
if len(roles) == 0 {
return nil, errors.New("no roles were found in guild")
}
return roles, nil
}
// Channel get a guild channel given it's ID
func (g *Guild) Channel(id Snowflake) (*Channel, error) {
for _, channel := range g.Channels {
if channel.ID == id {
return channel, nil
}
}
return nil, errors.New("channel not found in guild")
}
// Emoji get a guild emoji by it's ID
func (g *Guild) Emoji(id Snowflake) (emoji *Emoji, err error) {
for _, emoji = range g.Emojis {
if emoji.ID == id {
return
}
}
err = errors.New("emoji not found in guild")
return
}
// --------------
// PartialBan is used by audit logs
type PartialBan struct {
Reason string
BannedUserID Snowflake
ModeratorResponsibleID Snowflake
}
var _ fmt.Stringer = (*PartialBan)(nil)
func (p *PartialBan) String() string {
return fmt.Sprintf("mod{%d} banned member{%d}, reason: %s.", p.ModeratorResponsibleID, p.BannedUserID, p.Reason)
}
// Ban https://discord.com/developers/docs/resources/guild#ban-object
type Ban struct {
Reason string `json:"reason"`
User *User `json:"user"`
}
var _ Copier = (*Ban)(nil)
var _ DeepCopier = (*Ban)(nil)
// ------------
// GuildEmbed https://discord.com/developers/docs/resources/guild#guild-embed-object
type GuildWidget struct {
Enabled bool `json:"enabled"`
ChannelID Snowflake `json:"channel_id"`
}
var _ Copier = (*GuildWidget)(nil)
var _ DeepCopier = (*GuildWidget)(nil)
// -------
// Integration https://discord.com/developers/docs/resources/guild#integration-object
type Integration struct {
ID Snowflake `json:"id"`
Name string `json:"name"`
Type string `json:"type"`
Enabled bool `json:"enabled"`
Syncing bool `json:"syncing"`
RoleID Snowflake `json:"role_id"`
ExpireBehavior int `json:"expire_behavior"`
ExpireGracePeriod int `json:"expire_grace_period"`
User *User `json:"user"`
Account *IntegrationAccount `json:"account"`
}
var _ Copier = (*Integration)(nil)
var _ DeepCopier = (*Integration)(nil)
// IntegrationAccount https://discord.com/developers/docs/resources/guild#integration-account-object
type IntegrationAccount struct {
ID string `json:"id"` // id of the account
Name string `json:"name"` // name of the account
}
var _ Copier = (*IntegrationAccount)(nil)
var _ DeepCopier = (*IntegrationAccount)(nil)
// -------
// Member https://discord.com/developers/docs/resources/guild#guild-member-object
type Member struct {
GuildID Snowflake `json:"guild_id,omitempty"`
User *User `json:"user"`
Nick string `json:"nick,omitempty"`
Roles []Snowflake `json:"roles"`
JoinedAt Time `json:"joined_at,omitempty"`
PremiumSince Time `json:"premium_since,omitempty"`
CommunicationDisabledUntil Time `json:"communication_disabled_until"`
Deaf bool `json:"deaf"`
Mute bool `json:"mute"`
Pending bool `json:"pending"`
// custom
UserID Snowflake `json:"-"`
}
var _ Reseter = (*Member)(nil)
var _ fmt.Stringer = (*Member)(nil)
var _ internalUpdater = (*Member)(nil)
var _ Mentioner = (*Member)(nil)
var _ Copier = (*Member)(nil)
var _ DeepCopier = (*Member)(nil)
func (m *Member) updateInternals() {
if m.User != nil {
m.UserID = m.User.ID
}
}
func (m *Member) String() string {
username := m.Nick
if m.User != nil {
username = m.User.Username
}
id := m.UserID
if m.UserID.IsZero() && m.User != nil {
id = m.User.ID
}
return "member{user:" + username + ", nick:" + m.Nick + ", ID:" + id.String() + "}"
}
type GuildQueryBuilderCaller interface {
Guild(id Snowflake) GuildQueryBuilder
}
func (m *Member) UpdateNick(ctx context.Context, client GuildQueryBuilderCaller, nickname string) error {
_, err := client.Guild(m.GuildID).Member(m.UserID).WithContext(ctx).Update(&UpdateMember{Nick: &nickname})
return err
}
// GetPermissions populates a uint64 with all the permission flags
func (m *Member) GetPermissions(ctx context.Context, s GuildQueryBuilderCaller) (permissions PermissionBit, err error) {
// TODO: Don't deep copy channels for this in the future!
roles, err := s.Guild(m.GuildID).WithContext(ctx).GetRoles()
if err != nil {
return 0, err
}
unprocessedRoles := len(m.Roles)
for _, roleInfo := range roles {
for _, roleId := range m.Roles {
if roleInfo.ID == roleId {
permissions |= roleInfo.Permissions
unprocessedRoles--
break
}
}
if unprocessedRoles == 0 {
break
}
}
return permissions, nil
}
// GetUser tries to ensure that you get a user object and not a nil. The user can be nil if the guild
// was fetched from the cache.
func (m *Member) GetUser(ctx context.Context, session Session) (usr *User, err error) {
if m.User != nil {
return m.User, nil
}
return session.User(m.UserID).WithContext(ctx).Get()
}
// Mention creates a string which is parsed into a member mention on Discord GUI's
func (m *Member) Mention() string {
var id Snowflake
if !m.UserID.IsZero() {
id = m.UserID
} else if m.User != nil {
id = m.User.ID
}
return "<@!" + id.String() + ">"
}
//////////////////////////////////////////////////////
//
// REST Methods
//
//////////////////////////////////////////////////////
// CreateGuild ...
// https://discord.com/developers/docs/resources/guild#create-guild-json-params
// example partial channel object:
//
// {
// "name": "naming-things-is-hard",
// "type": 0
// }
type CreateGuild struct {
Name string `json:"name"` // required
Region string `json:"region"`
Icon string `json:"icon"`
VerificationLvl int `json:"verification_level"`
DefaultMsgNotifications DefaultMessageNotificationLvl `json:"default_message_notifications"`
ExplicitContentFilter ExplicitContentFilterLvl `json:"explicit_content_filter"`
Roles []*Role `json:"roles"`
Channels []*PartialChannel `json:"channels"`
}
// CreateGuild [REST] Create a new guild. Returns a guild object on success. Fires a Guild Create Gateway event.
//
// Method POST
// Endpoint /guilds
// Discord documentation https://discord.com/developers/docs/resources/guild#create-guild
// Reviewed 2018-08-16
// Comment This endpoint. can be used only by bots in less than 10 Guilds. Creating channel
// categories from this endpoint. is not supported.
// The params argument is optional.
func (c clientQueryBuilder) CreateGuild(guildName string, params *CreateGuild) (ret *Guild, err error) {
// TODO: check if bot
// TODO-2: is bot in less than 10 Guilds?
if guildName == "" {
return nil, ErrMissingGuildName
}
if l := len(guildName); !(2 <= l && l <= 100) {
return nil, fmt.Errorf("guild name must be 2 or more characters and no more than 100 characters: %w", ErrIllegalValue)
}
if params == nil {
params = &CreateGuild{}
}
params.Name = guildName
r := c.client.newRESTRequest(&httd.Request{
Method: http.MethodPost,
Ctx: c.ctx,
Endpoint: endpoint.Guilds(),
Body: params,
ContentType: httd.ContentTypeJSON,
}, c.flags)
r.factory = func() interface{} {
return &Guild{}
}
return getGuild(r.Execute)
}
// GuildQueryBuilder defines the exposed functions from the guild query builder.
type GuildQueryBuilder interface {
WithContext(ctx context.Context) GuildQueryBuilder
WithFlags(flags ...Flag) GuildQueryBuilder
// Get
// TODO: Add more guild attribute things. Waiting for caching changes before then.
Get() (guild *Guild, err error)
Update(params *UpdateGuild) (*Guild, error)
Delete() error
// Leave leaves the given guild
Leave() error
// GetChannels
// TODO: For GetChannels, it might sense to have the option for a function to filter before each channel ends up deep copied.
// TODO-2: This could be much more performant in guilds with a large number of channels.
GetChannels() ([]*Channel, error)
// GetMembers
// TODO: For GetMembers, it might sense to have the option for a function to filter before each member ends up deep copied.
// TODO-2: This could be much more performant in larger guilds where this is needed.
GetMembers(params *GetMembers) ([]*Member, error)
CreateChannel(name string, params *CreateGuildChannel) (*Channel, error)
UpdateChannelPositions(params []UpdateGuildChannelPositions) error
CreateMember(userID Snowflake, accessToken string, params *AddGuildMember) (*Member, error)
Member(userID Snowflake) GuildMemberQueryBuilder
DisconnectVoiceParticipant(userID Snowflake) error
SetCurrentUserNick(nick string) (newNick string, err error)
GetBans() ([]*Ban, error)
GetBan(userID Snowflake) (*Ban, error)
UnbanUser(userID Snowflake, reason string) error
// GetRoles
// TODO: For GetRoles, it might sense to have the option for a function to filter before each role ends up deep copied.
// TODO-2: This could be much more performant in larger guilds where this is needed.
GetRoles() ([]*Role, error)
UpdateRolePositions(params []UpdateGuildRolePositions) ([]*Role, error)
CreateRole(params *CreateGuildRole) (*Role, error)
Role(roleID Snowflake) GuildRoleQueryBuilder
GetPruneMembersCount(params *GetPruneMembersCount) (estimate int, err error)
PruneMembers(params *PruneMembers) (pruned int, err error)
GetVoiceRegions() ([]*VoiceRegion, error)
GetInvites() ([]*Invite, error)
GetIntegrations() ([]*Integration, error)
CreateIntegration(params *CreateGuildIntegration) error
UpdateIntegration(integrationID Snowflake, params *UpdateGuildIntegration) error
DeleteIntegration(integrationID Snowflake) error
SyncIntegration(integrationID Snowflake) error
GetWidget() (*GuildWidget, error)
UpdateWidget(params *UpdateGuildWidget) (*GuildWidget, error)
GetVanityURL() (*PartialInvite, error)
GetAuditLogs(logs *GetAuditLogs) (*AuditLog, error)
VoiceChannel(channelID Snowflake) VoiceChannelQueryBuilder
// GetEmojis
// TODO: For GetEmojis, it might sense to have the option for a function to filter before each emoji ends up deep copied.
// TODO-2: This could be much more performant in guilds with a large number of channels.
GetEmojis() ([]*Emoji, error)
CreateEmoji(params *CreateGuildEmoji) (*Emoji, error)
Emoji(emojiID Snowflake) GuildEmojiQueryBuilder
GetWebhooks() (ret []*Webhook, err error)
// GetActiveThreads Returns all active threads in the guild, including public and private threads. Threads are ordered
// by their id, in descending order.
GetActiveThreads() (*ActiveGuildThreads, error)
// Guild Scheduled Event
ScheduledEvent(eventID Snowflake) GuildScheduledEventQueryBuilder
GetScheduledEvents(params *GetScheduledEvents) ([]*GuildScheduledEvent, error)
CreateScheduledEvent(params *CreateScheduledEvent) (*GuildScheduledEvent, error)
}
// Guild is used to create a guild query builder.
func (c clientQueryBuilder) Guild(id Snowflake) GuildQueryBuilder {
return &guildQueryBuilder{client: c.client, gid: id}
}
// The default guild query builder.
type guildQueryBuilder struct {
ctx context.Context
flags Flag
client *Client
gid Snowflake
}
func (g *guildQueryBuilder) validate() error {
if g.client == nil {
return ErrMissingClientInstance
}
if g.gid.IsZero() {
return ErrMissingGuildID
}
return nil
}
func (g guildQueryBuilder) WithContext(ctx context.Context) GuildQueryBuilder {
g.ctx = ctx
return &g
}
func (g guildQueryBuilder) WithFlags(flags ...Flag) GuildQueryBuilder {
g.flags = mergeFlags(flags)
return &g
}
// Get is used to get the Guild struct containing all information from it.
// Note that it's significantly quicker in most instances where you have the cache enabled (as is by default) to get the individual parts you need.
func (g guildQueryBuilder) Get() (guild *Guild, err error) {
if !ignoreCache(g.flags) {
if guild, _ = g.client.cache.GetGuild(g.gid); guild != nil {
return guild, nil
}
}
r := g.client.newRESTRequest(&httd.Request{
Endpoint: endpoint.Guild(g.gid),
Ctx: g.ctx,
}, g.flags)
r.factory = func() interface{} {
return &Guild{}
}
return getGuild(r.Execute)
}
// Update update a guild
func (g guildQueryBuilder) Update(params *UpdateGuild) (*Guild, error) {
if params == nil {
return nil, ErrMissingRESTParams
}
if err := g.validate(); err != nil {
return nil, err
}
r := g.client.newRESTRequest(&httd.Request{
Method: http.MethodPatch,
Ctx: g.ctx,
Endpoint: endpoint.Guild(g.gid),
ContentType: httd.ContentTypeJSON,
Body: params,
Reason: params.AuditLogReason,
}, g.flags)
r.factory = func() interface{} {
return &Guild{}
}
return getGuild(r.Execute)
}
type UpdateGuild struct {
Name *string `json:"name,omitempty"`
Region *string `json:"region,omitempty"`
VerificationLvl *VerificationLvl `json:"verification_lvl,omitempty"`
DefaultMessageNotifications *DefaultMessageNotificationLvl `json:"default_message_notifications,omitempty"`
ExplicitContentFilter *ExplicitContentFilterLvl `json:"explicit_content_filter,omitempty"`
AFKChannelID *Snowflake `json:"afk_channel_id,omitempty"`
Icon *string `json:"icon,omitempty"`
OwnerID *Snowflake `json:"owner_id,omitempty"`
Splash *string `json:"splash,omitempty"`
DiscoverySplash *string `json:"discovery_splash,omitempty"`
Banner *string `json:"banner,omitempty"`
SystemChannelID *Snowflake `json:"system_channel_id,omitempty"`
SystemChannelFlags *uint `json:"system_channel_flags,omitempty"`
RulesChannelID *Snowflake `json:"rules_channel_id,omitempty"`
PublicUpdatesChannelID *Snowflake `json:"public_updates_channel_id,omitempty"`
PreferredLocale *string `json:"preferred_locale,omitempty"`
Features *[]string `json:"features,omitempty"`
Description *string `json:"description,omitempty"`
AuditLogReason string `json:"-"`
}
// Delete is used to delete a guild.
func (g guildQueryBuilder) Delete() error {
r := g.client.newRESTRequest(&httd.Request{
Method: http.MethodDelete,
Endpoint: endpoint.Guild(g.gid),
Ctx: g.ctx,
}, g.flags)
_, err := r.Execute()
return err
}
// Leave https://discord.com/developers/docs/resources/user#leave-guild
func (g guildQueryBuilder) Leave() error {
r := g.client.newRESTRequest(&httd.Request{
Method: http.MethodDelete,
Endpoint: endpoint.UserMeGuild(g.gid),
Ctx: g.ctx,
}, g.flags)
_, err := r.Execute()
return err
}
// GetChannels is used to get a guilds channels.
func (g guildQueryBuilder) GetChannels() ([]*Channel, error) {
if channels, _ := g.client.cache.GetGuildChannels(g.gid); channels != nil {
return channels, nil
}
r := g.client.newRESTRequest(&httd.Request{
Endpoint: endpoint.GuildChannels(g.gid),
Ctx: g.ctx,
}, g.flags)
r.factory = func() interface{} {
tmp := make([]*Channel, 0)
return &tmp
}
return getChannels(r.Execute)
}
// CreateChannel Create a new channel object for the guild. Requires the 'MANAGE_CHANNELS' permission.
// Returns the new channel object on success. Fires a Channel Create Gateway event.
func (g guildQueryBuilder) CreateChannel(name string, params *CreateGuildChannel) (*Channel, error) {
if name == "" && (params == nil || params.Name == "") {
return nil, ErrMissingChannelName
}
if l := len(name); !(2 <= l && l <= 100) {
return nil, fmt.Errorf("channel name must be 2 or more characters and no more than 100 characters: %w", ErrIllegalValue)
}
if params == nil {
params = &CreateGuildChannel{}
}
if name != "" && params.Name == "" {
params.Name = name
}
r := g.client.newRESTRequest(&httd.Request{
Method: http.MethodPost,
Ctx: g.ctx,
Endpoint: endpoint.GuildChannels(g.gid),
Body: params,
ContentType: httd.ContentTypeJSON,
Reason: params.Reason,
}, g.flags)
r.factory = func() interface{} {
return &Channel{}
}
return getChannel(r.Execute)
}
// UpdateChannelPositions Modify the positions of a set of channel objects for the guild.
// Requires 'MANAGE_CHANNELS' permission. Returns a 204 empty response on success. Fires multiple Channel Update
// Gateway events.
func (g guildQueryBuilder) UpdateChannelPositions(params []UpdateGuildChannelPositions) error {
var reason string
for i := range params {
if params[i].Reason != "" {
reason = params[i].Reason
break
}
}
r := g.client.newRESTRequest(&httd.Request{
Method: http.MethodPatch,
Ctx: g.ctx,
Endpoint: endpoint.GuildChannels(g.gid),
Body: params,
ContentType: httd.ContentTypeJSON,
Reason: reason,
}, g.flags)
_, err := r.Execute()
return err
}
// GetMembers uses the GetGuildMembers endpoint iteratively until your query params are met.
func (g guildQueryBuilder) GetMembers(params *GetMembers) ([]*Member, error) {
const QueryLimit uint32 = 1000
if params == nil {
params = &GetMembers{
Limit: math.MaxUint32,
}
}
highestSnowflake := func(ms []*Member) (highest Snowflake) {
for i := range ms {
if ms[i].User != nil && ms[i].User.ID > highest {
highest = ms[i].User.ID
}