github.com/meowstercatel/discordgo@v0.0.0-20250615204139-29b43d676735/restapi.go (about) 1 // Discordgo - Discord bindings for Go 2 // Available at https://github.com/bwmarrin/discordgo 3 4 // Copyright 2015-2016 Bruce Marriner <bruce@sqls.net>. All rights reserved. 5 // Use of this source code is governed by a BSD-style 6 // license that can be found in the LICENSE file. 7 8 // This file contains functions for interacting with the Discord REST/JSON API 9 // at the lowest level. 10 11 package discordgo 12 13 import ( 14 "bytes" 15 "encoding/json" 16 "errors" 17 "fmt" 18 "image" 19 _ "image/jpeg" // For JPEG decoding 20 _ "image/png" // For PNG decoding 21 "io" 22 "io/ioutil" 23 "log" 24 "net/http" 25 "net/url" 26 "strconv" 27 "strings" 28 "time" 29 30 "context" 31 ) 32 33 // All error constants 34 var ( 35 ErrJSONUnmarshal = errors.New("json unmarshal") 36 ErrStatusOffline = errors.New("You can't set your Status to offline") 37 ErrVerificationLevelBounds = errors.New("VerificationLevel out of bounds, should be between 0 and 3") 38 ErrPruneDaysBounds = errors.New("the number of days should be more than or equal to 1") 39 ErrGuildNoIcon = errors.New("guild does not have an icon set") 40 ErrGuildNoSplash = errors.New("guild does not have a splash set") 41 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") 42 ) 43 44 var ( 45 // Marshal defines function used to encode JSON payloads 46 Marshal func(v interface{}) ([]byte, error) = json.Marshal 47 // Unmarshal defines function used to decode JSON payloads 48 Unmarshal func(src []byte, v interface{}) error = json.Unmarshal 49 ) 50 51 // RESTError stores error information about a request with a bad response code. 52 // Message is not always present, there are cases where api calls can fail 53 // without returning a json message. 54 type RESTError struct { 55 Request *http.Request 56 Response *http.Response 57 ResponseBody []byte 58 59 Message *APIErrorMessage // Message may be nil. 60 } 61 62 // newRestError returns a new REST API error. 63 func newRestError(req *http.Request, resp *http.Response, body []byte) *RESTError { 64 restErr := &RESTError{ 65 Request: req, 66 Response: resp, 67 ResponseBody: body, 68 } 69 70 // Attempt to decode the error and assume no message was provided if it fails 71 var msg *APIErrorMessage 72 err := Unmarshal(body, &msg) 73 if err == nil { 74 restErr.Message = msg 75 } 76 77 return restErr 78 } 79 80 // Error returns a Rest API Error with its status code and body. 81 func (r RESTError) Error() string { 82 return "HTTP " + r.Response.Status + ", " + string(r.ResponseBody) 83 } 84 85 // RateLimitError is returned when a request exceeds a rate limit 86 // and ShouldRetryOnRateLimit is false. The request may be manually 87 // retried after waiting the duration specified by RetryAfter. 88 type RateLimitError struct { 89 *RateLimit 90 } 91 92 // Error returns a rate limit error with rate limited endpoint and retry time. 93 func (e RateLimitError) Error() string { 94 return "Rate limit exceeded on " + e.URL + ", retry after " + e.RetryAfter.String() 95 } 96 97 // RequestConfig is an HTTP request configuration. 98 type RequestConfig struct { 99 Request *http.Request 100 ShouldRetryOnRateLimit bool 101 MaxRestRetries int 102 Client *http.Client 103 } 104 105 // newRequestConfig returns a new HTTP request configuration based on parameters in Session. 106 func newRequestConfig(s *Session, req *http.Request) *RequestConfig { 107 return &RequestConfig{ 108 ShouldRetryOnRateLimit: s.ShouldRetryOnRateLimit, 109 MaxRestRetries: s.MaxRestRetries, 110 Client: s.Client, 111 Request: req, 112 } 113 } 114 115 // RequestOption is a function which mutates request configuration. 116 // It can be supplied as an argument to any REST method. 117 type RequestOption func(cfg *RequestConfig) 118 119 // WithClient changes the HTTP client used for the request. 120 func WithClient(client *http.Client) RequestOption { 121 return func(cfg *RequestConfig) { 122 if client != nil { 123 cfg.Client = client 124 } 125 } 126 } 127 128 // WithRetryOnRatelimit controls whether session will retry the request on rate limit. 129 func WithRetryOnRatelimit(retry bool) RequestOption { 130 return func(cfg *RequestConfig) { 131 cfg.ShouldRetryOnRateLimit = retry 132 } 133 } 134 135 // WithRestRetries changes maximum amount of retries if request fails. 136 func WithRestRetries(max int) RequestOption { 137 return func(cfg *RequestConfig) { 138 cfg.MaxRestRetries = max 139 } 140 } 141 142 // WithHeader sets a header in the request. 143 func WithHeader(key, value string) RequestOption { 144 return func(cfg *RequestConfig) { 145 cfg.Request.Header.Set(key, value) 146 } 147 } 148 149 // WithAuditLogReason changes audit log reason associated with the request. 150 func WithAuditLogReason(reason string) RequestOption { 151 return WithHeader("X-Audit-Log-Reason", reason) 152 } 153 154 // WithLocale changes accepted locale of the request. 155 func WithLocale(locale Locale) RequestOption { 156 return WithHeader("X-Discord-Locale", string(locale)) 157 } 158 159 // WithContext changes context of the request. 160 func WithContext(ctx context.Context) RequestOption { 161 return func(cfg *RequestConfig) { 162 cfg.Request = cfg.Request.WithContext(ctx) 163 } 164 } 165 166 // Request is the same as RequestWithBucketID but the bucket id is the same as the urlStr 167 func (s *Session) Request(method, urlStr string, data interface{}, options ...RequestOption) (response []byte, err error) { 168 return s.RequestWithBucketID(method, urlStr, data, strings.SplitN(urlStr, "?", 2)[0], options...) 169 } 170 171 // RequestWithBucketID makes a (GET/POST/...) Requests to Discord REST API with JSON data. 172 func (s *Session) RequestWithBucketID(method, urlStr string, data interface{}, bucketID string, options ...RequestOption) (response []byte, err error) { 173 var body []byte 174 if data != nil { 175 body, err = Marshal(data) 176 if err != nil { 177 return 178 } 179 } 180 181 return s.RequestRaw(method, urlStr, "application/json", body, bucketID, 0, options...) 182 } 183 184 // RequestRaw makes a (GET/POST/...) Requests to Discord REST API. 185 // Preferably use the other Request* methods but this lets you send JSON directly if that's what you have. 186 // Sequence is the sequence number, if it fails with a 502 it will 187 // retry with sequence+1 until it either succeeds or sequence >= session.MaxRestRetries 188 func (s *Session) RequestRaw(method, urlStr, contentType string, b []byte, bucketID string, sequence int, options ...RequestOption) (response []byte, err error) { 189 if bucketID == "" { 190 bucketID = strings.SplitN(urlStr, "?", 2)[0] 191 } 192 return s.RequestWithLockedBucket(method, urlStr, contentType, b, s.Ratelimiter.LockBucket(bucketID), sequence, options...) 193 } 194 195 // RequestWithLockedBucket makes a request using a bucket that's already been locked 196 func (s *Session) RequestWithLockedBucket(method, urlStr, contentType string, b []byte, bucket *Bucket, sequence int, options ...RequestOption) (response []byte, err error) { 197 if s.Debug { 198 log.Printf("API REQUEST %8s :: %s\n", method, urlStr) 199 log.Printf("API REQUEST PAYLOAD :: [%s]\n", string(b)) 200 } 201 202 req, err := http.NewRequest(method, urlStr, bytes.NewBuffer(b)) 203 if err != nil { 204 bucket.Release(nil) 205 return 206 } 207 208 // Not used on initial login.. 209 // TODO: Verify if a login, otherwise complain about no-token 210 if s.Token != "" { 211 req.Header.Set("authorization", s.Token) 212 } 213 214 // Discord's API returns a 400 Bad Request is Content-Type is set, but the 215 // request body is empty. 216 if b != nil { 217 req.Header.Set("Content-Type", contentType) 218 } 219 220 // TODO: Make a configurable static variable. 221 req.Header.Set("User-Agent", s.UserAgent) 222 223 cfg := newRequestConfig(s, req) 224 for _, opt := range options { 225 opt(cfg) 226 } 227 req = cfg.Request 228 229 if s.Debug { 230 for k, v := range req.Header { 231 log.Printf("API REQUEST HEADER :: [%s] = %+v\n", k, v) 232 } 233 } 234 235 resp, err := cfg.Client.Do(req) 236 if err != nil { 237 bucket.Release(nil) 238 return 239 } 240 defer func() { 241 err2 := resp.Body.Close() 242 if s.Debug && err2 != nil { 243 log.Println("error closing resp body") 244 } 245 }() 246 247 err = bucket.Release(resp.Header) 248 if err != nil { 249 return 250 } 251 252 response, err = ioutil.ReadAll(resp.Body) 253 if err != nil { 254 return 255 } 256 257 if s.Debug { 258 259 log.Printf("API RESPONSE STATUS :: %s\n", resp.Status) 260 for k, v := range resp.Header { 261 log.Printf("API RESPONSE HEADER :: [%s] = %+v\n", k, v) 262 } 263 log.Printf("API RESPONSE BODY :: [%s]\n\n\n", response) 264 } 265 266 switch resp.StatusCode { 267 case http.StatusOK: 268 case http.StatusCreated: 269 case http.StatusNoContent: 270 case http.StatusBadGateway: 271 // Retry sending request if possible 272 if sequence < cfg.MaxRestRetries { 273 274 s.log(LogInformational, "%s Failed (%s), Retrying...", urlStr, resp.Status) 275 response, err = s.RequestWithLockedBucket(method, urlStr, contentType, b, s.Ratelimiter.LockBucketObject(bucket), sequence+1, options...) 276 } else { 277 err = fmt.Errorf("Exceeded Max retries HTTP %s, %s", resp.Status, response) 278 } 279 case 429: // TOO MANY REQUESTS - Rate limiting 280 rl := TooManyRequests{} 281 err = Unmarshal(response, &rl) 282 if err != nil { 283 s.log(LogError, "rate limit unmarshal error, %s", err) 284 return 285 } 286 287 if cfg.ShouldRetryOnRateLimit { 288 s.log(LogInformational, "Rate Limiting %s, retry in %v", urlStr, rl.RetryAfter) 289 s.handleEvent(rateLimitEventType, &RateLimit{TooManyRequests: &rl, URL: urlStr}) 290 291 time.Sleep(rl.RetryAfter) 292 // we can make the above smarter 293 // this method can cause longer delays than required 294 295 response, err = s.RequestWithLockedBucket(method, urlStr, contentType, b, s.Ratelimiter.LockBucketObject(bucket), sequence, options...) 296 } else { 297 err = &RateLimitError{&RateLimit{TooManyRequests: &rl, URL: urlStr}} 298 } 299 case http.StatusUnauthorized: 300 if strings.Index(s.Token, "Bot ") != 0 { 301 s.log(LogInformational, ErrUnauthorized.Error()) 302 err = ErrUnauthorized 303 } 304 fallthrough 305 default: // Error condition 306 err = newRestError(req, resp, response) 307 } 308 309 return 310 } 311 312 func unmarshal(data []byte, v interface{}) error { 313 err := Unmarshal(data, v) 314 if err != nil { 315 return fmt.Errorf("%w: %s", ErrJSONUnmarshal, err) 316 } 317 318 return nil 319 } 320 321 // ------------------------------------------------------------------------------------------------ 322 // Functions specific to Discord Users 323 // ------------------------------------------------------------------------------------------------ 324 325 // User returns the user details of the given userID 326 // userID : A user ID or "@me" which is a shortcut of current user ID 327 func (s *Session) User(userID string, options ...RequestOption) (st *User, err error) { 328 329 body, err := s.RequestWithBucketID("GET", EndpointUser(userID), nil, EndpointUsers, options...) 330 if err != nil { 331 return 332 } 333 334 err = unmarshal(body, &st) 335 return 336 } 337 338 func (s *Session) UserProfile(userID string, options ...RequestOption) (st *User, err error) { 339 340 body, err := s.RequestWithBucketID("GET", EndpointUsers + userID + "/profile", nil, EndpointUsers, options...) 341 if err != nil { 342 return 343 } 344 345 err = unmarshal(body, &st) 346 return 347 } 348 349 // UserAvatar is deprecated. Please use UserAvatarDecode 350 // userID : A user ID or "@me" which is a shortcut of current user ID 351 func (s *Session) UserAvatar(userID string, options ...RequestOption) (img image.Image, err error) { 352 u, err := s.User(userID, options...) 353 if err != nil { 354 return 355 } 356 img, err = s.UserAvatarDecode(u, options...) 357 return 358 } 359 360 // UserAvatarDecode returns an image.Image of a user's Avatar 361 // user : The user which avatar should be retrieved 362 func (s *Session) UserAvatarDecode(u *User, options ...RequestOption) (img image.Image, err error) { 363 body, err := s.RequestWithBucketID("GET", EndpointUserAvatar(u.ID, u.Avatar), nil, EndpointUserAvatar("", ""), options...) 364 if err != nil { 365 return 366 } 367 368 img, _, err = image.Decode(bytes.NewReader(body)) 369 return 370 } 371 372 // UserUpdate updates current user settings. 373 func (s *Session) UserUpdate(username, avatar, banner string, options ...RequestOption) (st *User, err error) { 374 375 // NOTE: Avatar must be either the hash/id of existing Avatar or 376 // data:image/png;base64,BASE64_STRING_OF_NEW_AVATAR_PNG 377 // to set a new avatar. 378 // If left blank, avatar will be set to null/blank 379 380 data := struct { 381 Username string `json:"username,omitempty"` 382 Avatar string `json:"avatar,omitempty"` 383 Banner string `json:"banner,omitempty"` 384 }{username, avatar, banner} 385 386 body, err := s.RequestWithBucketID("PATCH", EndpointUser("@me"), data, EndpointUsers, options...) 387 if err != nil { 388 return 389 } 390 391 err = unmarshal(body, &st) 392 return 393 } 394 395 // UserConnections returns the user's connections 396 func (s *Session) UserConnections(options ...RequestOption) (conn []*UserConnection, err error) { 397 response, err := s.RequestWithBucketID("GET", EndpointUserConnections("@me"), nil, EndpointUserConnections("@me"), options...) 398 if err != nil { 399 return nil, err 400 } 401 402 err = unmarshal(response, &conn) 403 if err != nil { 404 return 405 } 406 407 return 408 } 409 410 // UserChannelCreate creates a new User (Private) Channel with another User 411 // recipientID : A user ID for the user to which this channel is opened with. 412 func (s *Session) UserChannelCreate(recipientID string, options ...RequestOption) (st *Channel, err error) { 413 414 data := struct { 415 RecipientID string `json:"recipient_id"` 416 }{recipientID} 417 418 body, err := s.RequestWithBucketID("POST", EndpointUserChannels("@me"), data, EndpointUserChannels(""), options...) 419 if err != nil { 420 return 421 } 422 423 err = unmarshal(body, &st) 424 return 425 } 426 427 // UserGuildMember returns a guild member object for the current user in the given Guild. 428 // guildID : ID of the guild 429 func (s *Session) UserGuildMember(guildID string, options ...RequestOption) (st *Member, err error) { 430 body, err := s.RequestWithBucketID("GET", EndpointUserGuildMember("@me", guildID), nil, EndpointUserGuildMember("@me", guildID), options...) 431 if err != nil { 432 return 433 } 434 435 err = unmarshal(body, &st) 436 return 437 } 438 439 // UserGuilds returns an array of UserGuild structures for all guilds. 440 // limit : The number guilds that can be returned. (max 200) 441 // beforeID : If provided all guilds returned will be before given ID. 442 // afterID : If provided all guilds returned will be after given ID. 443 // withCounts : Whether to include approximate member and presence counts or not. 444 func (s *Session) UserGuilds(limit int, beforeID, afterID string, withCounts bool, options ...RequestOption) (st []*UserGuild, err error) { 445 446 v := url.Values{} 447 448 if limit > 0 { 449 v.Set("limit", strconv.Itoa(limit)) 450 } 451 if afterID != "" { 452 v.Set("after", afterID) 453 } 454 if beforeID != "" { 455 v.Set("before", beforeID) 456 } 457 if withCounts { 458 v.Set("with_counts", "true") 459 } 460 461 uri := EndpointUserGuilds("@me") 462 463 if len(v) > 0 { 464 uri += "?" + v.Encode() 465 } 466 467 body, err := s.RequestWithBucketID("GET", uri, nil, EndpointUserGuilds(""), options...) 468 if err != nil { 469 return 470 } 471 472 err = unmarshal(body, &st) 473 return 474 } 475 476 // UserChannelPermissions returns the permission of a user in a channel. 477 // userID : The ID of the user to calculate permissions for. 478 // channelID : The ID of the channel to calculate permission for. 479 // fetchOptions : Options used to fetch guild, member or channel if they are not present in state. 480 // 481 // NOTE: This function is now deprecated and will be removed in the future. 482 // Please see the same function inside state.go 483 func (s *Session) UserChannelPermissions(userID, channelID string, fetchOptions ...RequestOption) (apermissions int64, err error) { 484 // Try to just get permissions from state. 485 apermissions, err = s.State.UserChannelPermissions(userID, channelID) 486 if err == nil { 487 return 488 } 489 490 // Otherwise try get as much data from state as possible, falling back to the network. 491 channel, err := s.State.Channel(channelID) 492 if err != nil || channel == nil { 493 channel, err = s.Channel(channelID, fetchOptions...) 494 if err != nil { 495 return 496 } 497 } 498 499 guild, err := s.State.Guild(channel.GuildID) 500 if err != nil || guild == nil { 501 guild, err = s.Guild(channel.GuildID, fetchOptions...) 502 if err != nil { 503 return 504 } 505 } 506 507 if userID == guild.OwnerID { 508 apermissions = PermissionAll 509 return 510 } 511 512 member, err := s.State.Member(guild.ID, userID) 513 if err != nil || member == nil { 514 member, err = s.GuildMember(guild.ID, userID, fetchOptions...) 515 if err != nil { 516 return 517 } 518 } 519 520 return memberPermissions(guild, channel, userID, member.Roles), nil 521 } 522 523 // Calculates the permissions for a member. 524 // https://support.discord.com/hc/en-us/articles/206141927-How-is-the-permission-hierarchy-structured- 525 func memberPermissions(guild *Guild, channel *Channel, userID string, roles []string) (apermissions int64) { 526 if userID == guild.OwnerID { 527 apermissions = PermissionAll 528 return 529 } 530 531 for _, role := range guild.Roles { 532 if role.ID == guild.ID { 533 apermissions |= role.Permissions 534 break 535 } 536 } 537 538 for _, role := range guild.Roles { 539 for _, roleID := range roles { 540 if role.ID == roleID { 541 apermissions |= role.Permissions 542 break 543 } 544 } 545 } 546 547 if apermissions&PermissionAdministrator == PermissionAdministrator { 548 apermissions |= PermissionAll 549 } 550 551 // Apply @everyone overrides from the channel. 552 for _, overwrite := range channel.PermissionOverwrites { 553 if guild.ID == overwrite.ID { 554 apermissions &= ^overwrite.Deny 555 apermissions |= overwrite.Allow 556 break 557 } 558 } 559 560 var denies, allows int64 561 // Member overwrites can override role overrides, so do two passes 562 for _, overwrite := range channel.PermissionOverwrites { 563 for _, roleID := range roles { 564 if overwrite.Type == PermissionOverwriteTypeRole && roleID == overwrite.ID { 565 denies |= overwrite.Deny 566 allows |= overwrite.Allow 567 break 568 } 569 } 570 } 571 572 apermissions &= ^denies 573 apermissions |= allows 574 575 for _, overwrite := range channel.PermissionOverwrites { 576 if overwrite.Type == PermissionOverwriteTypeMember && overwrite.ID == userID { 577 apermissions &= ^overwrite.Deny 578 apermissions |= overwrite.Allow 579 break 580 } 581 } 582 583 if apermissions&PermissionAdministrator == PermissionAdministrator { 584 apermissions |= PermissionAllChannel 585 } 586 587 return apermissions 588 } 589 590 // ------------------------------------------------------------------------------------------------ 591 // Functions specific to Discord Guilds 592 // ------------------------------------------------------------------------------------------------ 593 594 // Guild returns a Guild structure of a specific Guild. 595 // guildID : The ID of a Guild 596 func (s *Session) Guild(guildID string, options ...RequestOption) (st *Guild, err error) { 597 body, err := s.RequestWithBucketID("GET", EndpointGuild(guildID), nil, EndpointGuild(guildID), options...) 598 if err != nil { 599 return 600 } 601 602 err = unmarshal(body, &st) 603 return 604 } 605 606 // GuildWithCounts returns a Guild structure of a specific Guild with approximate member and presence counts. 607 // guildID : The ID of a Guild 608 func (s *Session) GuildWithCounts(guildID string, options ...RequestOption) (st *Guild, err error) { 609 610 body, err := s.RequestWithBucketID("GET", EndpointGuild(guildID)+"?with_counts=true", nil, EndpointGuild(guildID), options...) 611 if err != nil { 612 return 613 } 614 615 err = unmarshal(body, &st) 616 return 617 } 618 619 // GuildPreview returns a GuildPreview structure of a specific public Guild. 620 // guildID : The ID of a Guild 621 func (s *Session) GuildPreview(guildID string, options ...RequestOption) (st *GuildPreview, err error) { 622 body, err := s.RequestWithBucketID("GET", EndpointGuildPreview(guildID), nil, EndpointGuildPreview(guildID), options...) 623 if err != nil { 624 return 625 } 626 627 err = unmarshal(body, &st) 628 return 629 } 630 631 // GuildCreate creates a new Guild 632 // name : A name for the Guild (2-100 characters) 633 func (s *Session) GuildCreate(name string, options ...RequestOption) (st *Guild, err error) { 634 635 data := struct { 636 Name string `json:"name"` 637 }{name} 638 639 body, err := s.RequestWithBucketID("POST", EndpointGuildCreate, data, EndpointGuildCreate, options...) 640 if err != nil { 641 return 642 } 643 644 err = unmarshal(body, &st) 645 return 646 } 647 648 // GuildEdit edits a new Guild 649 // guildID : The ID of a Guild 650 // g : A GuildParams struct with the values Name, Region and VerificationLevel defined. 651 func (s *Session) GuildEdit(guildID string, g *GuildParams, options ...RequestOption) (st *Guild, err error) { 652 653 // Bounds checking for VerificationLevel, interval: [0, 4] 654 if g.VerificationLevel != nil { 655 val := *g.VerificationLevel 656 if val < 0 || val > 4 { 657 err = ErrVerificationLevelBounds 658 return 659 } 660 } 661 662 // Bounds checking for regions 663 if g.Region != "" { 664 isValid := false 665 regions, _ := s.VoiceRegions(options...) 666 for _, r := range regions { 667 if g.Region == r.ID { 668 isValid = true 669 } 670 } 671 if !isValid { 672 var valid []string 673 for _, r := range regions { 674 valid = append(valid, r.ID) 675 } 676 err = fmt.Errorf("Region not a valid region (%q)", valid) 677 return 678 } 679 } 680 681 body, err := s.RequestWithBucketID("PATCH", EndpointGuild(guildID), g, EndpointGuild(guildID), options...) 682 if err != nil { 683 return 684 } 685 686 err = unmarshal(body, &st) 687 return 688 } 689 690 // GuildDelete deletes a Guild. 691 // guildID : The ID of a Guild 692 func (s *Session) GuildDelete(guildID string, options ...RequestOption) (err error) { 693 694 _, err = s.RequestWithBucketID("DELETE", EndpointGuild(guildID), nil, EndpointGuild(guildID), options...) 695 return 696 } 697 698 // GuildLeave leaves a Guild. 699 // guildID : The ID of a Guild 700 func (s *Session) GuildLeave(guildID string, options ...RequestOption) (err error) { 701 702 _, err = s.RequestWithBucketID("DELETE", EndpointUserGuild("@me", guildID), nil, EndpointUserGuild("", guildID), options...) 703 return 704 } 705 706 // GuildBans returns an array of GuildBan structures for bans in the given guild. 707 // guildID : The ID of a Guild 708 // limit : Max number of bans to return (max 1000) 709 // beforeID : If not empty all returned users will be after the given id 710 // afterID : If not empty all returned users will be before the given id 711 func (s *Session) GuildBans(guildID string, limit int, beforeID, afterID string, options ...RequestOption) (st []*GuildBan, err error) { 712 uri := EndpointGuildBans(guildID) 713 714 v := url.Values{} 715 if limit != 0 { 716 v.Set("limit", strconv.Itoa(limit)) 717 } 718 if beforeID != "" { 719 v.Set("before", beforeID) 720 } 721 if afterID != "" { 722 v.Set("after", afterID) 723 } 724 725 if len(v) > 0 { 726 uri += "?" + v.Encode() 727 } 728 729 body, err := s.RequestWithBucketID("GET", uri, nil, EndpointGuildBans(guildID), options...) 730 if err != nil { 731 return 732 } 733 734 err = unmarshal(body, &st) 735 736 return 737 } 738 739 // GuildBanCreate bans the given user from the given guild. 740 // guildID : The ID of a Guild. 741 // userID : The ID of a User 742 // days : The number of days of previous comments to delete. 743 func (s *Session) GuildBanCreate(guildID, userID string, days int, options ...RequestOption) (err error) { 744 return s.GuildBanCreateWithReason(guildID, userID, "", days, options...) 745 } 746 747 // GuildBan finds ban by given guild and user id and returns GuildBan structure 748 func (s *Session) GuildBan(guildID, userID string, options ...RequestOption) (st *GuildBan, err error) { 749 750 body, err := s.RequestWithBucketID("GET", EndpointGuildBan(guildID, userID), nil, EndpointGuildBan(guildID, userID), options...) 751 if err != nil { 752 return 753 } 754 755 err = unmarshal(body, &st) 756 757 return 758 } 759 760 // GuildBanCreateWithReason bans the given user from the given guild also providing a reaso. 761 // guildID : The ID of a Guild. 762 // userID : The ID of a User 763 // reason : The reason for this ban 764 // days : The number of days of previous comments to delete. 765 func (s *Session) GuildBanCreateWithReason(guildID, userID, reason string, days int, options ...RequestOption) (err error) { 766 767 uri := EndpointGuildBan(guildID, userID) 768 769 queryParams := url.Values{} 770 if days > 0 { 771 queryParams.Set("delete_message_days", strconv.Itoa(days)) 772 } 773 if reason != "" { 774 queryParams.Set("reason", reason) 775 } 776 777 if len(queryParams) > 0 { 778 uri += "?" + queryParams.Encode() 779 } 780 781 _, err = s.RequestWithBucketID("PUT", uri, nil, EndpointGuildBan(guildID, ""), options...) 782 return 783 } 784 785 // GuildBanDelete removes the given user from the guild bans 786 // guildID : The ID of a Guild. 787 // userID : The ID of a User 788 func (s *Session) GuildBanDelete(guildID, userID string, options ...RequestOption) (err error) { 789 790 _, err = s.RequestWithBucketID("DELETE", EndpointGuildBan(guildID, userID), nil, EndpointGuildBan(guildID, ""), options...) 791 return 792 } 793 794 // GuildMembers returns a list of members for a guild. 795 // guildID : The ID of a Guild. 796 // after : The id of the member to return members after 797 // limit : max number of members to return (max 1000) 798 func (s *Session) GuildMembers(guildID string, after string, limit int, options ...RequestOption) (st []*Member, err error) { 799 800 uri := EndpointGuildMembers(guildID) 801 802 v := url.Values{} 803 804 if after != "" { 805 v.Set("after", after) 806 } 807 808 if limit > 0 { 809 v.Set("limit", strconv.Itoa(limit)) 810 } 811 812 if len(v) > 0 { 813 uri += "?" + v.Encode() 814 } 815 816 body, err := s.RequestWithBucketID("GET", uri, nil, EndpointGuildMembers(guildID), options...) 817 if err != nil { 818 return 819 } 820 821 err = unmarshal(body, &st) 822 return 823 } 824 825 // GuildMembersSearch returns a list of guild member objects whose username or nickname starts with a provided string 826 // guildID : The ID of a Guild 827 // query : Query string to match username(s) and nickname(s) against 828 // limit : Max number of members to return (default 1, min 1, max 1000) 829 func (s *Session) GuildMembersSearch(guildID, query string, limit int, options ...RequestOption) (st []*Member, err error) { 830 831 uri := EndpointGuildMembersSearch(guildID) 832 833 queryParams := url.Values{} 834 queryParams.Set("query", query) 835 if limit > 1 { 836 queryParams.Set("limit", strconv.Itoa(limit)) 837 } 838 839 body, err := s.RequestWithBucketID("GET", uri+"?"+queryParams.Encode(), nil, uri, options...) 840 if err != nil { 841 return 842 } 843 844 err = unmarshal(body, &st) 845 return 846 } 847 848 // GuildMember returns a member of a guild. 849 // guildID : The ID of a Guild. 850 // userID : The ID of a User 851 func (s *Session) GuildMember(guildID, userID string, options ...RequestOption) (st *Member, err error) { 852 853 body, err := s.RequestWithBucketID("GET", EndpointGuildMember(guildID, userID), nil, EndpointGuildMember(guildID, ""), options...) 854 if err != nil { 855 return 856 } 857 858 err = unmarshal(body, &st) 859 // The returned object doesn't have the GuildID attribute so we will set it here. 860 st.GuildID = guildID 861 return 862 } 863 864 // GuildMemberAdd force joins a user to the guild. 865 // guildID : The ID of a Guild. 866 // userID : The ID of a User. 867 // data : Parameters of the user to add. 868 func (s *Session) GuildMemberAdd(guildID, userID string, data *GuildMemberAddParams, options ...RequestOption) (err error) { 869 870 _, err = s.RequestWithBucketID("PUT", EndpointGuildMember(guildID, userID), data, EndpointGuildMember(guildID, ""), options...) 871 if err != nil { 872 return err 873 } 874 875 return err 876 } 877 878 // GuildMemberDelete removes the given user from the given guild. 879 // guildID : The ID of a Guild. 880 // userID : The ID of a User 881 func (s *Session) GuildMemberDelete(guildID, userID string, options ...RequestOption) (err error) { 882 883 return s.GuildMemberDeleteWithReason(guildID, userID, "", options...) 884 } 885 886 // GuildMemberDeleteWithReason removes the given user from the given guild. 887 // guildID : The ID of a Guild. 888 // userID : The ID of a User 889 // reason : The reason for the kick 890 func (s *Session) GuildMemberDeleteWithReason(guildID, userID, reason string, options ...RequestOption) (err error) { 891 892 uri := EndpointGuildMember(guildID, userID) 893 if reason != "" { 894 uri += "?reason=" + url.QueryEscape(reason) 895 } 896 897 _, err = s.RequestWithBucketID("DELETE", uri, nil, EndpointGuildMember(guildID, ""), options...) 898 return 899 } 900 901 // GuildMemberEdit edits and returns updated member. 902 // guildID : The ID of a Guild. 903 // userID : The ID of a User. 904 // data : Updated GuildMember data. 905 func (s *Session) GuildMemberEdit(guildID, userID string, data *GuildMemberParams, options ...RequestOption) (st *Member, err error) { 906 var body []byte 907 body, err = s.RequestWithBucketID("PATCH", EndpointGuildMember(guildID, userID), data, EndpointGuildMember(guildID, ""), options...) 908 if err != nil { 909 return nil, err 910 } 911 912 err = unmarshal(body, &st) 913 return 914 } 915 916 // GuildMemberEditComplex edits the nickname and roles of a member. 917 // NOTE: deprecated, use GuildMemberEdit instead. 918 // 919 // guildID : The ID of a Guild. 920 // userID : The ID of a User. 921 // data : A GuildMemberEditData struct with the new nickname and roles 922 func (s *Session) GuildMemberEditComplex(guildID, userID string, data *GuildMemberParams, options ...RequestOption) (st *Member, err error) { 923 return s.GuildMemberEdit(guildID, userID, data, options...) 924 } 925 926 // GuildMemberMove moves a guild member from one voice channel to another/none 927 // guildID : The ID of a Guild. 928 // userID : The ID of a User. 929 // channelID : The ID of a channel to move user to or nil to remove from voice channel 930 // 931 // NOTE : I am not entirely set on the name of this function and it may change 932 // prior to the final 1.0.0 release of Discordgo 933 func (s *Session) GuildMemberMove(guildID string, userID string, channelID *string, options ...RequestOption) (err error) { 934 data := struct { 935 ChannelID *string `json:"channel_id"` 936 }{channelID} 937 938 _, err = s.RequestWithBucketID("PATCH", EndpointGuildMember(guildID, userID), data, EndpointGuildMember(guildID, ""), options...) 939 return 940 } 941 942 // GuildMemberNickname updates the nickname of a guild member 943 // guildID : The ID of a guild 944 // userID : The ID of a user 945 // userID : The ID of a user or "@me" which is a shortcut of the current user ID 946 // nickname : The nickname of the member, "" will reset their nickname 947 func (s *Session) GuildMemberNickname(guildID, userID, nickname string, options ...RequestOption) (err error) { 948 949 data := struct { 950 Nick string `json:"nick"` 951 }{nickname} 952 953 if userID == "@me" { 954 userID += "/nick" 955 } 956 957 _, err = s.RequestWithBucketID("PATCH", EndpointGuildMember(guildID, userID), data, EndpointGuildMember(guildID, ""), options...) 958 return 959 } 960 961 // GuildMemberMute server mutes a guild member 962 // guildID : The ID of a Guild. 963 // userID : The ID of a User. 964 // mute : boolean value for if the user should be muted 965 func (s *Session) GuildMemberMute(guildID string, userID string, mute bool, options ...RequestOption) (err error) { 966 data := struct { 967 Mute bool `json:"mute"` 968 }{mute} 969 970 _, err = s.RequestWithBucketID("PATCH", EndpointGuildMember(guildID, userID), data, EndpointGuildMember(guildID, ""), options...) 971 return 972 } 973 974 // GuildMemberTimeout times out a guild member 975 // guildID : The ID of a Guild. 976 // userID : The ID of a User. 977 // until : The timestamp for how long a member should be timed out. Set to nil to remove timeout. 978 func (s *Session) GuildMemberTimeout(guildID string, userID string, until *time.Time, options ...RequestOption) (err error) { 979 data := struct { 980 CommunicationDisabledUntil *time.Time `json:"communication_disabled_until"` 981 }{until} 982 983 _, err = s.RequestWithBucketID("PATCH", EndpointGuildMember(guildID, userID), data, EndpointGuildMember(guildID, ""), options...) 984 return 985 } 986 987 // GuildMemberDeafen server deafens a guild member 988 // guildID : The ID of a Guild. 989 // userID : The ID of a User. 990 // deaf : boolean value for if the user should be deafened 991 func (s *Session) GuildMemberDeafen(guildID string, userID string, deaf bool, options ...RequestOption) (err error) { 992 data := struct { 993 Deaf bool `json:"deaf"` 994 }{deaf} 995 996 _, err = s.RequestWithBucketID("PATCH", EndpointGuildMember(guildID, userID), data, EndpointGuildMember(guildID, ""), options...) 997 return 998 } 999 1000 // GuildMemberRoleAdd adds the specified role to a given member 1001 // guildID : The ID of a Guild. 1002 // userID : The ID of a User. 1003 // roleID : The ID of a Role to be assigned to the user. 1004 func (s *Session) GuildMemberRoleAdd(guildID, userID, roleID string, options ...RequestOption) (err error) { 1005 1006 _, err = s.RequestWithBucketID("PUT", EndpointGuildMemberRole(guildID, userID, roleID), nil, EndpointGuildMemberRole(guildID, "", ""), options...) 1007 1008 return 1009 } 1010 1011 // GuildMemberRoleRemove removes the specified role to a given member 1012 // guildID : The ID of a Guild. 1013 // userID : The ID of a User. 1014 // roleID : The ID of a Role to be removed from the user. 1015 func (s *Session) GuildMemberRoleRemove(guildID, userID, roleID string, options ...RequestOption) (err error) { 1016 1017 _, err = s.RequestWithBucketID("DELETE", EndpointGuildMemberRole(guildID, userID, roleID), nil, EndpointGuildMemberRole(guildID, "", ""), options...) 1018 1019 return 1020 } 1021 1022 // GuildChannels returns an array of Channel structures for all channels of a 1023 // given guild. 1024 // guildID : The ID of a Guild. 1025 func (s *Session) GuildChannels(guildID string, options ...RequestOption) (st []*Channel, err error) { 1026 1027 body, err := s.RequestRaw("GET", EndpointGuildChannels(guildID), "", nil, EndpointGuildChannels(guildID), 0, options...) 1028 if err != nil { 1029 return 1030 } 1031 1032 err = unmarshal(body, &st) 1033 1034 return 1035 } 1036 1037 // GuildChannelCreateData is provided to GuildChannelCreateComplex 1038 type GuildChannelCreateData struct { 1039 Name string `json:"name"` 1040 Type ChannelType `json:"type"` 1041 Topic string `json:"topic,omitempty"` 1042 Bitrate int `json:"bitrate,omitempty"` 1043 UserLimit int `json:"user_limit,omitempty"` 1044 RateLimitPerUser int `json:"rate_limit_per_user,omitempty"` 1045 Position int `json:"position,omitempty"` 1046 PermissionOverwrites []*PermissionOverwrite `json:"permission_overwrites,omitempty"` 1047 ParentID string `json:"parent_id,omitempty"` 1048 NSFW bool `json:"nsfw,omitempty"` 1049 } 1050 1051 // GuildChannelCreateComplex creates a new channel in the given guild 1052 // guildID : The ID of a Guild 1053 // data : A data struct describing the new Channel, Name and Type are mandatory, other fields depending on the type 1054 func (s *Session) GuildChannelCreateComplex(guildID string, data GuildChannelCreateData, options ...RequestOption) (st *Channel, err error) { 1055 body, err := s.RequestWithBucketID("POST", EndpointGuildChannels(guildID), data, EndpointGuildChannels(guildID), options...) 1056 if err != nil { 1057 return 1058 } 1059 1060 err = unmarshal(body, &st) 1061 return 1062 } 1063 1064 // GuildChannelCreate creates a new channel in the given guild 1065 // guildID : The ID of a Guild. 1066 // name : Name of the channel (2-100 chars length) 1067 // ctype : Type of the channel 1068 func (s *Session) GuildChannelCreate(guildID, name string, ctype ChannelType, options ...RequestOption) (st *Channel, err error) { 1069 return s.GuildChannelCreateComplex(guildID, GuildChannelCreateData{ 1070 Name: name, 1071 Type: ctype, 1072 }, options...) 1073 } 1074 1075 // GuildChannelsReorder updates the order of channels in a guild 1076 // guildID : The ID of a Guild. 1077 // channels : Updated channels. 1078 func (s *Session) GuildChannelsReorder(guildID string, channels []*Channel, options ...RequestOption) (err error) { 1079 1080 data := make([]struct { 1081 ID string `json:"id"` 1082 Position int `json:"position"` 1083 }, len(channels)) 1084 1085 for i, c := range channels { 1086 data[i].ID = c.ID 1087 data[i].Position = c.Position 1088 } 1089 1090 _, err = s.RequestWithBucketID("PATCH", EndpointGuildChannels(guildID), data, EndpointGuildChannels(guildID), options...) 1091 return 1092 } 1093 1094 // GuildInvites returns an array of Invite structures for the given guild 1095 // guildID : The ID of a Guild. 1096 func (s *Session) GuildInvites(guildID string, options ...RequestOption) (st []*Invite, err error) { 1097 body, err := s.RequestWithBucketID("GET", EndpointGuildInvites(guildID), nil, EndpointGuildInvites(guildID), options...) 1098 if err != nil { 1099 return 1100 } 1101 1102 err = unmarshal(body, &st) 1103 return 1104 } 1105 1106 // GuildRoles returns all roles for a given guild. 1107 // guildID : The ID of a Guild. 1108 func (s *Session) GuildRoles(guildID string, options ...RequestOption) (st []*Role, err error) { 1109 1110 body, err := s.RequestWithBucketID("GET", EndpointGuildRoles(guildID), nil, EndpointGuildRoles(guildID), options...) 1111 if err != nil { 1112 return 1113 } 1114 1115 err = unmarshal(body, &st) 1116 1117 return // TODO return pointer 1118 } 1119 1120 // GuildRoleCreate creates a new Guild Role and returns it. 1121 // guildID : The ID of a Guild. 1122 // data : New Role parameters. 1123 func (s *Session) GuildRoleCreate(guildID string, data *RoleParams, options ...RequestOption) (st *Role, err error) { 1124 body, err := s.RequestWithBucketID("POST", EndpointGuildRoles(guildID), data, EndpointGuildRoles(guildID), options...) 1125 if err != nil { 1126 return 1127 } 1128 1129 err = unmarshal(body, &st) 1130 1131 return 1132 } 1133 1134 // GuildRoleEdit updates an existing Guild Role and returns updated Role data. 1135 // guildID : The ID of a Guild. 1136 // roleID : The ID of a Role. 1137 // data : Updated Role data. 1138 func (s *Session) GuildRoleEdit(guildID, roleID string, data *RoleParams, options ...RequestOption) (st *Role, err error) { 1139 1140 // Prevent sending a color int that is too big. 1141 if data.Color != nil && *data.Color > 0xFFFFFF { 1142 return nil, fmt.Errorf("color value cannot be larger than 0xFFFFFF") 1143 } 1144 1145 body, err := s.RequestWithBucketID("PATCH", EndpointGuildRole(guildID, roleID), data, EndpointGuildRole(guildID, ""), options...) 1146 if err != nil { 1147 return 1148 } 1149 1150 err = unmarshal(body, &st) 1151 1152 return 1153 } 1154 1155 // GuildRoleReorder reoders guild roles 1156 // guildID : The ID of a Guild. 1157 // roles : A list of ordered roles. 1158 func (s *Session) GuildRoleReorder(guildID string, roles []*Role, options ...RequestOption) (st []*Role, err error) { 1159 1160 body, err := s.RequestWithBucketID("PATCH", EndpointGuildRoles(guildID), roles, EndpointGuildRoles(guildID), options...) 1161 if err != nil { 1162 return 1163 } 1164 1165 err = unmarshal(body, &st) 1166 1167 return 1168 } 1169 1170 // GuildRoleDelete deletes an existing role. 1171 // guildID : The ID of a Guild. 1172 // roleID : The ID of a Role. 1173 func (s *Session) GuildRoleDelete(guildID, roleID string, options ...RequestOption) (err error) { 1174 1175 _, err = s.RequestWithBucketID("DELETE", EndpointGuildRole(guildID, roleID), nil, EndpointGuildRole(guildID, ""), options...) 1176 1177 return 1178 } 1179 1180 // GuildPruneCount Returns the number of members that would be removed in a prune operation. 1181 // Requires 'KICK_MEMBER' permission. 1182 // guildID : The ID of a Guild. 1183 // days : The number of days to count prune for (1 or more). 1184 func (s *Session) GuildPruneCount(guildID string, days uint32, options ...RequestOption) (count uint32, err error) { 1185 count = 0 1186 1187 if days <= 0 { 1188 err = ErrPruneDaysBounds 1189 return 1190 } 1191 1192 p := struct { 1193 Pruned uint32 `json:"pruned"` 1194 }{} 1195 1196 uri := EndpointGuildPrune(guildID) + "?days=" + strconv.FormatUint(uint64(days), 10) 1197 body, err := s.RequestWithBucketID("GET", uri, nil, EndpointGuildPrune(guildID), options...) 1198 if err != nil { 1199 return 1200 } 1201 1202 err = unmarshal(body, &p) 1203 if err != nil { 1204 return 1205 } 1206 1207 count = p.Pruned 1208 1209 return 1210 } 1211 1212 // GuildPrune Begin as prune operation. Requires the 'KICK_MEMBERS' permission. 1213 // Returns an object with one 'pruned' key indicating the number of members that were removed in the prune operation. 1214 // guildID : The ID of a Guild. 1215 // days : The number of days to count prune for (1 or more). 1216 func (s *Session) GuildPrune(guildID string, days uint32, options ...RequestOption) (count uint32, err error) { 1217 1218 count = 0 1219 1220 if days <= 0 { 1221 err = ErrPruneDaysBounds 1222 return 1223 } 1224 1225 data := struct { 1226 days uint32 1227 }{days} 1228 1229 p := struct { 1230 Pruned uint32 `json:"pruned"` 1231 }{} 1232 1233 body, err := s.RequestWithBucketID("POST", EndpointGuildPrune(guildID), data, EndpointGuildPrune(guildID), options...) 1234 if err != nil { 1235 return 1236 } 1237 1238 err = unmarshal(body, &p) 1239 if err != nil { 1240 return 1241 } 1242 1243 count = p.Pruned 1244 1245 return 1246 } 1247 1248 // GuildIntegrations returns an array of Integrations for a guild. 1249 // guildID : The ID of a Guild. 1250 func (s *Session) GuildIntegrations(guildID string, options ...RequestOption) (st []*Integration, err error) { 1251 1252 body, err := s.RequestWithBucketID("GET", EndpointGuildIntegrations(guildID), nil, EndpointGuildIntegrations(guildID), options...) 1253 if err != nil { 1254 return 1255 } 1256 1257 err = unmarshal(body, &st) 1258 1259 return 1260 } 1261 1262 // GuildIntegrationCreate creates a Guild Integration. 1263 // guildID : The ID of a Guild. 1264 // integrationType : The Integration type. 1265 // integrationID : The ID of an integration. 1266 func (s *Session) GuildIntegrationCreate(guildID, integrationType, integrationID string, options ...RequestOption) (err error) { 1267 1268 data := struct { 1269 Type string `json:"type"` 1270 ID string `json:"id"` 1271 }{integrationType, integrationID} 1272 1273 _, err = s.RequestWithBucketID("POST", EndpointGuildIntegrations(guildID), data, EndpointGuildIntegrations(guildID), options...) 1274 return 1275 } 1276 1277 // GuildIntegrationEdit edits a Guild Integration. 1278 // guildID : The ID of a Guild. 1279 // integrationType : The Integration type. 1280 // integrationID : The ID of an integration. 1281 // expireBehavior : The behavior when an integration subscription lapses (see the integration object documentation). 1282 // expireGracePeriod : Period (in seconds) where the integration will ignore lapsed subscriptions. 1283 // enableEmoticons : Whether emoticons should be synced for this integration (twitch only currently). 1284 func (s *Session) GuildIntegrationEdit(guildID, integrationID string, expireBehavior, expireGracePeriod int, enableEmoticons bool, options ...RequestOption) (err error) { 1285 1286 data := struct { 1287 ExpireBehavior int `json:"expire_behavior"` 1288 ExpireGracePeriod int `json:"expire_grace_period"` 1289 EnableEmoticons bool `json:"enable_emoticons"` 1290 }{expireBehavior, expireGracePeriod, enableEmoticons} 1291 1292 _, err = s.RequestWithBucketID("PATCH", EndpointGuildIntegration(guildID, integrationID), data, EndpointGuildIntegration(guildID, ""), options...) 1293 return 1294 } 1295 1296 // GuildIntegrationDelete removes the given integration from the Guild. 1297 // guildID : The ID of a Guild. 1298 // integrationID : The ID of an integration. 1299 func (s *Session) GuildIntegrationDelete(guildID, integrationID string, options ...RequestOption) (err error) { 1300 1301 _, err = s.RequestWithBucketID("DELETE", EndpointGuildIntegration(guildID, integrationID), nil, EndpointGuildIntegration(guildID, ""), options...) 1302 return 1303 } 1304 1305 // GuildIcon returns an image.Image of a guild icon. 1306 // guildID : The ID of a Guild. 1307 func (s *Session) GuildIcon(guildID string, options ...RequestOption) (img image.Image, err error) { 1308 g, err := s.Guild(guildID, options...) 1309 if err != nil { 1310 return 1311 } 1312 1313 if g.Icon == "" { 1314 err = ErrGuildNoIcon 1315 return 1316 } 1317 1318 body, err := s.RequestWithBucketID("GET", EndpointGuildIcon(guildID, g.Icon), nil, EndpointGuildIcon(guildID, ""), options...) 1319 if err != nil { 1320 return 1321 } 1322 1323 img, _, err = image.Decode(bytes.NewReader(body)) 1324 return 1325 } 1326 1327 // GuildSplash returns an image.Image of a guild splash image. 1328 // guildID : The ID of a Guild. 1329 func (s *Session) GuildSplash(guildID string, options ...RequestOption) (img image.Image, err error) { 1330 g, err := s.Guild(guildID, options...) 1331 if err != nil { 1332 return 1333 } 1334 1335 if g.Splash == "" { 1336 err = ErrGuildNoSplash 1337 return 1338 } 1339 1340 body, err := s.RequestWithBucketID("GET", EndpointGuildSplash(guildID, g.Splash), nil, EndpointGuildSplash(guildID, ""), options...) 1341 if err != nil { 1342 return 1343 } 1344 1345 img, _, err = image.Decode(bytes.NewReader(body)) 1346 return 1347 } 1348 1349 // GuildEmbed returns the embed for a Guild. 1350 // guildID : The ID of a Guild. 1351 func (s *Session) GuildEmbed(guildID string, options ...RequestOption) (st *GuildEmbed, err error) { 1352 1353 body, err := s.RequestWithBucketID("GET", EndpointGuildEmbed(guildID), nil, EndpointGuildEmbed(guildID), options...) 1354 if err != nil { 1355 return 1356 } 1357 1358 err = unmarshal(body, &st) 1359 return 1360 } 1361 1362 // GuildEmbedEdit edits the embed of a Guild. 1363 // guildID : The ID of a Guild. 1364 // data : New GuildEmbed data. 1365 func (s *Session) GuildEmbedEdit(guildID string, data *GuildEmbed, options ...RequestOption) (err error) { 1366 _, err = s.RequestWithBucketID("PATCH", EndpointGuildEmbed(guildID), data, EndpointGuildEmbed(guildID), options...) 1367 return 1368 } 1369 1370 // GuildAuditLog returns the audit log for a Guild. 1371 // guildID : The ID of a Guild. 1372 // userID : If provided the log will be filtered for the given ID. 1373 // beforeID : If provided all log entries returned will be before the given ID. 1374 // actionType : If provided the log will be filtered for the given Action Type. 1375 // limit : The number messages that can be returned. (default 50, min 1, max 100) 1376 func (s *Session) GuildAuditLog(guildID, userID, beforeID string, actionType, limit int, options ...RequestOption) (st *GuildAuditLog, err error) { 1377 1378 uri := EndpointGuildAuditLogs(guildID) 1379 1380 v := url.Values{} 1381 if userID != "" { 1382 v.Set("user_id", userID) 1383 } 1384 if beforeID != "" { 1385 v.Set("before", beforeID) 1386 } 1387 if actionType > 0 { 1388 v.Set("action_type", strconv.Itoa(actionType)) 1389 } 1390 if limit > 0 { 1391 v.Set("limit", strconv.Itoa(limit)) 1392 } 1393 if len(v) > 0 { 1394 uri = fmt.Sprintf("%s?%s", uri, v.Encode()) 1395 } 1396 1397 body, err := s.RequestWithBucketID("GET", uri, nil, EndpointGuildAuditLogs(guildID), options...) 1398 if err != nil { 1399 return 1400 } 1401 1402 err = unmarshal(body, &st) 1403 return 1404 } 1405 1406 // GuildEmojis returns all emoji 1407 // guildID : The ID of a Guild. 1408 func (s *Session) GuildEmojis(guildID string, options ...RequestOption) (emoji []*Emoji, err error) { 1409 1410 body, err := s.RequestWithBucketID("GET", EndpointGuildEmojis(guildID), nil, EndpointGuildEmojis(guildID), options...) 1411 if err != nil { 1412 return 1413 } 1414 1415 err = unmarshal(body, &emoji) 1416 return 1417 } 1418 1419 // GuildEmoji returns specified emoji. 1420 // guildID : The ID of a Guild 1421 // emojiID : The ID of an Emoji to retrieve 1422 func (s *Session) GuildEmoji(guildID, emojiID string, options ...RequestOption) (emoji *Emoji, err error) { 1423 var body []byte 1424 body, err = s.RequestWithBucketID("GET", EndpointGuildEmoji(guildID, emojiID), nil, EndpointGuildEmoji(guildID, emojiID), options...) 1425 if err != nil { 1426 return 1427 } 1428 1429 err = unmarshal(body, &emoji) 1430 return 1431 } 1432 1433 // GuildEmojiCreate creates a new Emoji. 1434 // guildID : The ID of a Guild. 1435 // data : New Emoji data. 1436 func (s *Session) GuildEmojiCreate(guildID string, data *EmojiParams, options ...RequestOption) (emoji *Emoji, err error) { 1437 body, err := s.RequestWithBucketID("POST", EndpointGuildEmojis(guildID), data, EndpointGuildEmojis(guildID), options...) 1438 if err != nil { 1439 return 1440 } 1441 1442 err = unmarshal(body, &emoji) 1443 return 1444 } 1445 1446 // GuildEmojiEdit modifies and returns updated Emoji. 1447 // guildID : The ID of a Guild. 1448 // emojiID : The ID of an Emoji. 1449 // data : Updated Emoji data. 1450 func (s *Session) GuildEmojiEdit(guildID, emojiID string, data *EmojiParams, options ...RequestOption) (emoji *Emoji, err error) { 1451 body, err := s.RequestWithBucketID("PATCH", EndpointGuildEmoji(guildID, emojiID), data, EndpointGuildEmojis(guildID), options...) 1452 if err != nil { 1453 return 1454 } 1455 1456 err = unmarshal(body, &emoji) 1457 return 1458 } 1459 1460 // GuildEmojiDelete deletes an Emoji. 1461 // guildID : The ID of a Guild. 1462 // emojiID : The ID of an Emoji. 1463 func (s *Session) GuildEmojiDelete(guildID, emojiID string, options ...RequestOption) (err error) { 1464 1465 _, err = s.RequestWithBucketID("DELETE", EndpointGuildEmoji(guildID, emojiID), nil, EndpointGuildEmojis(guildID), options...) 1466 return 1467 } 1468 1469 // ApplicationEmojis returns all emojis for the given application 1470 // appID : ID of the application 1471 func (s *Session) ApplicationEmojis(appID string, options ...RequestOption) (emojis []*Emoji, err error) { 1472 body, err := s.RequestWithBucketID("GET", EndpointApplicationEmojis(appID), nil, EndpointApplicationEmojis(appID), options...) 1473 if err != nil { 1474 return 1475 } 1476 1477 var temp struct { 1478 Items []*Emoji `json:"items"` 1479 } 1480 1481 err = unmarshal(body, &temp) 1482 if err != nil { 1483 return 1484 } 1485 1486 emojis = temp.Items 1487 return 1488 } 1489 1490 // ApplicationEmoji returns the emoji for the given application. 1491 // appID : ID of the application 1492 // emojiID : ID of an Emoji to retrieve 1493 func (s *Session) ApplicationEmoji(appID, emojiID string, options ...RequestOption) (emoji *Emoji, err error) { 1494 var body []byte 1495 body, err = s.RequestWithBucketID("GET", EndpointApplicationEmoji(appID, emojiID), nil, EndpointApplicationEmoji(appID, emojiID), options...) 1496 if err != nil { 1497 return 1498 } 1499 1500 err = unmarshal(body, &emoji) 1501 return 1502 } 1503 1504 // ApplicationEmojiCreate creates a new Emoji for the given application. 1505 // appID : ID of the application 1506 // data : New Emoji data 1507 func (s *Session) ApplicationEmojiCreate(appID string, data *EmojiParams, options ...RequestOption) (emoji *Emoji, err error) { 1508 body, err := s.RequestWithBucketID("POST", EndpointApplicationEmojis(appID), data, EndpointApplicationEmojis(appID), options...) 1509 if err != nil { 1510 return 1511 } 1512 1513 err = unmarshal(body, &emoji) 1514 return 1515 } 1516 1517 // ApplicationEmojiEdit modifies and returns updated Emoji for the given application. 1518 // appID : ID of the application 1519 // emojiID : ID of an Emoji 1520 // data : Updated Emoji data 1521 func (s *Session) ApplicationEmojiEdit(appID string, emojiID string, data *EmojiParams, options ...RequestOption) (emoji *Emoji, err error) { 1522 body, err := s.RequestWithBucketID("PATCH", EndpointApplicationEmoji(appID, emojiID), data, EndpointApplicationEmojis(appID), options...) 1523 if err != nil { 1524 return 1525 } 1526 1527 err = unmarshal(body, &emoji) 1528 return 1529 } 1530 1531 // ApplicationEmojiDelete deletes an Emoji for the given application. 1532 // appID : ID of the application 1533 // emojiID : ID of an Emoji 1534 func (s *Session) ApplicationEmojiDelete(appID, emojiID string, options ...RequestOption) (err error) { 1535 _, err = s.RequestWithBucketID("DELETE", EndpointApplicationEmoji(appID, emojiID), nil, EndpointApplicationEmojis(appID), options...) 1536 return 1537 } 1538 1539 // GuildTemplate returns a GuildTemplate for the given code 1540 // templateCode: The Code of a GuildTemplate 1541 func (s *Session) GuildTemplate(templateCode string, options ...RequestOption) (st *GuildTemplate, err error) { 1542 1543 body, err := s.RequestWithBucketID("GET", EndpointGuildTemplate(templateCode), nil, EndpointGuildTemplate(templateCode), options...) 1544 if err != nil { 1545 return 1546 } 1547 1548 err = unmarshal(body, &st) 1549 return 1550 } 1551 1552 // GuildCreateWithTemplate creates a guild based on a GuildTemplate 1553 // templateCode: The Code of a GuildTemplate 1554 // name: The name of the guild (2-100) characters 1555 // icon: base64 encoded 128x128 image for the guild icon 1556 func (s *Session) GuildCreateWithTemplate(templateCode, name, icon string, options ...RequestOption) (st *Guild, err error) { 1557 1558 data := struct { 1559 Name string `json:"name"` 1560 Icon string `json:"icon"` 1561 }{name, icon} 1562 1563 body, err := s.RequestWithBucketID("POST", EndpointGuildTemplate(templateCode), data, EndpointGuildTemplate(templateCode), options...) 1564 if err != nil { 1565 return 1566 } 1567 1568 err = unmarshal(body, &st) 1569 return 1570 } 1571 1572 // GuildTemplates returns all of GuildTemplates 1573 // guildID: The ID of the guild 1574 func (s *Session) GuildTemplates(guildID string, options ...RequestOption) (st []*GuildTemplate, err error) { 1575 1576 body, err := s.RequestWithBucketID("GET", EndpointGuildTemplates(guildID), nil, EndpointGuildTemplates(guildID), options...) 1577 if err != nil { 1578 return 1579 } 1580 1581 err = unmarshal(body, &st) 1582 return 1583 } 1584 1585 // GuildTemplateCreate creates a template for the guild 1586 // guildID : The ID of the guild 1587 // data : Template metadata 1588 func (s *Session) GuildTemplateCreate(guildID string, data *GuildTemplateParams, options ...RequestOption) (st *GuildTemplate) { 1589 body, err := s.RequestWithBucketID("POST", EndpointGuildTemplates(guildID), data, EndpointGuildTemplates(guildID), options...) 1590 if err != nil { 1591 return 1592 } 1593 1594 err = unmarshal(body, &st) 1595 return 1596 } 1597 1598 // GuildTemplateSync syncs the template to the guild's current state 1599 // guildID: The ID of the guild 1600 // templateCode: The code of the template 1601 func (s *Session) GuildTemplateSync(guildID, templateCode string, options ...RequestOption) (err error) { 1602 1603 _, err = s.RequestWithBucketID("PUT", EndpointGuildTemplateSync(guildID, templateCode), nil, EndpointGuildTemplateSync(guildID, ""), options...) 1604 return 1605 } 1606 1607 // GuildTemplateEdit modifies the template's metadata 1608 // guildID : The ID of the guild 1609 // templateCode : The code of the template 1610 // data : New template metadata 1611 func (s *Session) GuildTemplateEdit(guildID, templateCode string, data *GuildTemplateParams, options ...RequestOption) (st *GuildTemplate, err error) { 1612 1613 body, err := s.RequestWithBucketID("PATCH", EndpointGuildTemplateSync(guildID, templateCode), data, EndpointGuildTemplateSync(guildID, ""), options...) 1614 if err != nil { 1615 return 1616 } 1617 1618 err = unmarshal(body, &st) 1619 return 1620 } 1621 1622 // GuildTemplateDelete deletes the template 1623 // guildID: The ID of the guild 1624 // templateCode: The code of the template 1625 func (s *Session) GuildTemplateDelete(guildID, templateCode string, options ...RequestOption) (err error) { 1626 1627 _, err = s.RequestWithBucketID("DELETE", EndpointGuildTemplateSync(guildID, templateCode), nil, EndpointGuildTemplateSync(guildID, ""), options...) 1628 return 1629 } 1630 1631 // ------------------------------------------------------------------------------------------------ 1632 // Functions specific to Discord Channels 1633 // ------------------------------------------------------------------------------------------------ 1634 1635 // Channel returns a Channel structure of a specific Channel. 1636 // channelID : The ID of the Channel you want returned. 1637 func (s *Session) Channel(channelID string, options ...RequestOption) (st *Channel, err error) { 1638 body, err := s.RequestWithBucketID("GET", EndpointChannel(channelID), nil, EndpointChannel(channelID), options...) 1639 if err != nil { 1640 return 1641 } 1642 1643 err = unmarshal(body, &st) 1644 return 1645 } 1646 1647 // ChannelEdit edits the given channel and returns the updated Channel data. 1648 // channelID : The ID of a Channel. 1649 // data : New Channel data. 1650 func (s *Session) ChannelEdit(channelID string, data *ChannelEdit, options ...RequestOption) (st *Channel, err error) { 1651 body, err := s.RequestWithBucketID("PATCH", EndpointChannel(channelID), data, EndpointChannel(channelID), options...) 1652 if err != nil { 1653 return 1654 } 1655 1656 err = unmarshal(body, &st) 1657 return 1658 1659 } 1660 1661 // ChannelEditComplex edits an existing channel, replacing the parameters entirely with ChannelEdit struct 1662 // NOTE: deprecated, use ChannelEdit instead 1663 // channelID : The ID of a Channel 1664 // data : The channel struct to send 1665 func (s *Session) ChannelEditComplex(channelID string, data *ChannelEdit, options ...RequestOption) (st *Channel, err error) { 1666 return s.ChannelEdit(channelID, data, options...) 1667 } 1668 1669 // ChannelDelete deletes the given channel 1670 // channelID : The ID of a Channel 1671 func (s *Session) ChannelDelete(channelID string, options ...RequestOption) (st *Channel, err error) { 1672 1673 body, err := s.RequestWithBucketID("DELETE", EndpointChannel(channelID), nil, EndpointChannel(channelID), options...) 1674 if err != nil { 1675 return 1676 } 1677 1678 err = unmarshal(body, &st) 1679 return 1680 } 1681 1682 // ChannelTyping broadcasts to all members that authenticated user is typing in 1683 // the given channel. 1684 // channelID : The ID of a Channel 1685 func (s *Session) ChannelTyping(channelID string, options ...RequestOption) (err error) { 1686 1687 _, err = s.RequestWithBucketID("POST", EndpointChannelTyping(channelID), nil, EndpointChannelTyping(channelID), options...) 1688 return 1689 } 1690 1691 // ChannelMessages returns an array of Message structures for messages within 1692 // a given channel. 1693 // channelID : The ID of a Channel. 1694 // limit : The number messages that can be returned. (max 100) 1695 // beforeID : If provided all messages returned will be before given ID. 1696 // afterID : If provided all messages returned will be after given ID. 1697 // aroundID : If provided all messages returned will be around given ID. 1698 func (s *Session) ChannelMessages(channelID string, limit int, beforeID, afterID, aroundID string, options ...RequestOption) (st []*Message, err error) { 1699 1700 uri := EndpointChannelMessages(channelID) 1701 1702 v := url.Values{} 1703 if limit > 0 { 1704 v.Set("limit", strconv.Itoa(limit)) 1705 } 1706 if afterID != "" { 1707 v.Set("after", afterID) 1708 } 1709 if beforeID != "" { 1710 v.Set("before", beforeID) 1711 } 1712 if aroundID != "" { 1713 v.Set("around", aroundID) 1714 } 1715 if len(v) > 0 { 1716 uri += "?" + v.Encode() 1717 } 1718 1719 body, err := s.RequestWithBucketID("GET", uri, nil, EndpointChannelMessages(channelID), options...) 1720 if err != nil { 1721 return 1722 } 1723 1724 err = unmarshal(body, &st) 1725 return 1726 } 1727 1728 // ChannelMessage gets a single message by ID from a given channel. 1729 // channeld : The ID of a Channel 1730 // messageID : the ID of a Message 1731 func (s *Session) ChannelMessage(channelID, messageID string, options ...RequestOption) (st *Message, err error) { 1732 1733 response, err := s.RequestWithBucketID("GET", EndpointChannelMessage(channelID, messageID), nil, EndpointChannelMessage(channelID, ""), options...) 1734 if err != nil { 1735 return 1736 } 1737 1738 err = unmarshal(response, &st) 1739 return 1740 } 1741 1742 // ChannelMessageSend sends a message to the given channel. 1743 // channelID : The ID of a Channel. 1744 // content : The message to send. 1745 func (s *Session) ChannelMessageSend(channelID string, content string, options ...RequestOption) (*Message, error) { 1746 return s.ChannelMessageSendComplex(channelID, &MessageSend{ 1747 Content: content, 1748 }, options...) 1749 } 1750 1751 var quoteEscaper = strings.NewReplacer("\\", "\\\\", `"`, "\\\"") 1752 1753 // ChannelMessageSendComplex sends a message to the given channel. 1754 // channelID : The ID of a Channel. 1755 // data : The message struct to send. 1756 func (s *Session) ChannelMessageSendComplex(channelID string, data *MessageSend, options ...RequestOption) (st *Message, err error) { 1757 // TODO: Remove this when compatibility is not required. 1758 if data.Embed != nil { 1759 if data.Embeds == nil { 1760 data.Embeds = []*MessageEmbed{data.Embed} 1761 } else { 1762 err = fmt.Errorf("cannot specify both Embed and Embeds") 1763 return 1764 } 1765 } 1766 1767 for _, embed := range data.Embeds { 1768 if embed.Type == "" { 1769 embed.Type = "rich" 1770 } 1771 } 1772 endpoint := EndpointChannelMessages(channelID) 1773 1774 // TODO: Remove this when compatibility is not required. 1775 files := data.Files 1776 if data.File != nil { 1777 if files == nil { 1778 files = []*File{data.File} 1779 } else { 1780 err = fmt.Errorf("cannot specify both File and Files") 1781 return 1782 } 1783 } 1784 1785 if data.StickerIDs != nil { 1786 if len(data.StickerIDs) > 3 { 1787 err = fmt.Errorf("cannot send more than 3 stickers") 1788 return 1789 } 1790 } 1791 1792 var response []byte 1793 if len(files) > 0 { 1794 contentType, body, encodeErr := MultipartBodyWithJSON(data, files) 1795 if encodeErr != nil { 1796 return st, encodeErr 1797 } 1798 response, err = s.RequestRaw("POST", endpoint, contentType, body, endpoint, 0, options...) 1799 } else { 1800 response, err = s.RequestWithBucketID("POST", endpoint, data, endpoint, options...) 1801 } 1802 if err != nil { 1803 return 1804 } 1805 1806 err = unmarshal(response, &st) 1807 return 1808 } 1809 1810 // ChannelMessageSendTTS sends a message to the given channel with Text to Speech. 1811 // channelID : The ID of a Channel. 1812 // content : The message to send. 1813 func (s *Session) ChannelMessageSendTTS(channelID string, content string, options ...RequestOption) (*Message, error) { 1814 return s.ChannelMessageSendComplex(channelID, &MessageSend{ 1815 Content: content, 1816 TTS: true, 1817 }, options...) 1818 } 1819 1820 // ChannelMessageSendEmbed sends a message to the given channel with embedded data. 1821 // channelID : The ID of a Channel. 1822 // embed : The embed data to send. 1823 func (s *Session) ChannelMessageSendEmbed(channelID string, embed *MessageEmbed, options ...RequestOption) (*Message, error) { 1824 return s.ChannelMessageSendEmbeds(channelID, []*MessageEmbed{embed}, options...) 1825 } 1826 1827 // ChannelMessageSendEmbeds sends a message to the given channel with multiple embedded data. 1828 // channelID : The ID of a Channel. 1829 // embeds : The embeds data to send. 1830 func (s *Session) ChannelMessageSendEmbeds(channelID string, embeds []*MessageEmbed, options ...RequestOption) (*Message, error) { 1831 return s.ChannelMessageSendComplex(channelID, &MessageSend{ 1832 Embeds: embeds, 1833 }, options...) 1834 } 1835 1836 // ChannelMessageSendReply sends a message to the given channel with reference data. 1837 // channelID : The ID of a Channel. 1838 // content : The message to send. 1839 // reference : The message reference to send. 1840 func (s *Session) ChannelMessageSendReply(channelID string, content string, reference *MessageReference, options ...RequestOption) (*Message, error) { 1841 if reference == nil { 1842 return nil, fmt.Errorf("reply attempted with nil message reference") 1843 } 1844 return s.ChannelMessageSendComplex(channelID, &MessageSend{ 1845 Content: content, 1846 Reference: reference, 1847 }, options...) 1848 } 1849 1850 // ChannelMessageSendEmbedReply sends a message to the given channel with reference data and embedded data. 1851 // channelID : The ID of a Channel. 1852 // embed : The embed data to send. 1853 // reference : The message reference to send. 1854 func (s *Session) ChannelMessageSendEmbedReply(channelID string, embed *MessageEmbed, reference *MessageReference, options ...RequestOption) (*Message, error) { 1855 return s.ChannelMessageSendEmbedsReply(channelID, []*MessageEmbed{embed}, reference, options...) 1856 } 1857 1858 // ChannelMessageSendEmbedsReply sends a message to the given channel with reference data and multiple embedded data. 1859 // channelID : The ID of a Channel. 1860 // embeds : The embeds data to send. 1861 // reference : The message reference to send. 1862 func (s *Session) ChannelMessageSendEmbedsReply(channelID string, embeds []*MessageEmbed, reference *MessageReference, options ...RequestOption) (*Message, error) { 1863 if reference == nil { 1864 return nil, fmt.Errorf("reply attempted with nil message reference") 1865 } 1866 return s.ChannelMessageSendComplex(channelID, &MessageSend{ 1867 Embeds: embeds, 1868 Reference: reference, 1869 }, options...) 1870 } 1871 1872 // ChannelMessageEdit edits an existing message, replacing it entirely with 1873 // the given content. 1874 // channelID : The ID of a Channel 1875 // messageID : The ID of a Message 1876 // content : The contents of the message 1877 func (s *Session) ChannelMessageEdit(channelID, messageID, content string, options ...RequestOption) (*Message, error) { 1878 return s.ChannelMessageEditComplex(NewMessageEdit(channelID, messageID).SetContent(content), options...) 1879 } 1880 1881 // ChannelMessageEditComplex edits an existing message, replacing it entirely with 1882 // the given MessageEdit struct 1883 func (s *Session) ChannelMessageEditComplex(m *MessageEdit, options ...RequestOption) (st *Message, err error) { 1884 // TODO: Remove this when compatibility is not required. 1885 if m.Embed != nil { 1886 if m.Embeds == nil { 1887 m.Embeds = &[]*MessageEmbed{m.Embed} 1888 } else { 1889 err = fmt.Errorf("cannot specify both Embed and Embeds") 1890 return 1891 } 1892 } 1893 1894 if m.Embeds != nil { 1895 for _, embed := range *m.Embeds { 1896 if embed.Type == "" { 1897 embed.Type = "rich" 1898 } 1899 } 1900 } 1901 1902 endpoint := EndpointChannelMessage(m.Channel, m.ID) 1903 1904 var response []byte 1905 if len(m.Files) > 0 { 1906 contentType, body, encodeErr := MultipartBodyWithJSON(m, m.Files) 1907 if encodeErr != nil { 1908 return st, encodeErr 1909 } 1910 response, err = s.RequestRaw("PATCH", endpoint, contentType, body, EndpointChannelMessage(m.Channel, ""), 0, options...) 1911 } else { 1912 response, err = s.RequestWithBucketID("PATCH", endpoint, m, EndpointChannelMessage(m.Channel, ""), options...) 1913 } 1914 if err != nil { 1915 return 1916 } 1917 1918 err = unmarshal(response, &st) 1919 return 1920 } 1921 1922 // ChannelMessageEditEmbed edits an existing message with embedded data. 1923 // channelID : The ID of a Channel 1924 // messageID : The ID of a Message 1925 // embed : The embed data to send 1926 func (s *Session) ChannelMessageEditEmbed(channelID, messageID string, embed *MessageEmbed, options ...RequestOption) (*Message, error) { 1927 return s.ChannelMessageEditEmbeds(channelID, messageID, []*MessageEmbed{embed}, options...) 1928 } 1929 1930 // ChannelMessageEditEmbeds edits an existing message with multiple embedded data. 1931 // channelID : The ID of a Channel 1932 // messageID : The ID of a Message 1933 // embeds : The embeds data to send 1934 func (s *Session) ChannelMessageEditEmbeds(channelID, messageID string, embeds []*MessageEmbed, options ...RequestOption) (*Message, error) { 1935 return s.ChannelMessageEditComplex(NewMessageEdit(channelID, messageID).SetEmbeds(embeds), options...) 1936 } 1937 1938 // ChannelMessageDelete deletes a message from the Channel. 1939 func (s *Session) ChannelMessageDelete(channelID, messageID string, options ...RequestOption) (err error) { 1940 1941 _, err = s.RequestWithBucketID("DELETE", EndpointChannelMessage(channelID, messageID), nil, EndpointChannelMessage(channelID, ""), options...) 1942 return 1943 } 1944 1945 // ChannelMessagesBulkDelete bulk deletes the messages from the channel for the provided messageIDs. 1946 // If only one messageID is in the slice call channelMessageDelete function. 1947 // If the slice is empty do nothing. 1948 // channelID : The ID of the channel for the messages to delete. 1949 // messages : The IDs of the messages to be deleted. A slice of string IDs. A maximum of 100 messages. 1950 func (s *Session) ChannelMessagesBulkDelete(channelID string, messages []string, options ...RequestOption) (err error) { 1951 1952 if len(messages) == 0 { 1953 return 1954 } 1955 1956 if len(messages) == 1 { 1957 err = s.ChannelMessageDelete(channelID, messages[0], options...) 1958 return 1959 } 1960 1961 if len(messages) > 100 { 1962 messages = messages[:100] 1963 } 1964 1965 data := struct { 1966 Messages []string `json:"messages"` 1967 }{messages} 1968 1969 _, err = s.RequestWithBucketID("POST", EndpointChannelMessagesBulkDelete(channelID), data, EndpointChannelMessagesBulkDelete(channelID), options...) 1970 return 1971 } 1972 1973 // ChannelMessagePin pins a message within a given channel. 1974 // channelID: The ID of a channel. 1975 // messageID: The ID of a message. 1976 func (s *Session) ChannelMessagePin(channelID, messageID string, options ...RequestOption) (err error) { 1977 1978 _, err = s.RequestWithBucketID("PUT", EndpointChannelMessagePin(channelID, messageID), nil, EndpointChannelMessagePin(channelID, ""), options...) 1979 return 1980 } 1981 1982 // ChannelMessageUnpin unpins a message within a given channel. 1983 // channelID: The ID of a channel. 1984 // messageID: The ID of a message. 1985 func (s *Session) ChannelMessageUnpin(channelID, messageID string, options ...RequestOption) (err error) { 1986 1987 _, err = s.RequestWithBucketID("DELETE", EndpointChannelMessagePin(channelID, messageID), nil, EndpointChannelMessagePin(channelID, ""), options...) 1988 return 1989 } 1990 1991 // ChannelMessagesPinned returns an array of Message structures for pinned messages 1992 // within a given channel 1993 // channelID : The ID of a Channel. 1994 func (s *Session) ChannelMessagesPinned(channelID string, options ...RequestOption) (st []*Message, err error) { 1995 1996 body, err := s.RequestWithBucketID("GET", EndpointChannelMessagesPins(channelID), nil, EndpointChannelMessagesPins(channelID), options...) 1997 1998 if err != nil { 1999 return 2000 } 2001 2002 err = unmarshal(body, &st) 2003 return 2004 } 2005 2006 // ChannelFileSend sends a file to the given channel. 2007 // channelID : The ID of a Channel. 2008 // name: The name of the file. 2009 // io.Reader : A reader for the file contents. 2010 func (s *Session) ChannelFileSend(channelID, name string, r io.Reader, options ...RequestOption) (*Message, error) { 2011 return s.ChannelMessageSendComplex(channelID, &MessageSend{File: &File{Name: name, Reader: r}}, options...) 2012 } 2013 2014 // ChannelFileSendWithMessage sends a file to the given channel with an message. 2015 // DEPRECATED. Use ChannelMessageSendComplex instead. 2016 // channelID : The ID of a Channel. 2017 // content: Optional Message content. 2018 // name: The name of the file. 2019 // io.Reader : A reader for the file contents. 2020 func (s *Session) ChannelFileSendWithMessage(channelID, content string, name string, r io.Reader, options ...RequestOption) (*Message, error) { 2021 return s.ChannelMessageSendComplex(channelID, &MessageSend{File: &File{Name: name, Reader: r}, Content: content}, options...) 2022 } 2023 2024 // ChannelInvites returns an array of Invite structures for the given channel 2025 // channelID : The ID of a Channel 2026 func (s *Session) ChannelInvites(channelID string, options ...RequestOption) (st []*Invite, err error) { 2027 2028 body, err := s.RequestWithBucketID("GET", EndpointChannelInvites(channelID), nil, EndpointChannelInvites(channelID), options...) 2029 if err != nil { 2030 return 2031 } 2032 2033 err = unmarshal(body, &st) 2034 return 2035 } 2036 2037 // ChannelInviteCreate creates a new invite for the given channel. 2038 // channelID : The ID of a Channel 2039 // i : An Invite struct with the values MaxAge, MaxUses and Temporary defined. 2040 func (s *Session) ChannelInviteCreate(channelID string, i Invite, options ...RequestOption) (st *Invite, err error) { 2041 2042 data := struct { 2043 MaxAge int `json:"max_age"` 2044 MaxUses int `json:"max_uses"` 2045 Temporary bool `json:"temporary"` 2046 Unique bool `json:"unique"` 2047 }{i.MaxAge, i.MaxUses, i.Temporary, i.Unique} 2048 2049 body, err := s.RequestWithBucketID("POST", EndpointChannelInvites(channelID), data, EndpointChannelInvites(channelID), options...) 2050 if err != nil { 2051 return 2052 } 2053 2054 err = unmarshal(body, &st) 2055 return 2056 } 2057 2058 // ChannelPermissionSet creates a Permission Override for the given channel. 2059 // NOTE: This func name may changed. Using Set instead of Create because 2060 // you can both create a new override or update an override with this function. 2061 func (s *Session) ChannelPermissionSet(channelID, targetID string, targetType PermissionOverwriteType, allow, deny int64, options ...RequestOption) (err error) { 2062 2063 data := struct { 2064 ID string `json:"id"` 2065 Type PermissionOverwriteType `json:"type"` 2066 Allow int64 `json:"allow,string"` 2067 Deny int64 `json:"deny,string"` 2068 }{targetID, targetType, allow, deny} 2069 2070 _, err = s.RequestWithBucketID("PUT", EndpointChannelPermission(channelID, targetID), data, EndpointChannelPermission(channelID, ""), options...) 2071 return 2072 } 2073 2074 // ChannelPermissionDelete deletes a specific permission override for the given channel. 2075 // NOTE: Name of this func may change. 2076 func (s *Session) ChannelPermissionDelete(channelID, targetID string, options ...RequestOption) (err error) { 2077 2078 _, err = s.RequestWithBucketID("DELETE", EndpointChannelPermission(channelID, targetID), nil, EndpointChannelPermission(channelID, ""), options...) 2079 return 2080 } 2081 2082 // ChannelMessageCrosspost cross posts a message in a news channel to followers 2083 // of the channel 2084 // channelID : The ID of a Channel 2085 // messageID : The ID of a Message 2086 func (s *Session) ChannelMessageCrosspost(channelID, messageID string, options ...RequestOption) (st *Message, err error) { 2087 2088 endpoint := EndpointChannelMessageCrosspost(channelID, messageID) 2089 2090 body, err := s.RequestWithBucketID("POST", endpoint, nil, endpoint, options...) 2091 if err != nil { 2092 return 2093 } 2094 2095 err = unmarshal(body, &st) 2096 return 2097 } 2098 2099 // ChannelNewsFollow follows a news channel in the targetID 2100 // channelID : The ID of a News Channel 2101 // targetID : The ID of a Channel where the News Channel should post to 2102 func (s *Session) ChannelNewsFollow(channelID, targetID string, options ...RequestOption) (st *ChannelFollow, err error) { 2103 2104 endpoint := EndpointChannelFollow(channelID) 2105 2106 data := struct { 2107 WebhookChannelID string `json:"webhook_channel_id"` 2108 }{targetID} 2109 2110 body, err := s.RequestWithBucketID("POST", endpoint, data, endpoint, options...) 2111 if err != nil { 2112 return 2113 } 2114 2115 err = unmarshal(body, &st) 2116 return 2117 } 2118 2119 // ------------------------------------------------------------------------------------------------ 2120 // Functions specific to Discord Invites 2121 // ------------------------------------------------------------------------------------------------ 2122 2123 // Invite returns an Invite structure of the given invite 2124 // inviteID : The invite code 2125 func (s *Session) Invite(inviteID string, options ...RequestOption) (st *Invite, err error) { 2126 2127 body, err := s.RequestWithBucketID("GET", EndpointInvite(inviteID), nil, EndpointInvite(""), options...) 2128 if err != nil { 2129 return 2130 } 2131 2132 err = unmarshal(body, &st) 2133 return 2134 } 2135 2136 // InviteWithCounts returns an Invite structure of the given invite including approximate member counts 2137 // inviteID : The invite code 2138 func (s *Session) InviteWithCounts(inviteID string, options ...RequestOption) (st *Invite, err error) { 2139 2140 body, err := s.RequestWithBucketID("GET", EndpointInvite(inviteID)+"?with_counts=true", nil, EndpointInvite(""), options...) 2141 if err != nil { 2142 return 2143 } 2144 2145 err = unmarshal(body, &st) 2146 return 2147 } 2148 2149 // InviteComplex returns an Invite structure of the given invite including specified fields. 2150 // inviteID : The invite code 2151 // guildScheduledEventID : If specified, includes specified guild scheduled event. 2152 // withCounts : Whether to include approximate member counts or not 2153 // withExpiration : Whether to include expiration time or not 2154 func (s *Session) InviteComplex(inviteID, guildScheduledEventID string, withCounts, withExpiration bool, options ...RequestOption) (st *Invite, err error) { 2155 endpoint := EndpointInvite(inviteID) 2156 v := url.Values{} 2157 if guildScheduledEventID != "" { 2158 v.Set("guild_scheduled_event_id", guildScheduledEventID) 2159 } 2160 if withCounts { 2161 v.Set("with_counts", "true") 2162 } 2163 if withExpiration { 2164 v.Set("with_expiration", "true") 2165 } 2166 2167 if len(v) != 0 { 2168 endpoint += "?" + v.Encode() 2169 } 2170 2171 body, err := s.RequestWithBucketID("GET", endpoint, nil, EndpointInvite(""), options...) 2172 if err != nil { 2173 return 2174 } 2175 2176 err = unmarshal(body, &st) 2177 return 2178 } 2179 2180 // InviteDelete deletes an existing invite 2181 // inviteID : the code of an invite 2182 func (s *Session) InviteDelete(inviteID string, options ...RequestOption) (st *Invite, err error) { 2183 2184 body, err := s.RequestWithBucketID("DELETE", EndpointInvite(inviteID), nil, EndpointInvite(""), options...) 2185 if err != nil { 2186 return 2187 } 2188 2189 err = unmarshal(body, &st) 2190 return 2191 } 2192 2193 // InviteAccept accepts an Invite to a Guild or Channel 2194 // inviteID : The invite code 2195 func (s *Session) InviteAccept(inviteID string, options ...RequestOption) (st *Invite, err error) { 2196 2197 body, err := s.RequestWithBucketID("POST", EndpointInvite(inviteID), nil, EndpointInvite(""), options...) 2198 if err != nil { 2199 return 2200 } 2201 2202 err = unmarshal(body, &st) 2203 return 2204 } 2205 2206 // ------------------------------------------------------------------------------------------------ 2207 // Functions specific to Discord Voice 2208 // ------------------------------------------------------------------------------------------------ 2209 2210 // VoiceRegions returns the voice server regions 2211 func (s *Session) VoiceRegions(options ...RequestOption) (st []*VoiceRegion, err error) { 2212 2213 body, err := s.RequestWithBucketID("GET", EndpointVoiceRegions, nil, EndpointVoiceRegions, options...) 2214 if err != nil { 2215 return 2216 } 2217 2218 err = unmarshal(body, &st) 2219 return 2220 } 2221 2222 // ------------------------------------------------------------------------------------------------ 2223 // Functions specific to Discord Websockets 2224 // ------------------------------------------------------------------------------------------------ 2225 2226 // Gateway returns the websocket Gateway address 2227 func (s *Session) Gateway(options ...RequestOption) (gateway string, err error) { 2228 2229 response, err := s.RequestWithBucketID("GET", EndpointGateway, nil, EndpointGateway, options...) 2230 if err != nil { 2231 return 2232 } 2233 2234 temp := struct { 2235 URL string `json:"url"` 2236 }{} 2237 2238 err = unmarshal(response, &temp) 2239 if err != nil { 2240 return 2241 } 2242 2243 gateway = temp.URL 2244 2245 // Ensure the gateway always has a trailing slash. 2246 // MacOS will fail to connect if we add query params without a trailing slash on the base domain. 2247 if !strings.HasSuffix(gateway, "/") { 2248 gateway += "/" 2249 } 2250 2251 return 2252 } 2253 2254 // GatewayBot returns the websocket Gateway address and the recommended number of shards 2255 func (s *Session) GatewayBot(options ...RequestOption) (st *GatewayBotResponse, err error) { 2256 2257 response, err := s.RequestWithBucketID("GET", EndpointGatewayBot, nil, EndpointGatewayBot, options...) 2258 if err != nil { 2259 return 2260 } 2261 2262 err = unmarshal(response, &st) 2263 if err != nil { 2264 return 2265 } 2266 2267 // Ensure the gateway always has a trailing slash. 2268 // MacOS will fail to connect if we add query params without a trailing slash on the base domain. 2269 if !strings.HasSuffix(st.URL, "/") { 2270 st.URL += "/" 2271 } 2272 2273 return 2274 } 2275 2276 // Functions specific to Webhooks 2277 2278 // WebhookCreate returns a new Webhook. 2279 // channelID: The ID of a Channel. 2280 // name : The name of the webhook. 2281 // avatar : The avatar of the webhook. 2282 func (s *Session) WebhookCreate(channelID, name, avatar string, options ...RequestOption) (st *Webhook, err error) { 2283 2284 data := struct { 2285 Name string `json:"name"` 2286 Avatar string `json:"avatar,omitempty"` 2287 }{name, avatar} 2288 2289 body, err := s.RequestWithBucketID("POST", EndpointChannelWebhooks(channelID), data, EndpointChannelWebhooks(channelID), options...) 2290 if err != nil { 2291 return 2292 } 2293 2294 err = unmarshal(body, &st) 2295 2296 return 2297 } 2298 2299 // ChannelWebhooks returns all webhooks for a given channel. 2300 // channelID: The ID of a channel. 2301 func (s *Session) ChannelWebhooks(channelID string, options ...RequestOption) (st []*Webhook, err error) { 2302 2303 body, err := s.RequestWithBucketID("GET", EndpointChannelWebhooks(channelID), nil, EndpointChannelWebhooks(channelID), options...) 2304 if err != nil { 2305 return 2306 } 2307 2308 err = unmarshal(body, &st) 2309 2310 return 2311 } 2312 2313 // GuildWebhooks returns all webhooks for a given guild. 2314 // guildID: The ID of a Guild. 2315 func (s *Session) GuildWebhooks(guildID string, options ...RequestOption) (st []*Webhook, err error) { 2316 2317 body, err := s.RequestWithBucketID("GET", EndpointGuildWebhooks(guildID), nil, EndpointGuildWebhooks(guildID), options...) 2318 if err != nil { 2319 return 2320 } 2321 2322 err = unmarshal(body, &st) 2323 2324 return 2325 } 2326 2327 // Webhook returns a webhook for a given ID 2328 // webhookID: The ID of a webhook. 2329 func (s *Session) Webhook(webhookID string, options ...RequestOption) (st *Webhook, err error) { 2330 2331 body, err := s.RequestWithBucketID("GET", EndpointWebhook(webhookID), nil, EndpointWebhooks, options...) 2332 if err != nil { 2333 return 2334 } 2335 2336 err = unmarshal(body, &st) 2337 2338 return 2339 } 2340 2341 // WebhookWithToken returns a webhook for a given ID 2342 // webhookID: The ID of a webhook. 2343 // token : The auth token for the webhook. 2344 func (s *Session) WebhookWithToken(webhookID, token string, options ...RequestOption) (st *Webhook, err error) { 2345 2346 body, err := s.RequestWithBucketID("GET", EndpointWebhookToken(webhookID, token), nil, EndpointWebhookToken("", ""), options...) 2347 if err != nil { 2348 return 2349 } 2350 2351 err = unmarshal(body, &st) 2352 2353 return 2354 } 2355 2356 // WebhookEdit updates an existing Webhook. 2357 // webhookID: The ID of a webhook. 2358 // name : The name of the webhook. 2359 // avatar : The avatar of the webhook. 2360 func (s *Session) WebhookEdit(webhookID, name, avatar, channelID string, options ...RequestOption) (st *Webhook, err error) { 2361 2362 data := struct { 2363 Name string `json:"name,omitempty"` 2364 Avatar string `json:"avatar,omitempty"` 2365 ChannelID string `json:"channel_id,omitempty"` 2366 }{name, avatar, channelID} 2367 2368 body, err := s.RequestWithBucketID("PATCH", EndpointWebhook(webhookID), data, EndpointWebhooks, options...) 2369 if err != nil { 2370 return 2371 } 2372 2373 err = unmarshal(body, &st) 2374 2375 return 2376 } 2377 2378 // WebhookEditWithToken updates an existing Webhook with an auth token. 2379 // webhookID: The ID of a webhook. 2380 // token : The auth token for the webhook. 2381 // name : The name of the webhook. 2382 // avatar : The avatar of the webhook. 2383 func (s *Session) WebhookEditWithToken(webhookID, token, name, avatar string, options ...RequestOption) (st *Webhook, err error) { 2384 2385 data := struct { 2386 Name string `json:"name,omitempty"` 2387 Avatar string `json:"avatar,omitempty"` 2388 }{name, avatar} 2389 2390 var body []byte 2391 body, err = s.RequestWithBucketID("PATCH", EndpointWebhookToken(webhookID, token), data, EndpointWebhookToken("", ""), options...) 2392 if err != nil { 2393 return 2394 } 2395 2396 err = unmarshal(body, &st) 2397 2398 return 2399 } 2400 2401 // WebhookDelete deletes a webhook for a given ID 2402 // webhookID: The ID of a webhook. 2403 func (s *Session) WebhookDelete(webhookID string, options ...RequestOption) (err error) { 2404 2405 _, err = s.RequestWithBucketID("DELETE", EndpointWebhook(webhookID), nil, EndpointWebhooks, options...) 2406 2407 return 2408 } 2409 2410 // WebhookDeleteWithToken deletes a webhook for a given ID with an auth token. 2411 // webhookID: The ID of a webhook. 2412 // token : The auth token for the webhook. 2413 func (s *Session) WebhookDeleteWithToken(webhookID, token string, options ...RequestOption) (st *Webhook, err error) { 2414 2415 body, err := s.RequestWithBucketID("DELETE", EndpointWebhookToken(webhookID, token), nil, EndpointWebhookToken("", ""), options...) 2416 if err != nil { 2417 return 2418 } 2419 2420 err = unmarshal(body, &st) 2421 2422 return 2423 } 2424 2425 func (s *Session) webhookExecute(webhookID, token string, wait bool, threadID string, data *WebhookParams, options ...RequestOption) (st *Message, err error) { 2426 uri := EndpointWebhookToken(webhookID, token) 2427 2428 v := url.Values{} 2429 if wait { 2430 v.Set("wait", "true") 2431 } 2432 2433 if threadID != "" { 2434 v.Set("thread_id", threadID) 2435 } 2436 if len(v) != 0 { 2437 uri += "?" + v.Encode() 2438 } 2439 2440 var response []byte 2441 if len(data.Files) > 0 { 2442 contentType, body, encodeErr := MultipartBodyWithJSON(data, data.Files) 2443 if encodeErr != nil { 2444 return st, encodeErr 2445 } 2446 2447 response, err = s.RequestRaw("POST", uri, contentType, body, uri, 0, options...) 2448 } else { 2449 response, err = s.RequestWithBucketID("POST", uri, data, uri, options...) 2450 } 2451 if !wait || err != nil { 2452 return 2453 } 2454 2455 err = unmarshal(response, &st) 2456 return 2457 } 2458 2459 // WebhookExecute executes a webhook. 2460 // webhookID: The ID of a webhook. 2461 // token : The auth token for the webhook 2462 // wait : Waits for server confirmation of message send and ensures that the return struct is populated (it is nil otherwise) 2463 func (s *Session) WebhookExecute(webhookID, token string, wait bool, data *WebhookParams, options ...RequestOption) (st *Message, err error) { 2464 return s.webhookExecute(webhookID, token, wait, "", data, options...) 2465 } 2466 2467 // WebhookThreadExecute executes a webhook in a thread. 2468 // webhookID: The ID of a webhook. 2469 // token : The auth token for the webhook 2470 // wait : Waits for server confirmation of message send and ensures that the return struct is populated (it is nil otherwise) 2471 // threadID : Sends a message to the specified thread within a webhook's channel. The thread will automatically be unarchived. 2472 func (s *Session) WebhookThreadExecute(webhookID, token string, wait bool, threadID string, data *WebhookParams, options ...RequestOption) (st *Message, err error) { 2473 return s.webhookExecute(webhookID, token, wait, threadID, data, options...) 2474 } 2475 2476 // WebhookMessage gets a webhook message. 2477 // webhookID : The ID of a webhook 2478 // token : The auth token for the webhook 2479 // messageID : The ID of message to get 2480 func (s *Session) WebhookMessage(webhookID, token, messageID string, options ...RequestOption) (message *Message, err error) { 2481 uri := EndpointWebhookMessage(webhookID, token, messageID) 2482 2483 body, err := s.RequestWithBucketID("GET", uri, nil, EndpointWebhookToken("", ""), options...) 2484 if err != nil { 2485 return 2486 } 2487 2488 err = Unmarshal(body, &message) 2489 2490 return 2491 } 2492 2493 // WebhookMessageEdit edits a webhook message and returns a new one. 2494 // webhookID : The ID of a webhook 2495 // token : The auth token for the webhook 2496 // messageID : The ID of message to edit 2497 func (s *Session) WebhookMessageEdit(webhookID, token, messageID string, data *WebhookEdit, options ...RequestOption) (st *Message, err error) { 2498 uri := EndpointWebhookMessage(webhookID, token, messageID) 2499 2500 var response []byte 2501 if len(data.Files) > 0 { 2502 contentType, body, err := MultipartBodyWithJSON(data, data.Files) 2503 if err != nil { 2504 return nil, err 2505 } 2506 2507 response, err = s.RequestRaw("PATCH", uri, contentType, body, uri, 0, options...) 2508 if err != nil { 2509 return nil, err 2510 } 2511 } else { 2512 response, err = s.RequestWithBucketID("PATCH", uri, data, EndpointWebhookToken("", ""), options...) 2513 2514 if err != nil { 2515 return nil, err 2516 } 2517 } 2518 2519 err = unmarshal(response, &st) 2520 return 2521 } 2522 2523 // WebhookMessageDelete deletes a webhook message. 2524 // webhookID : The ID of a webhook 2525 // token : The auth token for the webhook 2526 // messageID : The ID of a message to edit 2527 func (s *Session) WebhookMessageDelete(webhookID, token, messageID string, options ...RequestOption) (err error) { 2528 uri := EndpointWebhookMessage(webhookID, token, messageID) 2529 2530 _, err = s.RequestWithBucketID("DELETE", uri, nil, EndpointWebhookToken("", ""), options...) 2531 return 2532 } 2533 2534 // MessageReactionAdd creates an emoji reaction to a message. 2535 // channelID : The channel ID. 2536 // messageID : The message ID. 2537 // emojiID : Either the unicode emoji for the reaction, or a guild emoji identifier in name:id format (e.g. "hello:1234567654321") 2538 func (s *Session) MessageReactionAdd(channelID, messageID, emojiID string, options ...RequestOption) error { 2539 2540 // emoji such as #⃣ need to have # escaped 2541 emojiID = strings.Replace(emojiID, "#", "%23", -1) 2542 _, err := s.RequestWithBucketID("PUT", EndpointMessageReaction(channelID, messageID, emojiID, "@me"), nil, EndpointMessageReaction(channelID, "", "", ""), options...) 2543 2544 return err 2545 } 2546 2547 // MessageReactionRemove deletes an emoji reaction to a message. 2548 // channelID : The channel ID. 2549 // messageID : The message ID. 2550 // emojiID : Either the unicode emoji for the reaction, or a guild emoji identifier. 2551 // userID : @me or ID of the user to delete the reaction for. 2552 func (s *Session) MessageReactionRemove(channelID, messageID, emojiID, userID string, options ...RequestOption) error { 2553 2554 // emoji such as #⃣ need to have # escaped 2555 emojiID = strings.Replace(emojiID, "#", "%23", -1) 2556 _, err := s.RequestWithBucketID("DELETE", EndpointMessageReaction(channelID, messageID, emojiID, userID), nil, EndpointMessageReaction(channelID, "", "", ""), options...) 2557 2558 return err 2559 } 2560 2561 // MessageReactionsRemoveAll deletes all reactions from a message 2562 // channelID : The channel ID 2563 // messageID : The message ID. 2564 func (s *Session) MessageReactionsRemoveAll(channelID, messageID string, options ...RequestOption) error { 2565 2566 _, err := s.RequestWithBucketID("DELETE", EndpointMessageReactionsAll(channelID, messageID), nil, EndpointMessageReactionsAll(channelID, messageID), options...) 2567 2568 return err 2569 } 2570 2571 // MessageReactionsRemoveEmoji deletes all reactions of a certain emoji from a message 2572 // channelID : The channel ID 2573 // messageID : The message ID 2574 // emojiID : The emoji ID 2575 func (s *Session) MessageReactionsRemoveEmoji(channelID, messageID, emojiID string, options ...RequestOption) error { 2576 2577 // emoji such as #⃣ need to have # escaped 2578 emojiID = strings.Replace(emojiID, "#", "%23", -1) 2579 _, err := s.RequestWithBucketID("DELETE", EndpointMessageReactions(channelID, messageID, emojiID), nil, EndpointMessageReactions(channelID, messageID, emojiID), options...) 2580 2581 return err 2582 } 2583 2584 // MessageReactions gets all the users reactions for a specific emoji. 2585 // channelID : The channel ID. 2586 // messageID : The message ID. 2587 // emojiID : Either the unicode emoji for the reaction, or a guild emoji identifier. 2588 // limit : max number of users to return (max 100) 2589 // beforeID : If provided all reactions returned will be before given ID. 2590 // afterID : If provided all reactions returned will be after given ID. 2591 func (s *Session) MessageReactions(channelID, messageID, emojiID string, limit int, beforeID, afterID string, options ...RequestOption) (st []*User, err error) { 2592 // emoji such as #⃣ need to have # escaped 2593 emojiID = strings.Replace(emojiID, "#", "%23", -1) 2594 uri := EndpointMessageReactions(channelID, messageID, emojiID) 2595 2596 v := url.Values{} 2597 2598 if limit > 0 { 2599 v.Set("limit", strconv.Itoa(limit)) 2600 } 2601 2602 if afterID != "" { 2603 v.Set("after", afterID) 2604 } 2605 if beforeID != "" { 2606 v.Set("before", beforeID) 2607 } 2608 2609 if len(v) > 0 { 2610 uri += "?" + v.Encode() 2611 } 2612 2613 body, err := s.RequestWithBucketID("GET", uri, nil, EndpointMessageReaction(channelID, "", "", ""), options...) 2614 if err != nil { 2615 return 2616 } 2617 2618 err = unmarshal(body, &st) 2619 return 2620 } 2621 2622 // ------------------------------------------------------------------------------------------------ 2623 // Functions specific to threads 2624 // ------------------------------------------------------------------------------------------------ 2625 2626 // MessageThreadStartComplex creates a new thread from an existing message. 2627 // channelID : Channel to create thread in 2628 // messageID : Message to start thread from 2629 // data : Parameters of the thread 2630 func (s *Session) MessageThreadStartComplex(channelID, messageID string, data *ThreadStart, options ...RequestOption) (ch *Channel, err error) { 2631 endpoint := EndpointChannelMessageThread(channelID, messageID) 2632 var body []byte 2633 body, err = s.RequestWithBucketID("POST", endpoint, data, endpoint, options...) 2634 if err != nil { 2635 return 2636 } 2637 2638 err = unmarshal(body, &ch) 2639 return 2640 } 2641 2642 // MessageThreadStart creates a new thread from an existing message. 2643 // channelID : Channel to create thread in 2644 // messageID : Message to start thread from 2645 // name : Name of the thread 2646 // archiveDuration : Auto archive duration (in minutes) 2647 func (s *Session) MessageThreadStart(channelID, messageID string, name string, archiveDuration int, options ...RequestOption) (ch *Channel, err error) { 2648 return s.MessageThreadStartComplex(channelID, messageID, &ThreadStart{ 2649 Name: name, 2650 AutoArchiveDuration: archiveDuration, 2651 }, options...) 2652 } 2653 2654 // ThreadStartComplex creates a new thread. 2655 // channelID : Channel to create thread in 2656 // data : Parameters of the thread 2657 func (s *Session) ThreadStartComplex(channelID string, data *ThreadStart, options ...RequestOption) (ch *Channel, err error) { 2658 endpoint := EndpointChannelThreads(channelID) 2659 var body []byte 2660 body, err = s.RequestWithBucketID("POST", endpoint, data, endpoint, options...) 2661 if err != nil { 2662 return 2663 } 2664 2665 err = unmarshal(body, &ch) 2666 return 2667 } 2668 2669 // ThreadStart creates a new thread. 2670 // channelID : Channel to create thread in 2671 // name : Name of the thread 2672 // archiveDuration : Auto archive duration (in minutes) 2673 func (s *Session) ThreadStart(channelID, name string, typ ChannelType, archiveDuration int, options ...RequestOption) (ch *Channel, err error) { 2674 return s.ThreadStartComplex(channelID, &ThreadStart{ 2675 Name: name, 2676 Type: typ, 2677 AutoArchiveDuration: archiveDuration, 2678 }, options...) 2679 } 2680 2681 // ForumThreadStartComplex starts a new thread (creates a post) in a forum channel. 2682 // channelID : Channel to create thread in. 2683 // threadData : Parameters of the thread. 2684 // messageData : Parameters of the starting message. 2685 func (s *Session) ForumThreadStartComplex(channelID string, threadData *ThreadStart, messageData *MessageSend, options ...RequestOption) (th *Channel, err error) { 2686 endpoint := EndpointChannelThreads(channelID) 2687 2688 // TODO: Remove this when compatibility is not required. 2689 if messageData.Embed != nil { 2690 if messageData.Embeds == nil { 2691 messageData.Embeds = []*MessageEmbed{messageData.Embed} 2692 } else { 2693 err = fmt.Errorf("cannot specify both Embed and Embeds") 2694 return 2695 } 2696 } 2697 2698 for _, embed := range messageData.Embeds { 2699 if embed.Type == "" { 2700 embed.Type = "rich" 2701 } 2702 } 2703 2704 // TODO: Remove this when compatibility is not required. 2705 files := messageData.Files 2706 if messageData.File != nil { 2707 if files == nil { 2708 files = []*File{messageData.File} 2709 } else { 2710 err = fmt.Errorf("cannot specify both File and Files") 2711 return 2712 } 2713 } 2714 2715 data := struct { 2716 *ThreadStart 2717 Message *MessageSend `json:"message"` 2718 }{ThreadStart: threadData, Message: messageData} 2719 2720 var response []byte 2721 if len(files) > 0 { 2722 contentType, body, encodeErr := MultipartBodyWithJSON(data, files) 2723 if encodeErr != nil { 2724 return th, encodeErr 2725 } 2726 2727 response, err = s.RequestRaw("POST", endpoint, contentType, body, endpoint, 0, options...) 2728 } else { 2729 response, err = s.RequestWithBucketID("POST", endpoint, data, endpoint, options...) 2730 } 2731 if err != nil { 2732 return 2733 } 2734 2735 err = unmarshal(response, &th) 2736 return 2737 } 2738 2739 // ForumThreadStart starts a new thread (post) in a forum channel. 2740 // channelID : Channel to create thread in. 2741 // name : Name of the thread. 2742 // archiveDuration : Auto archive duration. 2743 // content : Content of the starting message. 2744 func (s *Session) ForumThreadStart(channelID, name string, archiveDuration int, content string, options ...RequestOption) (th *Channel, err error) { 2745 return s.ForumThreadStartComplex(channelID, &ThreadStart{ 2746 Name: name, 2747 AutoArchiveDuration: archiveDuration, 2748 }, &MessageSend{Content: content}, options...) 2749 } 2750 2751 // ForumThreadStartEmbed starts a new thread (post) in a forum channel. 2752 // channelID : Channel to create thread in. 2753 // name : Name of the thread. 2754 // archiveDuration : Auto archive duration. 2755 // embed : Embed data of the starting message. 2756 func (s *Session) ForumThreadStartEmbed(channelID, name string, archiveDuration int, embed *MessageEmbed, options ...RequestOption) (th *Channel, err error) { 2757 return s.ForumThreadStartComplex(channelID, &ThreadStart{ 2758 Name: name, 2759 AutoArchiveDuration: archiveDuration, 2760 }, &MessageSend{Embeds: []*MessageEmbed{embed}}, options...) 2761 } 2762 2763 // ForumThreadStartEmbeds starts a new thread (post) in a forum channel. 2764 // channelID : Channel to create thread in. 2765 // name : Name of the thread. 2766 // archiveDuration : Auto archive duration. 2767 // embeds : Embeds data of the starting message. 2768 func (s *Session) ForumThreadStartEmbeds(channelID, name string, archiveDuration int, embeds []*MessageEmbed, options ...RequestOption) (th *Channel, err error) { 2769 return s.ForumThreadStartComplex(channelID, &ThreadStart{ 2770 Name: name, 2771 AutoArchiveDuration: archiveDuration, 2772 }, &MessageSend{Embeds: embeds}, options...) 2773 } 2774 2775 // ThreadJoin adds current user to a thread 2776 func (s *Session) ThreadJoin(id string, options ...RequestOption) error { 2777 endpoint := EndpointThreadMember(id, "@me") 2778 _, err := s.RequestWithBucketID("PUT", endpoint, nil, endpoint, options...) 2779 return err 2780 } 2781 2782 // ThreadLeave removes current user to a thread 2783 func (s *Session) ThreadLeave(id string, options ...RequestOption) error { 2784 endpoint := EndpointThreadMember(id, "@me") 2785 _, err := s.RequestWithBucketID("DELETE", endpoint, nil, endpoint, options...) 2786 return err 2787 } 2788 2789 // ThreadMemberAdd adds another member to a thread 2790 func (s *Session) ThreadMemberAdd(threadID, memberID string, options ...RequestOption) error { 2791 endpoint := EndpointThreadMember(threadID, memberID) 2792 _, err := s.RequestWithBucketID("PUT", endpoint, nil, endpoint, options...) 2793 return err 2794 } 2795 2796 // ThreadMemberRemove removes another member from a thread 2797 func (s *Session) ThreadMemberRemove(threadID, memberID string, options ...RequestOption) error { 2798 endpoint := EndpointThreadMember(threadID, memberID) 2799 _, err := s.RequestWithBucketID("DELETE", endpoint, nil, endpoint, options...) 2800 return err 2801 } 2802 2803 // ThreadMember returns thread member object for the specified member of a thread. 2804 // withMember : Whether to include a guild member object. 2805 func (s *Session) ThreadMember(threadID, memberID string, withMember bool, options ...RequestOption) (member *ThreadMember, err error) { 2806 uri := EndpointThreadMember(threadID, memberID) 2807 2808 queryParams := url.Values{} 2809 if withMember { 2810 queryParams.Set("with_member", "true") 2811 } 2812 2813 if len(queryParams) > 0 { 2814 uri += "?" + queryParams.Encode() 2815 } 2816 2817 var body []byte 2818 body, err = s.RequestWithBucketID("GET", uri, nil, uri, options...) 2819 2820 if err != nil { 2821 return 2822 } 2823 2824 err = unmarshal(body, &member) 2825 return 2826 } 2827 2828 // ThreadMembers returns all members of specified thread. 2829 // limit : Max number of thread members to return (1-100). Defaults to 100. 2830 // afterID : Get thread members after this user ID. 2831 // withMember : Whether to include a guild member object for each thread member. 2832 func (s *Session) ThreadMembers(threadID string, limit int, withMember bool, afterID string, options ...RequestOption) (members []*ThreadMember, err error) { 2833 uri := EndpointThreadMembers(threadID) 2834 2835 queryParams := url.Values{} 2836 if withMember { 2837 queryParams.Set("with_member", "true") 2838 } 2839 if limit > 0 { 2840 queryParams.Set("limit", strconv.Itoa(limit)) 2841 } 2842 if afterID != "" { 2843 queryParams.Set("after", afterID) 2844 } 2845 2846 if len(queryParams) > 0 { 2847 uri += "?" + queryParams.Encode() 2848 } 2849 2850 var body []byte 2851 body, err = s.RequestWithBucketID("GET", uri, nil, uri, options...) 2852 2853 if err != nil { 2854 return 2855 } 2856 2857 err = unmarshal(body, &members) 2858 return 2859 } 2860 2861 // ThreadsActive returns all active threads for specified channel. 2862 func (s *Session) ThreadsActive(channelID string, options ...RequestOption) (threads *ThreadsList, err error) { 2863 var body []byte 2864 body, err = s.RequestWithBucketID("GET", EndpointChannelActiveThreads(channelID), nil, EndpointChannelActiveThreads(channelID), options...) 2865 if err != nil { 2866 return 2867 } 2868 2869 err = unmarshal(body, &threads) 2870 return 2871 } 2872 2873 // GuildThreadsActive returns all active threads for specified guild. 2874 func (s *Session) GuildThreadsActive(guildID string, options ...RequestOption) (threads *ThreadsList, err error) { 2875 var body []byte 2876 body, err = s.RequestWithBucketID("GET", EndpointGuildActiveThreads(guildID), nil, EndpointGuildActiveThreads(guildID), options...) 2877 if err != nil { 2878 return 2879 } 2880 2881 err = unmarshal(body, &threads) 2882 return 2883 } 2884 2885 // ThreadsArchived returns archived threads for specified channel. 2886 // before : If specified returns only threads before the timestamp 2887 // limit : Optional maximum amount of threads to return. 2888 func (s *Session) ThreadsArchived(channelID string, before *time.Time, limit int, options ...RequestOption) (threads *ThreadsList, err error) { 2889 endpoint := EndpointChannelPublicArchivedThreads(channelID) 2890 v := url.Values{} 2891 if before != nil { 2892 v.Set("before", before.Format(time.RFC3339)) 2893 } 2894 2895 if limit > 0 { 2896 v.Set("limit", strconv.Itoa(limit)) 2897 } 2898 2899 if len(v) > 0 { 2900 endpoint += "?" + v.Encode() 2901 } 2902 2903 var body []byte 2904 body, err = s.RequestWithBucketID("GET", endpoint, nil, endpoint, options...) 2905 if err != nil { 2906 return 2907 } 2908 2909 err = unmarshal(body, &threads) 2910 return 2911 } 2912 2913 // ThreadsPrivateArchived returns archived private threads for specified channel. 2914 // before : If specified returns only threads before the timestamp 2915 // limit : Optional maximum amount of threads to return. 2916 func (s *Session) ThreadsPrivateArchived(channelID string, before *time.Time, limit int, options ...RequestOption) (threads *ThreadsList, err error) { 2917 endpoint := EndpointChannelPrivateArchivedThreads(channelID) 2918 v := url.Values{} 2919 if before != nil { 2920 v.Set("before", before.Format(time.RFC3339)) 2921 } 2922 2923 if limit > 0 { 2924 v.Set("limit", strconv.Itoa(limit)) 2925 } 2926 2927 if len(v) > 0 { 2928 endpoint += "?" + v.Encode() 2929 } 2930 var body []byte 2931 body, err = s.RequestWithBucketID("GET", endpoint, nil, endpoint, options...) 2932 if err != nil { 2933 return 2934 } 2935 2936 err = unmarshal(body, &threads) 2937 return 2938 } 2939 2940 // ThreadsPrivateJoinedArchived returns archived joined private threads for specified channel. 2941 // before : If specified returns only threads before the timestamp 2942 // limit : Optional maximum amount of threads to return. 2943 func (s *Session) ThreadsPrivateJoinedArchived(channelID string, before *time.Time, limit int, options ...RequestOption) (threads *ThreadsList, err error) { 2944 endpoint := EndpointChannelJoinedPrivateArchivedThreads(channelID) 2945 v := url.Values{} 2946 if before != nil { 2947 v.Set("before", before.Format(time.RFC3339)) 2948 } 2949 2950 if limit > 0 { 2951 v.Set("limit", strconv.Itoa(limit)) 2952 } 2953 2954 if len(v) > 0 { 2955 endpoint += "?" + v.Encode() 2956 } 2957 var body []byte 2958 body, err = s.RequestWithBucketID("GET", endpoint, nil, endpoint, options...) 2959 if err != nil { 2960 return 2961 } 2962 2963 err = unmarshal(body, &threads) 2964 return 2965 } 2966 2967 // ------------------------------------------------------------------------------------------------ 2968 // Functions specific to application (slash) commands 2969 // ------------------------------------------------------------------------------------------------ 2970 2971 // ApplicationCommandCreate creates a global application command and returns it. 2972 // appID : The application ID. 2973 // guildID : Guild ID to create guild-specific application command. If empty - creates global application command. 2974 // cmd : New application command data. 2975 func (s *Session) ApplicationCommandCreate(appID string, guildID string, cmd *ApplicationCommand, options ...RequestOption) (ccmd *ApplicationCommand, err error) { 2976 endpoint := EndpointApplicationGlobalCommands(appID) 2977 if guildID != "" { 2978 endpoint = EndpointApplicationGuildCommands(appID, guildID) 2979 } 2980 2981 body, err := s.RequestWithBucketID("POST", endpoint, *cmd, endpoint, options...) 2982 if err != nil { 2983 return 2984 } 2985 2986 err = unmarshal(body, &ccmd) 2987 2988 return 2989 } 2990 2991 // ApplicationCommandEdit edits application command and returns new command data. 2992 // appID : The application ID. 2993 // cmdID : Application command ID to edit. 2994 // guildID : Guild ID to edit guild-specific application command. If empty - edits global application command. 2995 // cmd : Updated application command data. 2996 func (s *Session) ApplicationCommandEdit(appID, guildID, cmdID string, cmd *ApplicationCommand, options ...RequestOption) (updated *ApplicationCommand, err error) { 2997 endpoint := EndpointApplicationGlobalCommand(appID, cmdID) 2998 if guildID != "" { 2999 endpoint = EndpointApplicationGuildCommand(appID, guildID, cmdID) 3000 } 3001 3002 body, err := s.RequestWithBucketID("PATCH", endpoint, *cmd, endpoint, options...) 3003 if err != nil { 3004 return 3005 } 3006 3007 err = unmarshal(body, &updated) 3008 3009 return 3010 } 3011 3012 // ApplicationCommandBulkOverwrite Creates commands overwriting existing commands. Returns a list of commands. 3013 // appID : The application ID. 3014 // commands : The commands to create. 3015 func (s *Session) ApplicationCommandBulkOverwrite(appID string, guildID string, commands []*ApplicationCommand, options ...RequestOption) (createdCommands []*ApplicationCommand, err error) { 3016 endpoint := EndpointApplicationGlobalCommands(appID) 3017 if guildID != "" { 3018 endpoint = EndpointApplicationGuildCommands(appID, guildID) 3019 } 3020 3021 body, err := s.RequestWithBucketID("PUT", endpoint, commands, endpoint, options...) 3022 if err != nil { 3023 return 3024 } 3025 3026 err = unmarshal(body, &createdCommands) 3027 3028 return 3029 } 3030 3031 // ApplicationCommandDelete deletes application command by ID. 3032 // appID : The application ID. 3033 // cmdID : Application command ID to delete. 3034 // guildID : Guild ID to delete guild-specific application command. If empty - deletes global application command. 3035 func (s *Session) ApplicationCommandDelete(appID, guildID, cmdID string, options ...RequestOption) error { 3036 endpoint := EndpointApplicationGlobalCommand(appID, cmdID) 3037 if guildID != "" { 3038 endpoint = EndpointApplicationGuildCommand(appID, guildID, cmdID) 3039 } 3040 3041 _, err := s.RequestWithBucketID("DELETE", endpoint, nil, endpoint, options...) 3042 3043 return err 3044 } 3045 3046 // ApplicationCommand retrieves an application command by given ID. 3047 // appID : The application ID. 3048 // cmdID : Application command ID. 3049 // guildID : Guild ID to retrieve guild-specific application command. If empty - retrieves global application command. 3050 func (s *Session) ApplicationCommand(appID, guildID, cmdID string, options ...RequestOption) (cmd *ApplicationCommand, err error) { 3051 endpoint := EndpointApplicationGlobalCommand(appID, cmdID) 3052 if guildID != "" { 3053 endpoint = EndpointApplicationGuildCommand(appID, guildID, cmdID) 3054 } 3055 3056 body, err := s.RequestWithBucketID("GET", endpoint, nil, endpoint, options...) 3057 if err != nil { 3058 return 3059 } 3060 3061 err = unmarshal(body, &cmd) 3062 3063 return 3064 } 3065 3066 // ApplicationCommands retrieves all commands in application. 3067 // appID : The application ID. 3068 // guildID : Guild ID to retrieve all guild-specific application commands. If empty - retrieves global application commands. 3069 func (s *Session) ApplicationCommands(appID, guildID string, options ...RequestOption) (cmd []*ApplicationCommand, err error) { 3070 endpoint := EndpointApplicationGlobalCommands(appID) 3071 if guildID != "" { 3072 endpoint = EndpointApplicationGuildCommands(appID, guildID) 3073 } 3074 3075 body, err := s.RequestWithBucketID("GET", endpoint+"?with_localizations=true", nil, "GET "+endpoint, options...) 3076 if err != nil { 3077 return 3078 } 3079 3080 err = unmarshal(body, &cmd) 3081 3082 return 3083 } 3084 3085 // GuildApplicationCommandsPermissions returns permissions for application commands in a guild. 3086 // appID : The application ID 3087 // guildID : Guild ID to retrieve application commands permissions for. 3088 func (s *Session) GuildApplicationCommandsPermissions(appID, guildID string, options ...RequestOption) (permissions []*GuildApplicationCommandPermissions, err error) { 3089 endpoint := EndpointApplicationCommandsGuildPermissions(appID, guildID) 3090 3091 var body []byte 3092 body, err = s.RequestWithBucketID("GET", endpoint, nil, endpoint, options...) 3093 if err != nil { 3094 return 3095 } 3096 3097 err = unmarshal(body, &permissions) 3098 return 3099 } 3100 3101 // ApplicationCommandPermissions returns all permissions of an application command 3102 // appID : The Application ID 3103 // guildID : The guild ID containing the application command 3104 // cmdID : The command ID to retrieve the permissions of 3105 func (s *Session) ApplicationCommandPermissions(appID, guildID, cmdID string, options ...RequestOption) (permissions *GuildApplicationCommandPermissions, err error) { 3106 endpoint := EndpointApplicationCommandPermissions(appID, guildID, cmdID) 3107 3108 var body []byte 3109 body, err = s.RequestWithBucketID("GET", endpoint, nil, endpoint, options...) 3110 if err != nil { 3111 return 3112 } 3113 3114 err = unmarshal(body, &permissions) 3115 return 3116 } 3117 3118 // ApplicationCommandPermissionsEdit edits the permissions of an application command 3119 // appID : The Application ID 3120 // guildID : The guild ID containing the application command 3121 // cmdID : The command ID to edit the permissions of 3122 // permissions : An object containing a list of permissions for the application command 3123 // 3124 // NOTE: Requires OAuth2 token with applications.commands.permissions.update scope 3125 func (s *Session) ApplicationCommandPermissionsEdit(appID, guildID, cmdID string, permissions *ApplicationCommandPermissionsList, options ...RequestOption) (err error) { 3126 endpoint := EndpointApplicationCommandPermissions(appID, guildID, cmdID) 3127 3128 _, err = s.RequestWithBucketID("PUT", endpoint, permissions, endpoint, options...) 3129 return 3130 } 3131 3132 // ApplicationCommandPermissionsBatchEdit edits the permissions of a batch of commands 3133 // appID : The Application ID 3134 // guildID : The guild ID to batch edit commands of 3135 // permissions : A list of permissions paired with a command ID, guild ID, and application ID per application command 3136 // 3137 // NOTE: This endpoint has been disabled with updates to command permissions (Permissions v2). Please use ApplicationCommandPermissionsEdit instead. 3138 func (s *Session) ApplicationCommandPermissionsBatchEdit(appID, guildID string, permissions []*GuildApplicationCommandPermissions, options ...RequestOption) (err error) { 3139 endpoint := EndpointApplicationCommandsGuildPermissions(appID, guildID) 3140 3141 _, err = s.RequestWithBucketID("PUT", endpoint, permissions, endpoint, options...) 3142 return 3143 } 3144 3145 // InteractionRespond creates the response to an interaction. 3146 // interaction : Interaction instance. 3147 // resp : Response message data. 3148 func (s *Session) InteractionRespond(interaction *Interaction, resp *InteractionResponse, options ...RequestOption) error { 3149 endpoint := EndpointInteractionResponse(interaction.ID, interaction.Token) 3150 3151 if resp.Data != nil && len(resp.Data.Files) > 0 { 3152 contentType, body, err := MultipartBodyWithJSON(resp, resp.Data.Files) 3153 if err != nil { 3154 return err 3155 } 3156 3157 _, err = s.RequestRaw("POST", endpoint, contentType, body, endpoint, 0, options...) 3158 return err 3159 } 3160 3161 _, err := s.RequestWithBucketID("POST", endpoint, *resp, endpoint, options...) 3162 return err 3163 } 3164 3165 // InteractionResponse gets the response to an interaction. 3166 // interaction : Interaction instance. 3167 func (s *Session) InteractionResponse(interaction *Interaction, options ...RequestOption) (*Message, error) { 3168 return s.WebhookMessage(interaction.AppID, interaction.Token, "@original", options...) 3169 } 3170 3171 // InteractionResponseEdit edits the response to an interaction. 3172 // interaction : Interaction instance. 3173 // newresp : Updated response message data. 3174 func (s *Session) InteractionResponseEdit(interaction *Interaction, newresp *WebhookEdit, options ...RequestOption) (*Message, error) { 3175 return s.WebhookMessageEdit(interaction.AppID, interaction.Token, "@original", newresp, options...) 3176 } 3177 3178 // InteractionResponseDelete deletes the response to an interaction. 3179 // interaction : Interaction instance. 3180 func (s *Session) InteractionResponseDelete(interaction *Interaction, options ...RequestOption) error { 3181 endpoint := EndpointInteractionResponseActions(interaction.AppID, interaction.Token) 3182 3183 _, err := s.RequestWithBucketID("DELETE", endpoint, nil, endpoint, options...) 3184 3185 return err 3186 } 3187 3188 // FollowupMessageCreate creates the followup message for an interaction. 3189 // interaction : Interaction instance. 3190 // wait : Waits for server confirmation of message send and ensures that the return struct is populated (it is nil otherwise) 3191 // data : Data of the message to send. 3192 func (s *Session) FollowupMessageCreate(interaction *Interaction, wait bool, data *WebhookParams, options ...RequestOption) (*Message, error) { 3193 return s.WebhookExecute(interaction.AppID, interaction.Token, wait, data, options...) 3194 } 3195 3196 // FollowupMessageEdit edits a followup message of an interaction. 3197 // interaction : Interaction instance. 3198 // messageID : The followup message ID. 3199 // data : Data to update the message 3200 func (s *Session) FollowupMessageEdit(interaction *Interaction, messageID string, data *WebhookEdit, options ...RequestOption) (*Message, error) { 3201 return s.WebhookMessageEdit(interaction.AppID, interaction.Token, messageID, data, options...) 3202 } 3203 3204 // FollowupMessageDelete deletes a followup message of an interaction. 3205 // interaction : Interaction instance. 3206 // messageID : The followup message ID. 3207 func (s *Session) FollowupMessageDelete(interaction *Interaction, messageID string, options ...RequestOption) error { 3208 return s.WebhookMessageDelete(interaction.AppID, interaction.Token, messageID, options...) 3209 } 3210 3211 // ------------------------------------------------------------------------------------------------ 3212 // Functions specific to stage instances 3213 // ------------------------------------------------------------------------------------------------ 3214 3215 // StageInstanceCreate creates and returns a new Stage instance associated to a Stage channel. 3216 // data : Parameters needed to create a stage instance. 3217 // data : The data of the Stage instance to create 3218 func (s *Session) StageInstanceCreate(data *StageInstanceParams, options ...RequestOption) (si *StageInstance, err error) { 3219 body, err := s.RequestWithBucketID("POST", EndpointStageInstances, data, EndpointStageInstances, options...) 3220 if err != nil { 3221 return 3222 } 3223 3224 err = unmarshal(body, &si) 3225 return 3226 } 3227 3228 // StageInstance will retrieve a Stage instance by ID of the Stage channel. 3229 // channelID : The ID of the Stage channel 3230 func (s *Session) StageInstance(channelID string, options ...RequestOption) (si *StageInstance, err error) { 3231 body, err := s.RequestWithBucketID("GET", EndpointStageInstance(channelID), nil, EndpointStageInstance(channelID), options...) 3232 if err != nil { 3233 return 3234 } 3235 3236 err = unmarshal(body, &si) 3237 return 3238 } 3239 3240 // StageInstanceEdit will edit a Stage instance by ID of the Stage channel. 3241 // channelID : The ID of the Stage channel 3242 // data : The data to edit the Stage instance 3243 func (s *Session) StageInstanceEdit(channelID string, data *StageInstanceParams, options ...RequestOption) (si *StageInstance, err error) { 3244 3245 body, err := s.RequestWithBucketID("PATCH", EndpointStageInstance(channelID), data, EndpointStageInstance(channelID), options...) 3246 if err != nil { 3247 return 3248 } 3249 3250 err = unmarshal(body, &si) 3251 return 3252 } 3253 3254 // StageInstanceDelete will delete a Stage instance by ID of the Stage channel. 3255 // channelID : The ID of the Stage channel 3256 func (s *Session) StageInstanceDelete(channelID string, options ...RequestOption) (err error) { 3257 _, err = s.RequestWithBucketID("DELETE", EndpointStageInstance(channelID), nil, EndpointStageInstance(channelID), options...) 3258 return 3259 } 3260 3261 // ------------------------------------------------------------------------------------------------ 3262 // Functions specific to guilds scheduled events 3263 // ------------------------------------------------------------------------------------------------ 3264 3265 // GuildScheduledEvents returns an array of GuildScheduledEvent for a guild 3266 // guildID : The ID of a Guild 3267 // userCount : Whether to include the user count in the response 3268 func (s *Session) GuildScheduledEvents(guildID string, userCount bool, options ...RequestOption) (st []*GuildScheduledEvent, err error) { 3269 uri := EndpointGuildScheduledEvents(guildID) 3270 if userCount { 3271 uri += "?with_user_count=true" 3272 } 3273 3274 body, err := s.RequestWithBucketID("GET", uri, nil, EndpointGuildScheduledEvents(guildID), options...) 3275 if err != nil { 3276 return 3277 } 3278 3279 err = unmarshal(body, &st) 3280 return 3281 } 3282 3283 // GuildScheduledEvent returns a specific GuildScheduledEvent in a guild 3284 // guildID : The ID of a Guild 3285 // eventID : The ID of the event 3286 // userCount : Whether to include the user count in the response 3287 func (s *Session) GuildScheduledEvent(guildID, eventID string, userCount bool, options ...RequestOption) (st *GuildScheduledEvent, err error) { 3288 uri := EndpointGuildScheduledEvent(guildID, eventID) 3289 if userCount { 3290 uri += "?with_user_count=true" 3291 } 3292 3293 body, err := s.RequestWithBucketID("GET", uri, nil, EndpointGuildScheduledEvent(guildID, eventID), options...) 3294 if err != nil { 3295 return 3296 } 3297 3298 err = unmarshal(body, &st) 3299 return 3300 } 3301 3302 // GuildScheduledEventCreate creates a GuildScheduledEvent for a guild and returns it 3303 // guildID : The ID of a Guild 3304 // eventID : The ID of the event 3305 func (s *Session) GuildScheduledEventCreate(guildID string, event *GuildScheduledEventParams, options ...RequestOption) (st *GuildScheduledEvent, err error) { 3306 body, err := s.RequestWithBucketID("POST", EndpointGuildScheduledEvents(guildID), event, EndpointGuildScheduledEvents(guildID), options...) 3307 if err != nil { 3308 return 3309 } 3310 3311 err = unmarshal(body, &st) 3312 return 3313 } 3314 3315 // GuildScheduledEventEdit updates a specific event for a guild and returns it. 3316 // guildID : The ID of a Guild 3317 // eventID : The ID of the event 3318 func (s *Session) GuildScheduledEventEdit(guildID, eventID string, event *GuildScheduledEventParams, options ...RequestOption) (st *GuildScheduledEvent, err error) { 3319 body, err := s.RequestWithBucketID("PATCH", EndpointGuildScheduledEvent(guildID, eventID), event, EndpointGuildScheduledEvent(guildID, eventID), options...) 3320 if err != nil { 3321 return 3322 } 3323 3324 err = unmarshal(body, &st) 3325 return 3326 } 3327 3328 // GuildScheduledEventDelete deletes a specific GuildScheduledEvent in a guild 3329 // guildID : The ID of a Guild 3330 // eventID : The ID of the event 3331 func (s *Session) GuildScheduledEventDelete(guildID, eventID string, options ...RequestOption) (err error) { 3332 _, err = s.RequestWithBucketID("DELETE", EndpointGuildScheduledEvent(guildID, eventID), nil, EndpointGuildScheduledEvent(guildID, eventID), options...) 3333 return 3334 } 3335 3336 // GuildScheduledEventUsers returns an array of GuildScheduledEventUser for a particular event in a guild 3337 // guildID : The ID of a Guild 3338 // eventID : The ID of the event 3339 // limit : The maximum number of users to return (Max 100) 3340 // withMember : Whether to include the member object in the response 3341 // beforeID : If is not empty all returned users entries will be before the given ID 3342 // afterID : If is not empty all returned users entries will be after the given ID 3343 func (s *Session) GuildScheduledEventUsers(guildID, eventID string, limit int, withMember bool, beforeID, afterID string, options ...RequestOption) (st []*GuildScheduledEventUser, err error) { 3344 uri := EndpointGuildScheduledEventUsers(guildID, eventID) 3345 3346 queryParams := url.Values{} 3347 if withMember { 3348 queryParams.Set("with_member", "true") 3349 } 3350 if limit > 0 { 3351 queryParams.Set("limit", strconv.Itoa(limit)) 3352 } 3353 if beforeID != "" { 3354 queryParams.Set("before", beforeID) 3355 } 3356 if afterID != "" { 3357 queryParams.Set("after", afterID) 3358 } 3359 3360 if len(queryParams) > 0 { 3361 uri += "?" + queryParams.Encode() 3362 } 3363 3364 body, err := s.RequestWithBucketID("GET", uri, nil, EndpointGuildScheduledEventUsers(guildID, eventID), options...) 3365 if err != nil { 3366 return 3367 } 3368 3369 err = unmarshal(body, &st) 3370 return 3371 } 3372 3373 // GuildOnboarding returns onboarding configuration of a guild. 3374 // guildID : The ID of the guild 3375 func (s *Session) GuildOnboarding(guildID string, options ...RequestOption) (onboarding *GuildOnboarding, err error) { 3376 endpoint := EndpointGuildOnboarding(guildID) 3377 3378 var body []byte 3379 body, err = s.RequestWithBucketID("GET", endpoint, nil, endpoint, options...) 3380 if err != nil { 3381 return 3382 } 3383 3384 err = unmarshal(body, &onboarding) 3385 return 3386 } 3387 3388 // GuildOnboardingEdit edits onboarding configuration of a guild. 3389 // guildID : The ID of the guild 3390 // o : New GuildOnboarding data 3391 func (s *Session) GuildOnboardingEdit(guildID string, o *GuildOnboarding, options ...RequestOption) (onboarding *GuildOnboarding, err error) { 3392 endpoint := EndpointGuildOnboarding(guildID) 3393 3394 var body []byte 3395 body, err = s.RequestWithBucketID("PUT", endpoint, o, endpoint, options...) 3396 if err != nil { 3397 return 3398 } 3399 3400 err = unmarshal(body, &onboarding) 3401 return 3402 } 3403 3404 // ---------------------------------------------------------------------- 3405 // Functions specific to auto moderation 3406 // ---------------------------------------------------------------------- 3407 3408 // AutoModerationRules returns a list of auto moderation rules. 3409 // guildID : ID of the guild 3410 func (s *Session) AutoModerationRules(guildID string, options ...RequestOption) (st []*AutoModerationRule, err error) { 3411 endpoint := EndpointGuildAutoModerationRules(guildID) 3412 3413 var body []byte 3414 body, err = s.RequestWithBucketID("GET", endpoint, nil, endpoint, options...) 3415 if err != nil { 3416 return 3417 } 3418 3419 err = unmarshal(body, &st) 3420 return 3421 } 3422 3423 // AutoModerationRule returns an auto moderation rule. 3424 // guildID : ID of the guild 3425 // ruleID : ID of the auto moderation rule 3426 func (s *Session) AutoModerationRule(guildID, ruleID string, options ...RequestOption) (st *AutoModerationRule, err error) { 3427 endpoint := EndpointGuildAutoModerationRule(guildID, ruleID) 3428 3429 var body []byte 3430 body, err = s.RequestWithBucketID("GET", endpoint, nil, endpoint, options...) 3431 if err != nil { 3432 return 3433 } 3434 3435 err = unmarshal(body, &st) 3436 return 3437 } 3438 3439 // AutoModerationRuleCreate creates an auto moderation rule with the given data and returns it. 3440 // guildID : ID of the guild 3441 // rule : Rule data 3442 func (s *Session) AutoModerationRuleCreate(guildID string, rule *AutoModerationRule, options ...RequestOption) (st *AutoModerationRule, err error) { 3443 endpoint := EndpointGuildAutoModerationRules(guildID) 3444 3445 var body []byte 3446 body, err = s.RequestWithBucketID("POST", endpoint, rule, endpoint, options...) 3447 if err != nil { 3448 return 3449 } 3450 3451 err = unmarshal(body, &st) 3452 return 3453 } 3454 3455 // AutoModerationRuleEdit edits and returns the updated auto moderation rule. 3456 // guildID : ID of the guild 3457 // ruleID : ID of the auto moderation rule 3458 // rule : New rule data 3459 func (s *Session) AutoModerationRuleEdit(guildID, ruleID string, rule *AutoModerationRule, options ...RequestOption) (st *AutoModerationRule, err error) { 3460 endpoint := EndpointGuildAutoModerationRule(guildID, ruleID) 3461 3462 var body []byte 3463 body, err = s.RequestWithBucketID("PATCH", endpoint, rule, endpoint, options...) 3464 if err != nil { 3465 return 3466 } 3467 3468 err = unmarshal(body, &st) 3469 return 3470 } 3471 3472 // AutoModerationRuleDelete deletes an auto moderation rule. 3473 // guildID : ID of the guild 3474 // ruleID : ID of the auto moderation rule 3475 func (s *Session) AutoModerationRuleDelete(guildID, ruleID string, options ...RequestOption) (err error) { 3476 endpoint := EndpointGuildAutoModerationRule(guildID, ruleID) 3477 _, err = s.RequestWithBucketID("DELETE", endpoint, nil, endpoint, options...) 3478 return 3479 } 3480 3481 // ApplicationRoleConnectionMetadata returns application role connection metadata. 3482 // appID : ID of the application 3483 func (s *Session) ApplicationRoleConnectionMetadata(appID string) (st []*ApplicationRoleConnectionMetadata, err error) { 3484 endpoint := EndpointApplicationRoleConnectionMetadata(appID) 3485 var body []byte 3486 body, err = s.RequestWithBucketID("GET", endpoint, nil, endpoint) 3487 if err != nil { 3488 return 3489 } 3490 3491 err = unmarshal(body, &st) 3492 return 3493 } 3494 3495 // ApplicationRoleConnectionMetadataUpdate updates and returns application role connection metadata. 3496 // appID : ID of the application 3497 // metadata : New metadata 3498 func (s *Session) ApplicationRoleConnectionMetadataUpdate(appID string, metadata []*ApplicationRoleConnectionMetadata) (st []*ApplicationRoleConnectionMetadata, err error) { 3499 endpoint := EndpointApplicationRoleConnectionMetadata(appID) 3500 var body []byte 3501 body, err = s.RequestWithBucketID("PUT", endpoint, metadata, endpoint) 3502 if err != nil { 3503 return 3504 } 3505 3506 err = unmarshal(body, &st) 3507 return 3508 } 3509 3510 // UserApplicationRoleConnection returns user role connection to the specified application. 3511 // appID : ID of the application 3512 func (s *Session) UserApplicationRoleConnection(appID string) (st *ApplicationRoleConnection, err error) { 3513 endpoint := EndpointUserApplicationRoleConnection(appID) 3514 var body []byte 3515 body, err = s.RequestWithBucketID("GET", endpoint, nil, endpoint) 3516 if err != nil { 3517 return 3518 } 3519 3520 err = unmarshal(body, &st) 3521 return 3522 3523 } 3524 3525 // UserApplicationRoleConnectionUpdate updates and returns user role connection to the specified application. 3526 // appID : ID of the application 3527 // connection : New ApplicationRoleConnection data 3528 func (s *Session) UserApplicationRoleConnectionUpdate(appID string, rconn *ApplicationRoleConnection) (st *ApplicationRoleConnection, err error) { 3529 endpoint := EndpointUserApplicationRoleConnection(appID) 3530 var body []byte 3531 body, err = s.RequestWithBucketID("PUT", endpoint, rconn, endpoint) 3532 if err != nil { 3533 return 3534 } 3535 3536 err = unmarshal(body, &st) 3537 return 3538 } 3539 3540 // ---------------------------------------------------------------------- 3541 // Functions specific to polls 3542 // ---------------------------------------------------------------------- 3543 3544 // PollAnswerVoters returns users who voted for a particular answer in a poll on the specified message. 3545 // channelID : ID of the channel. 3546 // messageID : ID of the message. 3547 // answerID : ID of the answer. 3548 func (s *Session) PollAnswerVoters(channelID, messageID string, answerID int) (voters []*User, err error) { 3549 endpoint := EndpointPollAnswerVoters(channelID, messageID, answerID) 3550 3551 var body []byte 3552 body, err = s.RequestWithBucketID("GET", endpoint, nil, endpoint) 3553 if err != nil { 3554 return 3555 } 3556 3557 var r struct { 3558 Users []*User `json:"users"` 3559 } 3560 3561 err = unmarshal(body, &r) 3562 if err != nil { 3563 return 3564 } 3565 3566 voters = r.Users 3567 return 3568 } 3569 3570 // PollExpire expires poll on the specified message. 3571 // channelID : ID of the channel. 3572 // messageID : ID of the message. 3573 func (s *Session) PollExpire(channelID, messageID string) (msg *Message, err error) { 3574 endpoint := EndpointPollExpire(channelID, messageID) 3575 3576 var body []byte 3577 body, err = s.RequestWithBucketID("POST", endpoint, nil, endpoint) 3578 if err != nil { 3579 return 3580 } 3581 3582 err = unmarshal(body, &msg) 3583 return 3584 } 3585 3586 // ---------------------------------------------------------------------- 3587 // Functions specific to monetization 3588 // ---------------------------------------------------------------------- 3589 3590 // SKUs returns all SKUs for a given application. 3591 // appID : The ID of the application. 3592 func (s *Session) SKUs(appID string) (skus []*SKU, err error) { 3593 endpoint := EndpointApplicationSKUs(appID) 3594 3595 body, err := s.RequestWithBucketID("GET", endpoint, nil, endpoint) 3596 if err != nil { 3597 return 3598 } 3599 3600 err = unmarshal(body, &skus) 3601 return 3602 } 3603 3604 // Entitlements returns all Entitlements for a given app, active and expired. 3605 // appID : The ID of the application. 3606 // filterOptions : Optional filter options; otherwise set it to nil. 3607 func (s *Session) Entitlements(appID string, filterOptions *EntitlementFilterOptions, options ...RequestOption) (entitlements []*Entitlement, err error) { 3608 endpoint := EndpointEntitlements(appID) 3609 3610 queryParams := url.Values{} 3611 if filterOptions != nil { 3612 if filterOptions.UserID != "" { 3613 queryParams.Set("user_id", filterOptions.UserID) 3614 } 3615 if filterOptions.SkuIDs != nil && len(filterOptions.SkuIDs) > 0 { 3616 queryParams.Set("sku_ids", strings.Join(filterOptions.SkuIDs, ",")) 3617 } 3618 if filterOptions.Before != nil { 3619 queryParams.Set("before", filterOptions.Before.Format(time.RFC3339)) 3620 } 3621 if filterOptions.After != nil { 3622 queryParams.Set("after", filterOptions.After.Format(time.RFC3339)) 3623 } 3624 if filterOptions.Limit > 0 { 3625 queryParams.Set("limit", strconv.Itoa(filterOptions.Limit)) 3626 } 3627 if filterOptions.GuildID != "" { 3628 queryParams.Set("guild_id", filterOptions.GuildID) 3629 } 3630 if filterOptions.ExcludeEnded { 3631 queryParams.Set("exclude_ended", "true") 3632 } 3633 } 3634 3635 body, err := s.RequestWithBucketID("GET", endpoint+"?"+queryParams.Encode(), nil, endpoint, options...) 3636 if err != nil { 3637 return 3638 } 3639 3640 err = unmarshal(body, &entitlements) 3641 return 3642 } 3643 3644 // EntitlementConsume marks a given One-Time Purchase for the user as consumed. 3645 func (s *Session) EntitlementConsume(appID, entitlementID string, options ...RequestOption) (err error) { 3646 _, err = s.RequestWithBucketID("POST", EndpointEntitlementConsume(appID, entitlementID), nil, EndpointEntitlementConsume(appID, ""), options...) 3647 return 3648 } 3649 3650 // EntitlementTestCreate creates a test entitlement to a given SKU for a given guild or user. 3651 // Discord will act as though that user or guild has entitlement to your premium offering. 3652 func (s *Session) EntitlementTestCreate(appID string, data *EntitlementTest, options ...RequestOption) (err error) { 3653 endpoint := EndpointEntitlements(appID) 3654 3655 _, err = s.RequestWithBucketID("POST", endpoint, data, endpoint, options...) 3656 return 3657 } 3658 3659 // EntitlementTestDelete deletes a currently-active test entitlement. Discord will act as though 3660 // that user or guild no longer has entitlement to your premium offering. 3661 func (s *Session) EntitlementTestDelete(appID, entitlementID string, options ...RequestOption) (err error) { 3662 _, err = s.RequestWithBucketID("DELETE", EndpointEntitlement(appID, entitlementID), nil, EndpointEntitlement(appID, ""), options...) 3663 return 3664 } 3665 3666 // Subscriptions returns all subscriptions containing the SKU. 3667 // skuID : The ID of the SKU. 3668 // userID : User ID for which to return subscriptions. Required except for OAuth queries. 3669 // before : Optional timestamp to retrieve subscriptions before this time. 3670 // after : Optional timestamp to retrieve subscriptions after this time. 3671 // limit : Optional maximum number of subscriptions to return (1-100, default 50). 3672 func (s *Session) Subscriptions(skuID string, userID string, before, after *time.Time, limit int, options ...RequestOption) (subscriptions []*Subscription, err error) { 3673 endpoint := EndpointSubscriptions(skuID) 3674 3675 queryParams := url.Values{} 3676 if before != nil { 3677 queryParams.Set("before", before.Format(time.RFC3339)) 3678 } 3679 if after != nil { 3680 queryParams.Set("after", after.Format(time.RFC3339)) 3681 } 3682 if userID != "" { 3683 queryParams.Set("user_id", userID) 3684 } 3685 if limit > 0 { 3686 queryParams.Set("limit", strconv.Itoa(limit)) 3687 } 3688 3689 body, err := s.RequestWithBucketID("GET", endpoint+"?"+queryParams.Encode(), nil, endpoint, options...) 3690 if err != nil { 3691 return 3692 } 3693 3694 err = unmarshal(body, &subscriptions) 3695 return 3696 } 3697 3698 // Subscription returns a subscription by its SKU and subscription ID. 3699 // skuID : The ID of the SKU. 3700 // subscriptionID : The ID of the subscription. 3701 // userID : User ID for which to return the subscription. Required except for OAuth queries. 3702 func (s *Session) Subscription(skuID, subscriptionID, userID string, options ...RequestOption) (subscription *Subscription, err error) { 3703 endpoint := EndpointSubscription(skuID, subscriptionID) 3704 3705 queryParams := url.Values{} 3706 if userID != "" { 3707 // Unlike stated in the documentation, the user_id parameter is required here. 3708 queryParams.Set("user_id", userID) 3709 } 3710 3711 body, err := s.RequestWithBucketID("GET", endpoint+"?"+queryParams.Encode(), nil, endpoint, options...) 3712 if err != nil { 3713 return 3714 } 3715 3716 err = unmarshal(body, &subscription) 3717 return 3718 }