forked from bwmarrin/discordgo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
restapi.go
3455 lines (2826 loc) · 115 KB
/
restapi.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
// Discordgo - Discord bindings for Go
// Available at https://github.com/bwmarrin/discordgo
// Copyright 2015-2016 Bruce Marriner <[email protected]>. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// This file contains functions for interacting with the Discord REST/JSON API
// at the lowest level.
package discordgo
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"image"
_ "image/jpeg" // For JPEG decoding
_ "image/png" // For PNG decoding
"io"
"io/ioutil"
"log"
"net/http"
"net/url"
"strconv"
"strings"
"time"
"context"
)
// All error constants
var (
ErrJSONUnmarshal = errors.New("json unmarshal")
ErrStatusOffline = errors.New("You can't set your Status to offline")
ErrVerificationLevelBounds = errors.New("VerificationLevel out of bounds, should be between 0 and 3")
ErrPruneDaysBounds = errors.New("the number of days should be more than or equal to 1")
ErrGuildNoIcon = errors.New("guild does not have an icon set")
ErrGuildNoSplash = errors.New("guild does not have a splash set")
ErrUnauthorized = errors.New("HTTP request was unauthorized. This could be because the provided token was not a bot token. Please add \"Bot \" to the start of your token. https://discord.com/developers/docs/reference#authentication-example-bot-token-authorization-header")
)
var (
// Marshal defines function used to encode JSON payloads
Marshal func(v interface{}) ([]byte, error) = json.Marshal
// Unmarshal defines function used to decode JSON payloads
Unmarshal func(src []byte, v interface{}) error = json.Unmarshal
)
// RESTError stores error information about a request with a bad response code.
// Message is not always present, there are cases where api calls can fail
// without returning a json message.
type RESTError struct {
Request *http.Request
Response *http.Response
ResponseBody []byte
Message *APIErrorMessage // Message may be nil.
}
// newRestError returns a new REST API error.
func newRestError(req *http.Request, resp *http.Response, body []byte) *RESTError {
restErr := &RESTError{
Request: req,
Response: resp,
ResponseBody: body,
}
// Attempt to decode the error and assume no message was provided if it fails
var msg *APIErrorMessage
err := Unmarshal(body, &msg)
if err == nil {
restErr.Message = msg
}
return restErr
}
// Error returns a Rest API Error with its status code and body.
func (r RESTError) Error() string {
return "HTTP " + r.Response.Status + ", " + string(r.ResponseBody)
}
// RateLimitError is returned when a request exceeds a rate limit
// and ShouldRetryOnRateLimit is false. The request may be manually
// retried after waiting the duration specified by RetryAfter.
type RateLimitError struct {
*RateLimit
}
// Error returns a rate limit error with rate limited endpoint and retry time.
func (e RateLimitError) Error() string {
return "Rate limit exceeded on " + e.URL + ", retry after " + e.RetryAfter.String()
}
// RequestConfig is an HTTP request configuration.
type RequestConfig struct {
Request *http.Request
ShouldRetryOnRateLimit bool
MaxRestRetries int
Client *http.Client
}
// newRequestConfig returns a new HTTP request configuration based on parameters in Session.
func newRequestConfig(s *Session, req *http.Request) *RequestConfig {
return &RequestConfig{
ShouldRetryOnRateLimit: s.ShouldRetryOnRateLimit,
MaxRestRetries: s.MaxRestRetries,
Client: s.Client,
Request: req,
}
}
// RequestOption is a function which mutates request configuration.
// It can be supplied as an argument to any REST method.
type RequestOption func(cfg *RequestConfig)
// WithClient changes the HTTP client used for the request.
func WithClient(client *http.Client) RequestOption {
return func(cfg *RequestConfig) {
if client != nil {
cfg.Client = client
}
}
}
// WithRetryOnRatelimit controls whether session will retry the request on rate limit.
func WithRetryOnRatelimit(retry bool) RequestOption {
return func(cfg *RequestConfig) {
cfg.ShouldRetryOnRateLimit = retry
}
}
// WithRestRetries changes maximum amount of retries if request fails.
func WithRestRetries(max int) RequestOption {
return func(cfg *RequestConfig) {
cfg.MaxRestRetries = max
}
}
// WithHeader sets a header in the request.
func WithHeader(key, value string) RequestOption {
return func(cfg *RequestConfig) {
cfg.Request.Header.Set(key, value)
}
}
// WithAuditLogReason changes audit log reason associated with the request.
func WithAuditLogReason(reason string) RequestOption {
return WithHeader("X-Audit-Log-Reason", reason)
}
// WithLocale changes accepted locale of the request.
func WithLocale(locale Locale) RequestOption {
return WithHeader("X-Discord-Locale", string(locale))
}
// WithContext changes context of the request.
func WithContext(ctx context.Context) RequestOption {
return func(cfg *RequestConfig) {
cfg.Request = cfg.Request.WithContext(ctx)
}
}
// Request is the same as RequestWithBucketID but the bucket id is the same as the urlStr
func (s *Session) Request(method, urlStr string, data interface{}, options ...RequestOption) (response []byte, err error) {
return s.RequestWithBucketID(method, urlStr, data, strings.SplitN(urlStr, "?", 2)[0], options...)
}
// RequestWithBucketID makes a (GET/POST/...) Requests to Discord REST API with JSON data.
func (s *Session) RequestWithBucketID(method, urlStr string, data interface{}, bucketID string, options ...RequestOption) (response []byte, err error) {
var body []byte
if data != nil {
body, err = Marshal(data)
if err != nil {
return
}
}
return s.request(method, urlStr, "application/json", body, bucketID, 0, options...)
}
// request makes a (GET/POST/...) Requests to Discord REST API.
// Sequence is the sequence number, if it fails with a 502 it will
// retry with sequence+1 until it either succeeds or sequence >= session.MaxRestRetries
func (s *Session) request(method, urlStr, contentType string, b []byte, bucketID string, sequence int, options ...RequestOption) (response []byte, err error) {
if bucketID == "" {
bucketID = strings.SplitN(urlStr, "?", 2)[0]
}
return s.RequestWithLockedBucket(method, urlStr, contentType, b, s.Ratelimiter.LockBucket(bucketID), sequence, options...)
}
// RequestWithLockedBucket makes a request using a bucket that's already been locked
func (s *Session) RequestWithLockedBucket(method, urlStr, contentType string, b []byte, bucket *Bucket, sequence int, options ...RequestOption) (response []byte, err error) {
if s.Debug {
log.Printf("API REQUEST %8s :: %s\n", method, urlStr)
log.Printf("API REQUEST PAYLOAD :: [%s]\n", string(b))
}
req, err := http.NewRequest(method, urlStr, bytes.NewBuffer(b))
if err != nil {
bucket.Release(nil)
return
}
// Not used on initial login..
// TODO: Verify if a login, otherwise complain about no-token
if s.Token != "" {
req.Header.Set("authorization", s.Token)
}
// Discord's API returns a 400 Bad Request is Content-Type is set, but the
// request body is empty.
if b != nil {
req.Header.Set("Content-Type", contentType)
}
// TODO: Make a configurable static variable.
req.Header.Set("User-Agent", s.UserAgent)
cfg := newRequestConfig(s, req)
for _, opt := range options {
opt(cfg)
}
req = cfg.Request
if s.Debug {
for k, v := range req.Header {
log.Printf("API REQUEST HEADER :: [%s] = %+v\n", k, v)
}
}
resp, err := cfg.Client.Do(req)
if err != nil {
bucket.Release(nil)
return
}
defer func() {
err2 := resp.Body.Close()
if s.Debug && err2 != nil {
log.Println("error closing resp body")
}
}()
err = bucket.Release(resp.Header)
if err != nil {
return
}
response, err = ioutil.ReadAll(resp.Body)
if err != nil {
return
}
if s.Debug {
log.Printf("API RESPONSE STATUS :: %s\n", resp.Status)
for k, v := range resp.Header {
log.Printf("API RESPONSE HEADER :: [%s] = %+v\n", k, v)
}
log.Printf("API RESPONSE BODY :: [%s]\n\n\n", response)
}
switch resp.StatusCode {
case http.StatusOK:
case http.StatusCreated:
case http.StatusNoContent:
case http.StatusBadGateway:
// Retry sending request if possible
if sequence < cfg.MaxRestRetries {
s.log(LogInformational, "%s Failed (%s), Retrying...", urlStr, resp.Status)
response, err = s.RequestWithLockedBucket(method, urlStr, contentType, b, s.Ratelimiter.LockBucketObject(bucket), sequence+1, options...)
} else {
err = fmt.Errorf("Exceeded Max retries HTTP %s, %s", resp.Status, response)
}
case 429: // TOO MANY REQUESTS - Rate limiting
rl := TooManyRequests{}
err = Unmarshal(response, &rl)
if err != nil {
s.log(LogError, "rate limit unmarshal error, %s", err)
return
}
if cfg.ShouldRetryOnRateLimit {
s.log(LogInformational, "Rate Limiting %s, retry in %v", urlStr, rl.RetryAfter)
s.handleEvent(rateLimitEventType, &RateLimit{TooManyRequests: &rl, URL: urlStr})
time.Sleep(rl.RetryAfter)
// we can make the above smarter
// this method can cause longer delays than required
response, err = s.RequestWithLockedBucket(method, urlStr, contentType, b, s.Ratelimiter.LockBucketObject(bucket), sequence, options...)
} else {
err = &RateLimitError{&RateLimit{TooManyRequests: &rl, URL: urlStr}}
}
case http.StatusUnauthorized:
if strings.Index(s.Token, "Bot ") != 0 {
s.log(LogInformational, ErrUnauthorized.Error())
err = ErrUnauthorized
}
fallthrough
default: // Error condition
err = newRestError(req, resp, response)
}
return
}
func unmarshal(data []byte, v interface{}) error {
err := Unmarshal(data, v)
if err != nil {
return fmt.Errorf("%w: %s", ErrJSONUnmarshal, err)
}
return nil
}
// ------------------------------------------------------------------------------------------------
// Functions specific to Discord Users
// ------------------------------------------------------------------------------------------------
// User returns the user details of the given userID
// userID : A user ID or "@me" which is a shortcut of current user ID
func (s *Session) User(userID string, options ...RequestOption) (st *User, err error) {
body, err := s.RequestWithBucketID("GET", EndpointUser(userID), nil, EndpointUsers, options...)
if err != nil {
return
}
err = unmarshal(body, &st)
return
}
// UserAvatar is deprecated. Please use UserAvatarDecode
// userID : A user ID or "@me" which is a shortcut of current user ID
func (s *Session) UserAvatar(userID string, options ...RequestOption) (img image.Image, err error) {
u, err := s.User(userID, options...)
if err != nil {
return
}
img, err = s.UserAvatarDecode(u, options...)
return
}
// UserAvatarDecode returns an image.Image of a user's Avatar
// user : The user which avatar should be retrieved
func (s *Session) UserAvatarDecode(u *User, options ...RequestOption) (img image.Image, err error) {
body, err := s.RequestWithBucketID("GET", EndpointUserAvatar(u.ID, u.Avatar), nil, EndpointUserAvatar("", ""), options...)
if err != nil {
return
}
img, _, err = image.Decode(bytes.NewReader(body))
return
}
// UserUpdate updates current user settings.
func (s *Session) UserUpdate(username, avatar string, options ...RequestOption) (st *User, err error) {
// NOTE: Avatar must be either the hash/id of existing Avatar or
// data:image/png;base64,BASE64_STRING_OF_NEW_AVATAR_PNG
// to set a new avatar.
// If left blank, avatar will be set to null/blank
data := struct {
Username string `json:"username,omitempty"`
Avatar string `json:"avatar,omitempty"`
}{username, avatar}
body, err := s.RequestWithBucketID("PATCH", EndpointUser("@me"), data, EndpointUsers, options...)
if err != nil {
return
}
err = unmarshal(body, &st)
return
}
// UserConnections returns the user's connections
func (s *Session) UserConnections(options ...RequestOption) (conn []*UserConnection, err error) {
response, err := s.RequestWithBucketID("GET", EndpointUserConnections("@me"), nil, EndpointUserConnections("@me"), options...)
if err != nil {
return nil, err
}
err = unmarshal(response, &conn)
if err != nil {
return
}
return
}
// UserChannelCreate creates a new User (Private) Channel with another User
// recipientID : A user ID for the user to which this channel is opened with.
func (s *Session) UserChannelCreate(recipientID string, options ...RequestOption) (st *Channel, err error) {
data := struct {
RecipientID string `json:"recipient_id"`
}{recipientID}
body, err := s.RequestWithBucketID("POST", EndpointUserChannels("@me"), data, EndpointUserChannels(""), options...)
if err != nil {
return
}
err = unmarshal(body, &st)
return
}
// UserGuildMember returns a guild member object for the current user in the given Guild.
// guildID : ID of the guild
func (s *Session) UserGuildMember(guildID string, options ...RequestOption) (st *Member, err error) {
body, err := s.RequestWithBucketID("GET", EndpointUserGuildMember("@me", guildID), nil, EndpointUserGuildMember("@me", guildID), options...)
if err != nil {
return
}
err = unmarshal(body, &st)
return
}
// UserGuilds returns an array of UserGuild structures for all guilds.
// limit : The number guilds that can be returned. (max 200)
// beforeID : If provided all guilds returned will be before given ID.
// afterID : If provided all guilds returned will be after given ID.
// withCounts : Whether to include approximate member and presence counts or not.
func (s *Session) UserGuilds(limit int, beforeID, afterID string, withCounts bool, options ...RequestOption) (st []*UserGuild, err error) {
v := url.Values{}
if limit > 0 {
v.Set("limit", strconv.Itoa(limit))
}
if afterID != "" {
v.Set("after", afterID)
}
if beforeID != "" {
v.Set("before", beforeID)
}
if withCounts {
v.Set("with_counts", "true")
}
uri := EndpointUserGuilds("@me")
if len(v) > 0 {
uri += "?" + v.Encode()
}
body, err := s.RequestWithBucketID("GET", uri, nil, EndpointUserGuilds(""), options...)
if err != nil {
return
}
err = unmarshal(body, &st)
return
}
// UserChannelPermissions returns the permission of a user in a channel.
// userID : The ID of the user to calculate permissions for.
// channelID : The ID of the channel to calculate permission for.
// fetchOptions : Options used to fetch guild, member or channel if they are not present in state.
//
// NOTE: This function is now deprecated and will be removed in the future.
// Please see the same function inside state.go
func (s *Session) UserChannelPermissions(userID, channelID string, fetchOptions ...RequestOption) (apermissions int64, err error) {
// Try to just get permissions from state.
apermissions, err = s.State.UserChannelPermissions(userID, channelID)
if err == nil {
return
}
// Otherwise try get as much data from state as possible, falling back to the network.
channel, err := s.State.Channel(channelID)
if err != nil || channel == nil {
channel, err = s.Channel(channelID, fetchOptions...)
if err != nil {
return
}
}
guild, err := s.State.Guild(channel.GuildID)
if err != nil || guild == nil {
guild, err = s.Guild(channel.GuildID, fetchOptions...)
if err != nil {
return
}
}
if userID == guild.OwnerID {
apermissions = PermissionAll
return
}
member, err := s.State.Member(guild.ID, userID)
if err != nil || member == nil {
member, err = s.GuildMember(guild.ID, userID, fetchOptions...)
if err != nil {
return
}
}
return memberPermissions(guild, channel, userID, member.Roles), nil
}
// Calculates the permissions for a member.
// https://support.discord.com/hc/en-us/articles/206141927-How-is-the-permission-hierarchy-structured-
func memberPermissions(guild *Guild, channel *Channel, userID string, roles []string) (apermissions int64) {
if userID == guild.OwnerID {
apermissions = PermissionAll
return
}
for _, role := range guild.Roles {
if role.ID == guild.ID {
apermissions |= role.Permissions
break
}
}
for _, role := range guild.Roles {
for _, roleID := range roles {
if role.ID == roleID {
apermissions |= role.Permissions
break
}
}
}
if apermissions&PermissionAdministrator == PermissionAdministrator {
apermissions |= PermissionAll
}
// Apply @everyone overrides from the channel.
for _, overwrite := range channel.PermissionOverwrites {
if guild.ID == overwrite.ID {
apermissions &= ^overwrite.Deny
apermissions |= overwrite.Allow
break
}
}
var denies, allows int64
// Member overwrites can override role overrides, so do two passes
for _, overwrite := range channel.PermissionOverwrites {
for _, roleID := range roles {
if overwrite.Type == PermissionOverwriteTypeRole && roleID == overwrite.ID {
denies |= overwrite.Deny
allows |= overwrite.Allow
break
}
}
}
apermissions &= ^denies
apermissions |= allows
for _, overwrite := range channel.PermissionOverwrites {
if overwrite.Type == PermissionOverwriteTypeMember && overwrite.ID == userID {
apermissions &= ^overwrite.Deny
apermissions |= overwrite.Allow
break
}
}
if apermissions&PermissionAdministrator == PermissionAdministrator {
apermissions |= PermissionAllChannel
}
return apermissions
}
// ------------------------------------------------------------------------------------------------
// Functions specific to Discord Guilds
// ------------------------------------------------------------------------------------------------
// Guild returns a Guild structure of a specific Guild.
// guildID : The ID of a Guild
func (s *Session) Guild(guildID string, options ...RequestOption) (st *Guild, err error) {
body, err := s.RequestWithBucketID("GET", EndpointGuild(guildID), nil, EndpointGuild(guildID), options...)
if err != nil {
return
}
err = unmarshal(body, &st)
return
}
// GuildWithCounts returns a Guild structure of a specific Guild with approximate member and presence counts.
// guildID : The ID of a Guild
func (s *Session) GuildWithCounts(guildID string, options ...RequestOption) (st *Guild, err error) {
body, err := s.RequestWithBucketID("GET", EndpointGuild(guildID)+"?with_counts=true", nil, EndpointGuild(guildID), options...)
if err != nil {
return
}
err = unmarshal(body, &st)
return
}
// GuildPreview returns a GuildPreview structure of a specific public Guild.
// guildID : The ID of a Guild
func (s *Session) GuildPreview(guildID string, options ...RequestOption) (st *GuildPreview, err error) {
body, err := s.RequestWithBucketID("GET", EndpointGuildPreview(guildID), nil, EndpointGuildPreview(guildID), options...)
if err != nil {
return
}
err = unmarshal(body, &st)
return
}
// GuildCreate creates a new Guild
// name : A name for the Guild (2-100 characters)
func (s *Session) GuildCreate(name string, options ...RequestOption) (st *Guild, err error) {
data := struct {
Name string `json:"name"`
}{name}
body, err := s.RequestWithBucketID("POST", EndpointGuildCreate, data, EndpointGuildCreate, options...)
if err != nil {
return
}
err = unmarshal(body, &st)
return
}
// GuildEdit edits a new Guild
// guildID : The ID of a Guild
// g : A GuildParams struct with the values Name, Region and VerificationLevel defined.
func (s *Session) GuildEdit(guildID string, g *GuildParams, options ...RequestOption) (st *Guild, err error) {
// Bounds checking for VerificationLevel, interval: [0, 4]
if g.VerificationLevel != nil {
val := *g.VerificationLevel
if val < 0 || val > 4 {
err = ErrVerificationLevelBounds
return
}
}
// Bounds checking for regions
if g.Region != "" {
isValid := false
regions, _ := s.VoiceRegions(options...)
for _, r := range regions {
if g.Region == r.ID {
isValid = true
}
}
if !isValid {
var valid []string
for _, r := range regions {
valid = append(valid, r.ID)
}
err = fmt.Errorf("Region not a valid region (%q)", valid)
return
}
}
body, err := s.RequestWithBucketID("PATCH", EndpointGuild(guildID), g, EndpointGuild(guildID), options...)
if err != nil {
return
}
err = unmarshal(body, &st)
return
}
// GuildDelete deletes a Guild.
// guildID : The ID of a Guild
func (s *Session) GuildDelete(guildID string, options ...RequestOption) (err error) {
_, err = s.RequestWithBucketID("DELETE", EndpointGuild(guildID), nil, EndpointGuild(guildID), options...)
return
}
// GuildLeave leaves a Guild.
// guildID : The ID of a Guild
func (s *Session) GuildLeave(guildID string, options ...RequestOption) (err error) {
_, err = s.RequestWithBucketID("DELETE", EndpointUserGuild("@me", guildID), nil, EndpointUserGuild("", guildID), options...)
return
}
// GuildBans returns an array of GuildBan structures for bans in the given guild.
// guildID : The ID of a Guild
// limit : Max number of bans to return (max 1000)
// beforeID : If not empty all returned users will be after the given id
// afterID : If not empty all returned users will be before the given id
func (s *Session) GuildBans(guildID string, limit int, beforeID, afterID string, options ...RequestOption) (st []*GuildBan, err error) {
uri := EndpointGuildBans(guildID)
v := url.Values{}
if limit != 0 {
v.Set("limit", strconv.Itoa(limit))
}
if beforeID != "" {
v.Set("before", beforeID)
}
if afterID != "" {
v.Set("after", afterID)
}
if len(v) > 0 {
uri += "?" + v.Encode()
}
body, err := s.RequestWithBucketID("GET", uri, nil, EndpointGuildBans(guildID), options...)
if err != nil {
return
}
err = unmarshal(body, &st)
return
}
// GuildBanCreate bans the given user from the given guild.
// guildID : The ID of a Guild.
// userID : The ID of a User
// days : The number of days of previous comments to delete.
func (s *Session) GuildBanCreate(guildID, userID string, days int, options ...RequestOption) (err error) {
return s.GuildBanCreateWithReason(guildID, userID, "", days, options...)
}
// GuildBan finds ban by given guild and user id and returns GuildBan structure
func (s *Session) GuildBan(guildID, userID string, options ...RequestOption) (st *GuildBan, err error) {
body, err := s.RequestWithBucketID("GET", EndpointGuildBan(guildID, userID), nil, EndpointGuildBan(guildID, userID), options...)
if err != nil {
return
}
err = unmarshal(body, &st)
return
}
// GuildBanCreateWithReason bans the given user from the given guild also providing a reaso.
// guildID : The ID of a Guild.
// userID : The ID of a User
// reason : The reason for this ban
// days : The number of days of previous comments to delete.
func (s *Session) GuildBanCreateWithReason(guildID, userID, reason string, days int, options ...RequestOption) (err error) {
uri := EndpointGuildBan(guildID, userID)
queryParams := url.Values{}
if days > 0 {
queryParams.Set("delete_message_days", strconv.Itoa(days))
}
if reason != "" {
queryParams.Set("reason", reason)
}
if len(queryParams) > 0 {
uri += "?" + queryParams.Encode()
}
_, err = s.RequestWithBucketID("PUT", uri, nil, EndpointGuildBan(guildID, ""), options...)
return
}
// GuildBanDelete removes the given user from the guild bans
// guildID : The ID of a Guild.
// userID : The ID of a User
func (s *Session) GuildBanDelete(guildID, userID string, options ...RequestOption) (err error) {
_, err = s.RequestWithBucketID("DELETE", EndpointGuildBan(guildID, userID), nil, EndpointGuildBan(guildID, ""), options...)
return
}
// GuildMembers returns a list of members for a guild.
// guildID : The ID of a Guild.
// after : The id of the member to return members after
// limit : max number of members to return (max 1000)
func (s *Session) GuildMembers(guildID string, after string, limit int, options ...RequestOption) (st []*Member, err error) {
uri := EndpointGuildMembers(guildID)
v := url.Values{}
if after != "" {
v.Set("after", after)
}
if limit > 0 {
v.Set("limit", strconv.Itoa(limit))
}
if len(v) > 0 {
uri += "?" + v.Encode()
}
body, err := s.RequestWithBucketID("GET", uri, nil, EndpointGuildMembers(guildID), options...)
if err != nil {
return
}
err = unmarshal(body, &st)
return
}
// GuildMembersSearch returns a list of guild member objects whose username or nickname starts with a provided string
// guildID : The ID of a Guild
// query : Query string to match username(s) and nickname(s) against
// limit : Max number of members to return (default 1, min 1, max 1000)
func (s *Session) GuildMembersSearch(guildID, query string, limit int, options ...RequestOption) (st []*Member, err error) {
uri := EndpointGuildMembersSearch(guildID)
queryParams := url.Values{}
queryParams.Set("query", query)
if limit > 1 {
queryParams.Set("limit", strconv.Itoa(limit))
}
body, err := s.RequestWithBucketID("GET", uri+"?"+queryParams.Encode(), nil, uri, options...)
if err != nil {
return
}
err = unmarshal(body, &st)
return
}
// GuildMember returns a member of a guild.
// guildID : The ID of a Guild.
// userID : The ID of a User
func (s *Session) GuildMember(guildID, userID string, options ...RequestOption) (st *Member, err error) {
body, err := s.RequestWithBucketID("GET", EndpointGuildMember(guildID, userID), nil, EndpointGuildMember(guildID, ""), options...)
if err != nil {
return
}
err = unmarshal(body, &st)
// The returned object doesn't have the GuildID attribute so we will set it here.
st.GuildID = guildID
return
}
// GuildMemberAdd force joins a user to the guild.
// guildID : The ID of a Guild.
// userID : The ID of a User.
// data : Parameters of the user to add.
func (s *Session) GuildMemberAdd(guildID, userID string, data *GuildMemberAddParams, options ...RequestOption) (err error) {
_, err = s.RequestWithBucketID("PUT", EndpointGuildMember(guildID, userID), data, EndpointGuildMember(guildID, ""), options...)
if err != nil {
return err
}
return err
}
// GuildMemberDelete removes the given user from the given guild.
// guildID : The ID of a Guild.
// userID : The ID of a User
func (s *Session) GuildMemberDelete(guildID, userID string, options ...RequestOption) (err error) {
return s.GuildMemberDeleteWithReason(guildID, userID, "", options...)
}
// GuildMemberDeleteWithReason removes the given user from the given guild.
// guildID : The ID of a Guild.
// userID : The ID of a User
// reason : The reason for the kick
func (s *Session) GuildMemberDeleteWithReason(guildID, userID, reason string, options ...RequestOption) (err error) {
uri := EndpointGuildMember(guildID, userID)
if reason != "" {
uri += "?reason=" + url.QueryEscape(reason)
}
_, err = s.RequestWithBucketID("DELETE", uri, nil, EndpointGuildMember(guildID, ""), options...)
return
}
// GuildMemberEdit edits and returns updated member.
// guildID : The ID of a Guild.
// userID : The ID of a User.
// data : Updated GuildMember data.
func (s *Session) GuildMemberEdit(guildID, userID string, data *GuildMemberParams, options ...RequestOption) (st *Member, err error) {
var body []byte
body, err = s.RequestWithBucketID("PATCH", EndpointGuildMember(guildID, userID), data, EndpointGuildMember(guildID, ""), options...)
if err != nil {
return nil, err
}
err = unmarshal(body, &st)
return
}
// GuildMemberEditComplex edits the nickname and roles of a member.
// NOTE: deprecated, use GuildMemberEdit instead.
//
// guildID : The ID of a Guild.
// userID : The ID of a User.
// data : A GuildMemberEditData struct with the new nickname and roles
func (s *Session) GuildMemberEditComplex(guildID, userID string, data *GuildMemberParams, options ...RequestOption) (st *Member, err error) {
return s.GuildMemberEdit(guildID, userID, data, options...)
}
// GuildMemberMove moves a guild member from one voice channel to another/none
// guildID : The ID of a Guild.
// userID : The ID of a User.
// channelID : The ID of a channel to move user to or nil to remove from voice channel
//
// NOTE : I am not entirely set on the name of this function and it may change
// prior to the final 1.0.0 release of Discordgo
func (s *Session) GuildMemberMove(guildID string, userID string, channelID *string, options ...RequestOption) (err error) {
data := struct {
ChannelID *string `json:"channel_id"`
}{channelID}
_, err = s.RequestWithBucketID("PATCH", EndpointGuildMember(guildID, userID), data, EndpointGuildMember(guildID, ""), options...)
return
}
// GuildMemberNickname updates the nickname of a guild member
// guildID : The ID of a guild
// userID : The ID of a user
// userID : The ID of a user or "@me" which is a shortcut of the current user ID
// nickname : The nickname of the member, "" will reset their nickname
func (s *Session) GuildMemberNickname(guildID, userID, nickname string, options ...RequestOption) (err error) {
data := struct {
Nick string `json:"nick"`
}{nickname}
if userID == "@me" {
userID += "/nick"
}
_, err = s.RequestWithBucketID("PATCH", EndpointGuildMember(guildID, userID), data, EndpointGuildMember(guildID, ""), options...)
return
}
// GuildMemberMute server mutes a guild member
// guildID : The ID of a Guild.
// userID : The ID of a User.
// mute : boolean value for if the user should be muted
func (s *Session) GuildMemberMute(guildID string, userID string, mute bool, options ...RequestOption) (err error) {
data := struct {
Mute bool `json:"mute"`
}{mute}
_, err = s.RequestWithBucketID("PATCH", EndpointGuildMember(guildID, userID), data, EndpointGuildMember(guildID, ""), options...)
return
}
// GuildMemberTimeout times out a guild member
// guildID : The ID of a Guild.
// userID : The ID of a User.
// until : The timestamp for how long a member should be timed out. Set to nil to remove timeout.
func (s *Session) GuildMemberTimeout(guildID string, userID string, until *time.Time, options ...RequestOption) (err error) {
data := struct {
CommunicationDisabledUntil *time.Time `json:"communication_disabled_until"`
}{until}
_, err = s.RequestWithBucketID("PATCH", EndpointGuildMember(guildID, userID), data, EndpointGuildMember(guildID, ""), options...)
return
}
// GuildMemberDeafen server deafens a guild member
// guildID : The ID of a Guild.
// userID : The ID of a User.
// deaf : boolean value for if the user should be deafened
func (s *Session) GuildMemberDeafen(guildID string, userID string, deaf bool, options ...RequestOption) (err error) {
data := struct {
Deaf bool `json:"deaf"`
}{deaf}
_, err = s.RequestWithBucketID("PATCH", EndpointGuildMember(guildID, userID), data, EndpointGuildMember(guildID, ""), options...)
return
}
// GuildMemberRoleAdd adds the specified role to a given member
// guildID : The ID of a Guild.
// userID : The ID of a User.
// roleID : The ID of a Role to be assigned to the user.
func (s *Session) GuildMemberRoleAdd(guildID, userID, roleID string, options ...RequestOption) (err error) {
_, err = s.RequestWithBucketID("PUT", EndpointGuildMemberRole(guildID, userID, roleID), nil, EndpointGuildMemberRole(guildID, "", ""), options...)
return
}
// GuildMemberRoleRemove removes the specified role to a given member
// guildID : The ID of a Guild.
// userID : The ID of a User.