forked from andersfylling/disgord
-
Notifications
You must be signed in to change notification settings - Fork 0
/
channel.go
1448 lines (1243 loc) · 50 KB
/
channel.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 (
"bytes"
"context"
"errors"
"fmt"
"io"
"mime/multipart"
"net/http"
"strconv"
"strings"
"sync"
"github.com/andersfylling/disgord/internal/endpoint"
"github.com/andersfylling/disgord/internal/httd"
"github.com/andersfylling/disgord/json"
)
// ChannelType https://discord.com/developers/docs/resources/channel#channel-object-channel-types
type ChannelType uint
const (
ChannelTypeGuildText ChannelType = iota
ChannelTypeDM
ChannelTypeGuildVoice
ChannelTypeGroupDM
ChannelTypeGuildCategory
ChannelTypeGuildNews
ChannelTypeGuildStore
_
_
_
ChannelTypeGuildNewsThread
ChannelTypeGuildPublicThread
// a temporary sub-channel within a GUILD_TEXT channel that is only viewable by those
// invited and those with the MANAGE_THREADS permission
ChannelTypeGuildPrivateThread
)
// VideoQualityMode https://discord.com/developers/docs/resources/channel#channel-object-video-quality-modes
type VideoQualityMode uint
const (
VideoQualityModeAuto VideoQualityMode = 1
VideoQualityModeFull VideoQualityMode = 2
)
// Attachment https://discord.com/developers/docs/resources/channel#attachment-object
type Attachment struct {
ID Snowflake `json:"id"`
Filename string `json:"filename"`
Size uint `json:"size"`
URL string `json:"url"`
ProxyURL string `json:"proxy_url"`
Height uint `json:"height"`
Width uint `json:"width"`
SpoilerTag bool `json:"-"`
}
var _ internalUpdater = (*Attachment)(nil)
var _ Copier = (*Attachment)(nil)
var _ DeepCopier = (*Attachment)(nil)
func (a *Attachment) updateInternals() {
a.SpoilerTag = strings.HasPrefix(a.Filename, AttachmentSpoilerPrefix)
}
type PermissionOverwriteType uint8
const (
PermissionOverwriteRole PermissionOverwriteType = iota
PermissionOverwriteMember
)
// PermissionOverwrite https://discord.com/developers/docs/resources/channel#overwrite-object
//
// WARNING! Discord is bugged, and the Type field needs to be a string to read Permission Overwrites from audit log
type PermissionOverwrite struct {
ID Snowflake `json:"id"` // role or user id
Type PermissionOverwriteType `json:"type"`
Allow PermissionBit `json:"allow"`
Deny PermissionBit `json:"deny"`
}
// type ChannelDeleter interface { DeleteChannel(id Snowflake) (err error) }
// type ChannelUpdater interface {}
// PartialChannel ...
// example of partial channel
// // "channel": {
// // "id": "165176875973476352",
// // "name": "illuminati",
// // "type": 0
// // }
type PartialChannel struct {
ID Snowflake `json:"id"`
Name string `json:"name"`
Type ChannelType `json:"type"`
}
// Channel ...
type Channel struct {
ID Snowflake `json:"id"`
Type ChannelType `json:"type"`
GuildID Snowflake `json:"guild_id,omitempty"`
Position int `json:"position,omitempty"` // can be less than 0
PermissionOverwrites []PermissionOverwrite `json:"permission_overwrites,omitempty"`
Name string `json:"name,omitempty"`
Topic string `json:"topic,omitempty"`
NSFW bool `json:"nsfw,omitempty"`
LastMessageID Snowflake `json:"last_message_id,omitempty"`
Bitrate uint `json:"bitrate,omitempty"`
UserLimit uint `json:"user_limit,omitempty"`
RateLimitPerUser uint `json:"rate_limit_per_user,omitempty"`
Recipients []*User `json:"recipients,omitempty"` // empty if not DM/GroupDM
Icon string `json:"icon,omitempty"`
OwnerID Snowflake `json:"owner_id,omitempty"`
ApplicationID Snowflake `json:"application_id,omitempty"`
ParentID Snowflake `json:"parent_id,omitempty"`
LastPinTimestamp Time `json:"last_pin_timestamp,omitempty"`
MessageCount int `json:"message_count,omitempty"` //threads only. stops counting at 50
MemberCount int `json:"member_count,omitempty"` //threads only. stops counting at 50
ThreadMetadata ThreadMetadata `json:"thread_metadata,omitempty"` //threads only
Member ThreadMember `json:"member,omitempty"` //threads only
DefaultAutoArchiveDuration int `json:"default_auto_archive_duration,omitempty"` //threads only
}
var _ Reseter = (*Channel)(nil)
var _ fmt.Stringer = (*Channel)(nil)
var _ Copier = (*Channel)(nil)
var _ DeepCopier = (*Channel)(nil)
var _ Mentioner = (*Channel)(nil)
func (c *Channel) String() string {
return "channel{name:'" + c.Name + "', id:" + c.ID.String() + "}"
}
func (c *Channel) valid() bool {
if c.RateLimitPerUser > 120 {
return false
}
if len(c.Topic) > 1024 {
return false
}
if c.Name != "" && (len(c.Name) > 100 || len(c.Name) < 2) {
return false
}
return true
}
// GetPermissions is used to get a members permissions in a channel.
func (c *Channel) GetPermissions(ctx context.Context, s GuildQueryBuilderCaller, member *Member) (permissions PermissionBit, err error) {
// Get the guild permissions.
permissions, err = member.GetPermissions(ctx, s)
if err != nil {
return 0, err
}
// Handle permission overwrites.
apply := func(o PermissionOverwrite) {
permissions |= o.Allow
permissions &= (-o.Deny) - 1
}
for _, overwrite := range c.PermissionOverwrites {
if overwrite.Type == PermissionOverwriteMember {
// This is a member. Is it me?
if overwrite.ID == member.UserID {
// It is! Time to apply the overwrites.
apply(overwrite)
}
continue
}
for _, role := range member.Roles {
if role == overwrite.ID {
apply(overwrite)
break
}
}
}
// Return the result.
return
}
// Mention creates a channel mention string. Mention format is according the Discord protocol.
func (c *Channel) Mention() string {
return "<#" + c.ID.String() + ">"
}
// Compare checks if channel A is the same as channel B
func (c *Channel) Compare(other *Channel) bool {
// eh
return (c == nil && other == nil) || (other != nil && c.ID == other.ID)
}
// SendMsgString same as SendMsg, however this only takes the message content (string) as a argument for the message
func (c *Channel) SendMsgString(ctx context.Context, s Session, content string) (msg *Message, err error) {
if c.ID.IsZero() {
err = newErrorMissingSnowflake("snowflake ID not set for channel")
return
}
params := &CreateMessage{
Content: content,
}
msg, err = s.Channel(c.ID).WithContext(ctx).CreateMessage(params)
return
}
// SendMsg sends a message to a channel
func (c *Channel) SendMsg(ctx context.Context, s Session, message *Message) (msg *Message, err error) {
if c.ID.IsZero() {
err = newErrorMissingSnowflake("snowflake ID not set for channel")
return
}
nonce := fmt.Sprint(message.Nonce)
if len(nonce) > 25 {
return nil, errors.New("nonce can not be longer than 25 characters")
}
params := &CreateMessage{
Content: message.Content,
Nonce: nonce, // THIS IS A STRING. NOT A SNOWFLAKE! DONT TOUCH!
Tts: message.Tts,
MessageReference: message.MessageReference,
// File: ...
// Embed: ...
}
if len(message.Embeds) > 0 {
params.Embed = message.Embeds[0]
}
msg, err = s.Channel(c.ID).WithContext(ctx).CreateMessage(params)
return
}
//////////////////////////////////////////////////////
//
// REST Methods
//
//////////////////////////////////////////////////////
func (c clientQueryBuilder) Channel(id Snowflake) ChannelQueryBuilder {
return &channelQueryBuilder{client: c.client, cid: id}
}
// ChannelQueryBuilder REST interface for all Channel endpoints
type ChannelQueryBuilder interface {
WithContext(ctx context.Context) ChannelQueryBuilder
WithFlags(flags ...Flag) ChannelQueryBuilder
// TriggerTypingIndicator Post a typing indicator for the specified channel. Generally bots should not implement
// this route. However, if a bot is responding to a command and expects the computation to take a few seconds, this
// endpoint may be called to let the user know that the bot is processing their message. Returns a 204 empty response
// on success. Fires a Typing Start Gateway event.
TriggerTypingIndicator() error
// Get Get a channel by Snowflake. Returns a channel object.
Get() (*Channel, error)
// Update a Channels settings. Requires the 'MANAGE_CHANNELS' permission for the guild. Returns
// a channel on success, and a 400 BAD REQUEST on invalid parameters. Fires a Channel Update Gateway event. If
// modifying a category, individual Channel Update events will fire for each child channel that also changes.
// For the PATCH method, all the JSON Params are optional.
Update(params *UpdateChannel) (*Channel, error)
// Delete a channel, or close a private message. Requires the 'MANAGE_CHANNELS' permission for
// the guild. Deleting a category does not delete its child Channels; they will have their parent_id removed and a
// Channel Update Gateway event will fire for each of them. Returns a channel object on success.
// Fires a Channel Delete Gateway event.
Delete() (*Channel, error)
// UpdatePermissions Edit the channel permission overwrites for a user or role in a channel. Only usable
// for guild Channels. Requires the 'MANAGE_ROLES' permission. Returns a 204 empty response on success.
// For more information about permissions, see permissions.
UpdatePermissions(overwriteID Snowflake, params *UpdateChannelPermissions) error
// GetInvites Returns a list of invite objects (with invite metadata) for the channel. Only usable for
// guild Channels. Requires the 'MANAGE_CHANNELS' permission.
GetInvites() ([]*Invite, error)
// CreateInvite Create a new invite object for the channel. Only usable for guild Channels. Requires
// the CREATE_INSTANT_INVITE permission. All JSON parameters for this route are optional, however the request
// body is not. If you are not sending any fields, you still have to send an empty JSON object ({}).
// Returns an invite object.
CreateInvite(params *CreateInvite) (*Invite, error)
// DeletePermission Delete a channel permission overwrite for a user or role in a channel. Only usable
// for guild Channels. Requires the 'MANAGE_ROLES' permission. Returns a 204 empty response on success. For more
// information about permissions,
// see permissions: https://discord.com/developers/docs/topics/permissions#permissions
DeletePermission(overwriteID Snowflake) error
// AddDMParticipant Adds a recipient to a Group DM using their access token. Returns a 204 empty response
// on success.
AddDMParticipant(participant *GroupDMParticipant) error
// KickParticipant Removes a recipient from a Group DM. Returns a 204 empty response on success.
KickParticipant(userID Snowflake) error
// GetPinnedMessages Returns all pinned messages in the channel as an array of message objects.
GetPinnedMessages() ([]*Message, error)
// DeleteMessages Delete multiple messages in a single request. This endpoint can only be used on guild
// Channels and requires the 'MANAGE_MESSAGES' permission. Returns a 204 empty response on success. Fires multiple
// Message Delete Gateway events.Any message IDs given that do not exist or are invalid will count towards
// the minimum and maximum message count (currently 2 and 100 respectively). Additionally, duplicated IDs
// will only be counted once.
DeleteMessages(params *DeleteMessages) error
// GetMessages Returns the messages for a channel. If operating on a guild channel, this endpoint requires
// the 'VIEW_CHANNEL' permission to be present on the current user. If the current user is missing
// the 'READ_MESSAGE_HISTORY' permission in the channel then this will return no messages
// (since they cannot read the message history). Returns an array of message objects on success.
GetMessages(params *GetMessages) ([]*Message, error)
// CreateMessage Post a message to a guild text or DM channel. If operating on a guild channel, this
// endpoint requires the 'SEND_MESSAGES' permission to be present on the current user. If the tts field is set to true,
// the SEND_TTS_MESSAGES permission is required for the message to be spoken. Returns a message object. Fires a
// Message Create Gateway event. See message formatting for more information on how to properly format messages.
// The maximum request size when sending a message is 8MB.
CreateMessage(params *CreateMessage) (*Message, error)
// CreateWebhook Create a new webhook. Requires the 'MANAGE_WEBHOOKS' permission.
// Returns a webhook object on success.
CreateWebhook(params *CreateWebhook) (ret *Webhook, err error)
// GetWebhooks Returns a list of channel webhook objects. Requires the 'MANAGE_WEBHOOKS' permission.
GetWebhooks() (ret []*Webhook, err error)
Message(id Snowflake) MessageQueryBuilder
// CreateThread Create a thread that is not connected to an existing message.
CreateThread(params *CreateThreadWithoutMessage) (*Channel, error)
// JoinThread Adds the current user to a thread. Also requires the thread is not archived.
// Returns a 204 empty response on success.
JoinThread() error
// AddThreadMember Adds another member to a thread. Requires the ability to send messages in the thread.
// Also requires the thread is not archived. Returns a 204 empty response if the member
// is successfully added or was already a member of the thread.
AddThreadMember(userID Snowflake) error
// LeaveThread Removes the current user from a thread. Also requires the thread is not archived.
// Returns a 204 empty response on success.
LeaveThread() error
// RemoveThreadMember Removes another member from a thread. Requires the MANAGE_THREADS permission, or the
// creator of the thread if it is a GUILD_PRIVATE_THREAD. Also requires the thread is not archived.
// Returns a 204 empty response on success.
RemoveThreadMember(userID Snowflake) error
// GetThreadMember Returns a thread member object for the specified user if
// they are a member of the thread, returns a 404 response otherwise.
GetThreadMember(userID Snowflake) (*ThreadMember, error)
// GetThreadMembers Returns array of thread members objects that are members of the thread.
// This endpoint is restricted according to whether the GUILD_MEMBERS Privileged Intent is enabled for your application.
GetThreadMembers() ([]*ThreadMember, error)
// GetPublicArchivedThreads Returns archived threads in the channel that are public. When called on a GUILD_TEXT channel, returns
// threads of type GUILD_PUBLIC_THREAD. When called on a GUILD_NEWS channel returns threads of type
// GUILD_NEWS_THREAD. Threads are ordered by archive_timestamp, in descending order. Requires the READ_MESSAGE_HISTORY
// permission.
GetPublicArchivedThreads(params *GetArchivedThreads) (*ArchivedThreads, error)
// GetPrivateArchivedThreads Returns archived threads in the channel that are of type GUILD_PRIVATE_THREAD. Threads are ordered by
// archive_timestamp, in descending order. Requires both the READ_MESSAGE_HISTORY and MANAGE_THREADS permissions.
GetPrivateArchivedThreads(params *GetArchivedThreads) (*ArchivedThreads, error)
// GetJoinedPrivateArchivedThreads Returns archived threads in the channel that are of type GUILD_PRIVATE_THREAD, and the user has joined.
// Threads are ordered by their id, in descending order. Requires the READ_MESSAGE_HISTORY permission.
GetJoinedPrivateArchivedThreads(params *GetArchivedThreads) (*ArchivedThreads, error)
}
type channelQueryBuilder struct {
ctx context.Context
flags Flag
client *Client
cid Snowflake
}
var _ ChannelQueryBuilder = (*channelQueryBuilder)(nil)
func (c *channelQueryBuilder) validate() error {
if c.client == nil {
return ErrMissingClientInstance
}
if c.cid.IsZero() {
return ErrMissingChannelID
}
return nil
}
func (c channelQueryBuilder) WithContext(ctx context.Context) ChannelQueryBuilder {
c.ctx = ctx
return &c
}
func (c channelQueryBuilder) WithFlags(flags ...Flag) ChannelQueryBuilder {
c.flags = mergeFlags(flags)
return &c
}
// Get [REST] Get a channel by Snowflake. Returns a channel object.
//
// Method GET
// Endpoint /channels/{channel.id}
// Discord documentation https://discord.com/developers/docs/resources/channel#get-channel
// Reviewed 2018-06-07
// Comment -
func (c channelQueryBuilder) Get() (*Channel, error) {
if c.cid.IsZero() {
return nil, ErrMissingChannelID
}
if !ignoreCache(c.flags) {
if channel, _ := c.client.cache.GetChannel(c.cid); channel != nil {
return channel, nil
}
}
r := c.client.newRESTRequest(&httd.Request{
Endpoint: endpoint.Channel(c.cid),
Ctx: c.ctx,
}, c.flags)
r.pool = c.client.pool.channel
r.factory = func() interface{} {
return &Channel{}
}
return getChannel(r.Execute)
}
// Update [REST] Update a channel's settings. Returns a channel on success, and a 400 BAD REQUEST
// on invalid parameters. All JSON parameters are optional.
//
// Method PATCH
// Endpoint /channels/{channel.id}
// Discord documentation https://discord.com/developers/docs/resources/channel#modify-channel
// Reviewed 2021-08-08
func (c channelQueryBuilder) Update(params *UpdateChannel) (*Channel, error) {
if params == nil {
return nil, ErrMissingRESTParams
}
if err := c.validate(); err != nil {
return nil, err
}
r := c.client.newRESTRequest(&httd.Request{
Method: http.MethodPatch,
Ctx: c.ctx,
Endpoint: endpoint.Channel(c.cid),
ContentType: httd.ContentTypeJSON,
Body: params,
Reason: params.AuditLogReason,
}, c.flags)
r.factory = func() interface{} {
return &Channel{}
}
return getChannel(r.Execute)
}
type UpdateChannel struct {
Name *string `json:"name,omitempty"`
Type *ChannelType `json:"type,omitempty"`
Position *uint `json:"position,omitempty"`
Topic *string `json:"topic,omitempty"`
NSFW *bool `json:"nsfw,omitempty"`
RateLimitPerUser *uint `json:"rate_limit_per_user,omitempty"`
Bitrate *uint `json:"bitrate,omitempty"`
UserLimit *uint `json:"user_limit,omitempty"`
PermissionOverwrites *[]PermissionOverwriteType `json:"permission_overwrites,omitempty"`
ParentID *Snowflake `json:"parent_id,omitempty"`
RTCRegion *string `json:"rtc_region,omitempty"`
VideoQualityMode *VideoQualityMode `json:"video_quality_mode,omitempty"`
DefaultAutoArchiveDuration *uint `json:"default_auto_archive_duration,omitempty"`
AuditLogReason string `json:"-"`
}
// Delete [REST] Delete a channel, or close a private message. Requires the 'MANAGE_CHANNELS' permission for
// the guild. Deleting a category does not delete its child Channels; they will have their parent_id removed and a
// Channel Update Gateway event will fire for each of them. Returns a channel object on success.
// Fires a Channel Delete Gateway event.
//
// Method Delete
// Endpoint /channels/{channel.id}
// Discord documentation https://discord.com/developers/docs/resources/channel#deleteclose-channel
// Reviewed 2018-10-09
// Comment Deleting a guild channel cannot be undone. Use this with caution, as it
// is impossible to undo this action when performed on a guild channel. In
// contrast, when used with a private message, it is possible to undo the
// action by opening a private message with the recipient again.
func (c channelQueryBuilder) Delete() (channel *Channel, err error) {
if c.cid.IsZero() {
return nil, ErrMissingChannelID
}
r := c.client.newRESTRequest(&httd.Request{
Method: http.MethodDelete,
Endpoint: endpoint.Channel(c.cid),
Ctx: context.Background(),
}, c.flags)
r.factory = func() interface{} {
return &Channel{}
}
return getChannel(r.Execute)
}
// TriggerTypingIndicator [REST] Post a typing indicator for the specified channel. Generally bots should not implement
// this route. However, if a bot is responding to a command and expects the computation to take a few seconds, this
// endpoint may be called to let the user know that the bot is processing their message. Returns a 204 empty response
// on success. Fires a Typing Start Gateway event.
//
// Method POST
// Endpoint /channels/{channel.id}/typing
// Discord documentation https://discord.com/developers/docs/resources/channel#trigger-typing-indicator
// Reviewed 2018-06-10
// Comment -
func (c channelQueryBuilder) TriggerTypingIndicator() (err error) {
r := c.client.newRESTRequest(&httd.Request{
Method: http.MethodPost,
Endpoint: endpoint.ChannelTyping(c.cid),
Ctx: c.ctx,
}, c.flags)
_, err = r.Execute()
return err
}
// UpdateChannelPermissions https://discord.com/developers/docs/resources/channel#edit-channel-permissions-json-params
type UpdateChannelPermissions struct {
Allow PermissionBit `json:"allow"` // the bitwise value of all allowed permissions
Deny PermissionBit `json:"deny"` // the bitwise value of all disallowed permissions
Type uint `json:"type"` // 0=role, 1=member
}
// UpdatePermissions [REST] Edit the channel permission overwrites for a user or role in a channel. Only usable
// for guild Channels. Requires the 'MANAGE_ROLES' permission. Returns a 204 empty response on success.
// For more information about permissions, see permissions.
//
// Method PUT
// Endpoint /channels/{channel.id}/permissions/{overwrite.id}
// Discord documentation https://discord.com/developers/docs/resources/channel#edit-channel-permissions
// Reviewed 2018-06-07
// Comment -
func (c channelQueryBuilder) UpdatePermissions(overwriteID Snowflake, params *UpdateChannelPermissions) (err error) {
if c.cid.IsZero() {
return ErrMissingChannelID
}
if overwriteID.IsZero() {
return ErrMissingPermissionOverwriteID
}
r := c.client.newRESTRequest(&httd.Request{
Method: http.MethodPut,
Ctx: c.ctx,
Endpoint: endpoint.ChannelPermission(c.cid, overwriteID),
ContentType: httd.ContentTypeJSON,
Body: params,
}, c.flags)
_, err = r.Execute()
return err
}
// GetInvites [REST] Returns a list of invite objects (with invite metadata) for the channel. Only usable for
// guild Channels. Requires the 'MANAGE_CHANNELS' permission.
//
// Method GET
// Endpoint /channels/{channel.id}/invites
// Discord documentation https://discord.com/developers/docs/resources/channel#get-channel-invites
// Reviewed 2018-06-07
// Comment -
func (c channelQueryBuilder) GetInvites() (invites []*Invite, err error) {
if c.cid.IsZero() {
return nil, ErrMissingChannelID
}
r := c.client.newRESTRequest(&httd.Request{
Endpoint: endpoint.ChannelInvites(c.cid),
Ctx: c.ctx,
}, c.flags)
r.factory = func() interface{} {
tmp := make([]*Invite, 0)
return &tmp
}
return getInvites(r.Execute)
}
// CreateInvite https://discord.com/developers/docs/resources/channel#create-channel-invite
func (c channelQueryBuilder) CreateInvite(params *CreateInvite) (*Invite, error) {
if params == nil {
return nil, ErrMissingRESTParams
}
r := c.client.newRESTRequest(&httd.Request{
Method: http.MethodPost,
Ctx: c.ctx,
Endpoint: endpoint.ChannelInvites(c.cid),
ContentType: httd.ContentTypeJSON,
Body: params,
Reason: params.AuditLogReason,
}, c.flags)
r.factory = func() interface{} {
return &Invite{}
}
return getInvite(r.Execute)
}
type CreateInvite struct {
MaxAge int `json:"max_age"`
MaxUses int `json:"max_uses,omitempty"`
Temporary bool `json:"temporary,omitempty"`
Unique bool `json:"unique,omitempty"`
TargetType int `json:"target_type,omitempty"`
TargetUserID Snowflake `json:"target_user_id,omitempty"`
TargetApplicationID Snowflake `json:"target_application_id,omitempty"`
AuditLogReason string `json:"-"`
}
// DeletePermission [REST] Delete a channel permission overwrite for a user or role in a channel. Only usable
// for guild Channels. Requires the 'MANAGE_ROLES' permission. Returns a 204 empty response on success. For more
// information about permissions, see permissions: https://discord.com/developers/docs/topics/permissions#permissions
//
// Method DELETE
// Endpoint /channels/{channel.id}/permissions/{overwrite.id}
// Discord documentation https://discord.com/developers/docs/resources/channel#delete-channel-permission
// Reviewed 2018-06-07
// Comment -
func (c channelQueryBuilder) DeletePermission(overwriteID Snowflake) (err error) {
if c.cid.IsZero() {
return ErrMissingChannelID
}
if overwriteID.IsZero() {
return ErrMissingPermissionOverwriteID
}
r := c.client.newRESTRequest(&httd.Request{
Method: http.MethodDelete,
Endpoint: endpoint.ChannelPermission(c.cid, overwriteID),
Ctx: c.ctx,
}, c.flags)
_, err = r.Execute()
return err
}
// GroupDMParticipant Information needed to add a recipient to a group chat
type GroupDMParticipant struct {
AccessToken string `json:"access_token"` // access token of a user that has granted your app the gdm.join scope
Nickname string `json:"nick,omitempty"` // nickname of the user being added
UserID Snowflake `json:"-"`
}
func (g *GroupDMParticipant) FindErrors() error {
if g.UserID.IsZero() {
return ErrMissingUserID
}
if g.AccessToken == "" {
return errors.New("missing access token")
}
if err := ValidateUsername(g.Nickname); err != nil && g.Nickname != "" {
return err
}
return nil
}
// AddDMParticipant [REST] Adds a recipient to a Group DM using their access token. Returns a 204 empty response
// on success.
//
// Method PUT
// Endpoint /channels/{channel.id}/recipients/{user.id}
// Discord documentation https://discord.com/developers/docs/resources/channel#group-dm-add-recipient
// Reviewed 2018-06-10
// Comment -
func (c channelQueryBuilder) AddDMParticipant(participant *GroupDMParticipant) error {
if c.cid.IsZero() {
return ErrMissingChannelID
}
if participant == nil {
return errors.New("params can not be nil")
}
if err := participant.FindErrors(); err != nil {
return err
}
r := c.client.newRESTRequest(&httd.Request{
Method: http.MethodPut,
Ctx: c.ctx,
Endpoint: endpoint.ChannelRecipient(c.cid, participant.UserID),
Body: participant,
ContentType: httd.ContentTypeJSON,
}, c.flags)
_, err := r.Execute()
return err
}
// KickParticipant [REST] Removes a recipient from a Group DM. Returns a 204 empty response on success.
//
// Method DELETE
// Endpoint /channels/{channel.id}/recipients/{user.id}
// Discord documentation https://discord.com/developers/docs/resources/channel#group-dm-remove-recipient
// Reviewed 2018-06-10
// Comment -
func (c channelQueryBuilder) KickParticipant(userID Snowflake) (err error) {
if c.cid.IsZero() {
return ErrMissingChannelID
}
if userID.IsZero() {
return ErrMissingUserID
}
r := c.client.newRESTRequest(&httd.Request{
Method: http.MethodDelete,
Endpoint: endpoint.ChannelRecipient(c.cid, userID),
Ctx: c.ctx,
}, c.flags)
_, err = r.Execute()
return err
}
// GetMessages https://discord.com/developers/docs/resources/channel#get-channel-messages-query-string-params
// TODO: ensure limits
type GetMessages struct {
Around Snowflake `urlparam:"around,omitempty"`
Before Snowflake `urlparam:"before,omitempty"`
After Snowflake `urlparam:"after,omitempty"`
Limit uint `urlparam:"limit,omitempty"`
}
func (g *GetMessages) Validate() error {
var mutuallyExclusives int
if !g.Around.IsZero() {
mutuallyExclusives++
}
if !g.Before.IsZero() {
mutuallyExclusives++
}
if !g.After.IsZero() {
mutuallyExclusives++
}
if mutuallyExclusives > 1 {
return errors.New(`only one of the keys "around", "before" and "after" can be set at the time`)
}
return nil
}
var _ URLQueryStringer = (*GetMessages)(nil)
// getMessages [REST] Returns the messages for a channel. If operating on a guild channel, this endpoint requires
// the 'VIEW_CHANNEL' permission to be present on the current user. If the current user is missing
// the 'READ_MESSAGE_HISTORY' permission in the channel then this will return no messages
// (since they cannot read the message history). Returns an array of message objects on success.
//
// Method GET
// Endpoint /channels/{channel.id}/messages
// Discord documentation https://discord.com/developers/docs/resources/channel#get-channel-messages
// Reviewed 2018-06-10
// Comment The before, after, and around keys are mutually exclusive, only one may
// be passed at a time. see ReqGetChannelMessagesParams.
func (c channelQueryBuilder) getMessages(params URLQueryStringer) (ret []*Message, err error) {
if c.cid.IsZero() {
return nil, ErrMissingChannelID
}
var query string
if params != nil {
query += params.URLQueryString()
}
r := c.client.newRESTRequest(&httd.Request{
Endpoint: endpoint.ChannelMessages(c.cid) + query,
Ctx: c.ctx,
}, c.flags)
r.factory = func() interface{} {
tmp := make([]*Message, 0)
return &tmp
}
return getMessages(r.Execute)
}
// GetMessages bypasses discord limitations and iteratively fetches messages until the set filters are met.
func (c channelQueryBuilder) GetMessages(filter *GetMessages) (messages []*Message, err error) {
// discord values
const filterLimit = 100
const filterDefault = 50
if err = filter.Validate(); err != nil {
return nil, err
}
if filter.Limit == 0 {
filter.Limit = filterDefault
// we hardcode it here in case discord goes dumb and decided to randomly change it.
// This avoids that the bot do not experience a new, random, behaviour on API changes
}
if filter.Limit <= filterLimit {
return c.getMessages(filter)
}
latestSnowflake := func(msgs []*Message) (latest Snowflake) {
for i := range msgs {
// if msgs[i].ID.Date().After(latest.Date()) {
if msgs[i].ID > latest {
latest = msgs[i].ID
}
}
return
}
earliestSnowflake := func(msgs []*Message) (earliest Snowflake) {
for i := range msgs {
// if msgs[i].ID.Date().Before(earliest.Date()) {
if msgs[i].ID < earliest {
earliest = msgs[i].ID
}
}
return
}
// scenario#1: filter.Around is not 0 AND filter.Limit is above 100
// divide the limit by half and use .Before and .After tags on each quotient limit.
// Use the .After on potential remainder.
// Note! This method can be used recursively
if !filter.Around.IsZero() {
beforeParams := *filter
beforeParams.Before = beforeParams.Around
beforeParams.Around = 0
beforeParams.Limit = filter.Limit / 2
befores, err := c.GetMessages(&beforeParams)
if err != nil {
return nil, err
}
messages = append(messages, befores...)
afterParams := *filter
afterParams.After = afterParams.Around
afterParams.Around = 0
afterParams.Limit = filter.Limit / 2
afters, err := c.GetMessages(&afterParams)
if err != nil {
return nil, err
}
messages = append(messages, afters...)
// filter.Around includes the given ID, so should .Before and .After iterations do as well
if msg, _ := c.Message(filter.Around).WithContext(c.ctx).Get(); msg != nil {
// assumption: error here can be caused by the message ID not actually being a real message
// and that it was used to get messages in the vicinity. Therefore the err is ignored.
// TODO: const discord errors.
messages = append(messages, msg)
}
} else {
// scenario#3: filter.After or filter.Before is set.
// note that none might be set, which will cause filter.Before to be set after the first 100 messages.
//
for {
if filter.Limit <= 0 {
break
}
f := *filter
if f.Limit > 100 {
f.Limit = 100
}
filter.Limit -= f.Limit
msgs, err := c.getMessages(&f)
if err != nil {
return nil, err
}
messages = append(messages, msgs...)
if !filter.After.IsZero() {
filter.After = latestSnowflake(msgs)
} else {
// no snowflake or filter.Before
filter.Before = earliestSnowflake(msgs)
}
}
}
// duplicates should not exist as we use snowflakes to fetch unique segments in time
return messages, nil
}
// DeleteMessages https://discord.com/developers/docs/resources/channel#bulk-delete-messages-json-params
type DeleteMessages struct {
Messages []Snowflake `json:"messages"`
m sync.RWMutex
}
func (p *DeleteMessages) tooMany(messages int) (err error) {
if messages > 100 {
err = errors.New("must be 100 or less messages to delete")
}
return
}
func (p *DeleteMessages) tooFew(messages int) (err error) {
if messages < 2 {
err = errors.New("must be at least two messages to delete")
}
return
}
// Valid validates the DeleteMessages data
func (p *DeleteMessages) Valid() (err error) {
p.m.RLock()
defer p.m.RUnlock()
messages := len(p.Messages)
if err = p.tooMany(messages); err != nil {
return
}
err = p.tooFew(messages)
return
}
// AddMessage Adds a message to be deleted
func (p *DeleteMessages) AddMessage(msg *Message) (err error) {
p.m.Lock()
defer p.m.Unlock()
if err = p.tooMany(len(p.Messages) + 1); err != nil {
return
}
// TODO: check for duplicates as those are counted only once
p.Messages = append(p.Messages, msg.ID)
return
}
// DeleteMessages [REST] Delete multiple messages in a single request. This endpoint can only be used on guild
// Channels and requires the 'MANAGE_MESSAGES' permission. Returns a 204 empty response on success. Fires multiple
// Message Delete Gateway events.Any message IDs given that do not exist or are invalid will count towards
// the minimum and maximum message count (currently 2 and 100 respectively). Additionally, duplicated IDs
// will only be counted once.
//
// Method POST
// Endpoint /channels/{channel.id}/messages/bulk_delete
// Discord documentation https://discord.com/developers/docs/resources/channel#delete-message
// Reviewed 2018-06-10
// Comment This endpoint will not delete messages older than 2 weeks, and will fail if any message
// provided is older than that.
func (c channelQueryBuilder) DeleteMessages(params *DeleteMessages) (err error) {
if c.cid.IsZero() {
return ErrMissingChannelID
}
if err = params.Valid(); err != nil {
return err
}
r := c.client.newRESTRequest(&httd.Request{
Method: http.MethodPost,
Ctx: c.ctx,
Endpoint: endpoint.ChannelMessagesBulkDelete(c.cid),
ContentType: httd.ContentTypeJSON,
Body: params,
}, c.flags)
_, err = r.Execute()
return err
}
// AllowedMentions allows finer control over mentions in a message, see
// https://discord.com/developers/docs/resources/channel#allowed-mentions-object for more info.
// Any strings in the Parse value must be any from ["everyone", "users", "roles"].
type AllowedMentions struct {
Parse []string `json:"parse"` // this is purposefully not marked as omitempty as to allow `parse: []` which blocks all mentions.
Roles []Snowflake `json:"roles,omitempty"`
Users []Snowflake `json:"users,omitempty"`
RepliedUser bool `json:"replied_user,omitempty"`
}
// CreateMessageFile contains the information needed to upload a file to Discord, it is part of the
// CreateMessage struct.
type CreateMessageFile struct {
Reader io.Reader `json:"-"` // always omit as we don't want this as part of the JSON payload
FileName string `json:"-"`