restapi.go 90 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870
  1. // Discordgo - Discord bindings for Go
  2. // Available at https://github.com/bwmarrin/discordgo
  3. // Copyright 2015-2016 Bruce Marriner <bruce@sqls.net>. All rights reserved.
  4. // Use of this source code is governed by a BSD-style
  5. // license that can be found in the LICENSE file.
  6. // This file contains functions for interacting with the Discord REST/JSON API
  7. // at the lowest level.
  8. package discordgo
  9. import (
  10. "bytes"
  11. "encoding/json"
  12. "errors"
  13. "fmt"
  14. "image"
  15. _ "image/jpeg" // For JPEG decoding
  16. _ "image/png" // For PNG decoding
  17. "io"
  18. "io/ioutil"
  19. "log"
  20. "net/http"
  21. "net/url"
  22. "strconv"
  23. "strings"
  24. "time"
  25. )
  26. // All error constants
  27. var (
  28. ErrJSONUnmarshal = errors.New("json unmarshal")
  29. ErrStatusOffline = errors.New("You can't set your Status to offline")
  30. ErrVerificationLevelBounds = errors.New("VerificationLevel out of bounds, should be between 0 and 3")
  31. ErrPruneDaysBounds = errors.New("the number of days should be more than or equal to 1")
  32. ErrGuildNoIcon = errors.New("guild does not have an icon set")
  33. ErrGuildNoSplash = errors.New("guild does not have a splash set")
  34. 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")
  35. )
  36. // Request is the same as RequestWithBucketID but the bucket id is the same as the urlStr
  37. func (s *Session) Request(method, urlStr string, data interface{}) (response []byte, err error) {
  38. return s.RequestWithBucketID(method, urlStr, data, strings.SplitN(urlStr, "?", 2)[0])
  39. }
  40. // RequestWithBucketID makes a (GET/POST/...) Requests to Discord REST API with JSON data.
  41. func (s *Session) RequestWithBucketID(method, urlStr string, data interface{}, bucketID string) (response []byte, err error) {
  42. var body []byte
  43. if data != nil {
  44. body, err = json.Marshal(data)
  45. if err != nil {
  46. return
  47. }
  48. }
  49. return s.request(method, urlStr, "application/json", body, bucketID, 0)
  50. }
  51. // request makes a (GET/POST/...) Requests to Discord REST API.
  52. // Sequence is the sequence number, if it fails with a 502 it will
  53. // retry with sequence+1 until it either succeeds or sequence >= session.MaxRestRetries
  54. func (s *Session) request(method, urlStr, contentType string, b []byte, bucketID string, sequence int) (response []byte, err error) {
  55. if bucketID == "" {
  56. bucketID = strings.SplitN(urlStr, "?", 2)[0]
  57. }
  58. return s.RequestWithLockedBucket(method, urlStr, contentType, b, s.Ratelimiter.LockBucket(bucketID), sequence)
  59. }
  60. // RequestWithLockedBucket makes a request using a bucket that's already been locked
  61. func (s *Session) RequestWithLockedBucket(method, urlStr, contentType string, b []byte, bucket *Bucket, sequence int) (response []byte, err error) {
  62. if s.Debug {
  63. log.Printf("API REQUEST %8s :: %s\n", method, urlStr)
  64. log.Printf("API REQUEST PAYLOAD :: [%s]\n", string(b))
  65. }
  66. req, err := http.NewRequest(method, urlStr, bytes.NewBuffer(b))
  67. if err != nil {
  68. bucket.Release(nil)
  69. return
  70. }
  71. // Not used on initial login..
  72. // TODO: Verify if a login, otherwise complain about no-token
  73. if s.Token != "" {
  74. req.Header.Set("authorization", s.Token)
  75. }
  76. // Discord's API returns a 400 Bad Request is Content-Type is set, but the
  77. // request body is empty.
  78. if b != nil {
  79. req.Header.Set("Content-Type", contentType)
  80. }
  81. // TODO: Make a configurable static variable.
  82. req.Header.Set("User-Agent", s.UserAgent)
  83. if s.Debug {
  84. for k, v := range req.Header {
  85. log.Printf("API REQUEST HEADER :: [%s] = %+v\n", k, v)
  86. }
  87. }
  88. resp, err := s.Client.Do(req)
  89. if err != nil {
  90. bucket.Release(nil)
  91. return
  92. }
  93. defer func() {
  94. err2 := resp.Body.Close()
  95. if err2 != nil {
  96. log.Println("error closing resp body")
  97. }
  98. }()
  99. err = bucket.Release(resp.Header)
  100. if err != nil {
  101. return
  102. }
  103. response, err = ioutil.ReadAll(resp.Body)
  104. if err != nil {
  105. return
  106. }
  107. if s.Debug {
  108. log.Printf("API RESPONSE STATUS :: %s\n", resp.Status)
  109. for k, v := range resp.Header {
  110. log.Printf("API RESPONSE HEADER :: [%s] = %+v\n", k, v)
  111. }
  112. log.Printf("API RESPONSE BODY :: [%s]\n\n\n", response)
  113. }
  114. switch resp.StatusCode {
  115. case http.StatusOK:
  116. case http.StatusCreated:
  117. case http.StatusNoContent:
  118. case http.StatusBadGateway:
  119. // Retry sending request if possible
  120. if sequence < s.MaxRestRetries {
  121. s.log(LogInformational, "%s Failed (%s), Retrying...", urlStr, resp.Status)
  122. response, err = s.RequestWithLockedBucket(method, urlStr, contentType, b, s.Ratelimiter.LockBucketObject(bucket), sequence+1)
  123. } else {
  124. err = fmt.Errorf("Exceeded Max retries HTTP %s, %s", resp.Status, response)
  125. }
  126. case 429: // TOO MANY REQUESTS - Rate limiting
  127. rl := TooManyRequests{}
  128. err = json.Unmarshal(response, &rl)
  129. if err != nil {
  130. s.log(LogError, "rate limit unmarshal error, %s", err)
  131. return
  132. }
  133. s.log(LogInformational, "Rate Limiting %s, retry in %v", urlStr, rl.RetryAfter)
  134. s.handleEvent(rateLimitEventType, &RateLimit{TooManyRequests: &rl, URL: urlStr})
  135. time.Sleep(rl.RetryAfter)
  136. // we can make the above smarter
  137. // this method can cause longer delays than required
  138. response, err = s.RequestWithLockedBucket(method, urlStr, contentType, b, s.Ratelimiter.LockBucketObject(bucket), sequence)
  139. case http.StatusUnauthorized:
  140. if strings.Index(s.Token, "Bot ") != 0 {
  141. s.log(LogInformational, ErrUnauthorized.Error())
  142. err = ErrUnauthorized
  143. }
  144. fallthrough
  145. default: // Error condition
  146. err = newRestError(req, resp, response)
  147. }
  148. return
  149. }
  150. func unmarshal(data []byte, v interface{}) error {
  151. err := json.Unmarshal(data, v)
  152. if err != nil {
  153. return fmt.Errorf("%w: %s", ErrJSONUnmarshal, err)
  154. }
  155. return nil
  156. }
  157. // ------------------------------------------------------------------------------------------------
  158. // Functions specific to Discord Users
  159. // ------------------------------------------------------------------------------------------------
  160. // User returns the user details of the given userID
  161. // userID : A user ID or "@me" which is a shortcut of current user ID
  162. func (s *Session) User(userID string) (st *User, err error) {
  163. body, err := s.RequestWithBucketID("GET", EndpointUser(userID), nil, EndpointUsers)
  164. if err != nil {
  165. return
  166. }
  167. err = unmarshal(body, &st)
  168. return
  169. }
  170. // UserAvatar is deprecated. Please use UserAvatarDecode
  171. // userID : A user ID or "@me" which is a shortcut of current user ID
  172. func (s *Session) UserAvatar(userID string) (img image.Image, err error) {
  173. u, err := s.User(userID)
  174. if err != nil {
  175. return
  176. }
  177. img, err = s.UserAvatarDecode(u)
  178. return
  179. }
  180. // UserAvatarDecode returns an image.Image of a user's Avatar
  181. // user : The user which avatar should be retrieved
  182. func (s *Session) UserAvatarDecode(u *User) (img image.Image, err error) {
  183. body, err := s.RequestWithBucketID("GET", EndpointUserAvatar(u.ID, u.Avatar), nil, EndpointUserAvatar("", ""))
  184. if err != nil {
  185. return
  186. }
  187. img, _, err = image.Decode(bytes.NewReader(body))
  188. return
  189. }
  190. // UserUpdate updates current user settings.
  191. func (s *Session) UserUpdate(username, avatar string) (st *User, err error) {
  192. // NOTE: Avatar must be either the hash/id of existing Avatar or
  193. // data:image/png;base64,BASE64_STRING_OF_NEW_AVATAR_PNG
  194. // to set a new avatar.
  195. // If left blank, avatar will be set to null/blank
  196. data := struct {
  197. Username string `json:"username,omitempty"`
  198. Avatar string `json:"avatar,omitempty"`
  199. }{username, avatar}
  200. body, err := s.RequestWithBucketID("PATCH", EndpointUser("@me"), data, EndpointUsers)
  201. if err != nil {
  202. return
  203. }
  204. err = unmarshal(body, &st)
  205. return
  206. }
  207. // UserConnections returns the user's connections
  208. func (s *Session) UserConnections() (conn []*UserConnection, err error) {
  209. response, err := s.RequestWithBucketID("GET", EndpointUserConnections("@me"), nil, EndpointUserConnections("@me"))
  210. if err != nil {
  211. return nil, err
  212. }
  213. err = unmarshal(response, &conn)
  214. if err != nil {
  215. return
  216. }
  217. return
  218. }
  219. // UserChannelCreate creates a new User (Private) Channel with another User
  220. // recipientID : A user ID for the user to which this channel is opened with.
  221. func (s *Session) UserChannelCreate(recipientID string) (st *Channel, err error) {
  222. data := struct {
  223. RecipientID string `json:"recipient_id"`
  224. }{recipientID}
  225. body, err := s.RequestWithBucketID("POST", EndpointUserChannels("@me"), data, EndpointUserChannels(""))
  226. if err != nil {
  227. return
  228. }
  229. err = unmarshal(body, &st)
  230. return
  231. }
  232. // UserGuilds returns an array of UserGuild structures for all guilds.
  233. // limit : The number guilds that can be returned. (max 100)
  234. // beforeID : If provided all guilds returned will be before given ID.
  235. // afterID : If provided all guilds returned will be after given ID.
  236. func (s *Session) UserGuilds(limit int, beforeID, afterID string) (st []*UserGuild, err error) {
  237. v := url.Values{}
  238. if limit > 0 {
  239. v.Set("limit", strconv.Itoa(limit))
  240. }
  241. if afterID != "" {
  242. v.Set("after", afterID)
  243. }
  244. if beforeID != "" {
  245. v.Set("before", beforeID)
  246. }
  247. uri := EndpointUserGuilds("@me")
  248. if len(v) > 0 {
  249. uri += "?" + v.Encode()
  250. }
  251. body, err := s.RequestWithBucketID("GET", uri, nil, EndpointUserGuilds(""))
  252. if err != nil {
  253. return
  254. }
  255. err = unmarshal(body, &st)
  256. return
  257. }
  258. // UserChannelPermissions returns the permission of a user in a channel.
  259. // userID : The ID of the user to calculate permissions for.
  260. // channelID : The ID of the channel to calculate permission for.
  261. //
  262. // NOTE: This function is now deprecated and will be removed in the future.
  263. // Please see the same function inside state.go
  264. func (s *Session) UserChannelPermissions(userID, channelID string) (apermissions int64, err error) {
  265. // Try to just get permissions from state.
  266. apermissions, err = s.State.UserChannelPermissions(userID, channelID)
  267. if err == nil {
  268. return
  269. }
  270. // Otherwise try get as much data from state as possible, falling back to the network.
  271. channel, err := s.State.Channel(channelID)
  272. if err != nil || channel == nil {
  273. channel, err = s.Channel(channelID)
  274. if err != nil {
  275. return
  276. }
  277. }
  278. guild, err := s.State.Guild(channel.GuildID)
  279. if err != nil || guild == nil {
  280. guild, err = s.Guild(channel.GuildID)
  281. if err != nil {
  282. return
  283. }
  284. }
  285. if userID == guild.OwnerID {
  286. apermissions = PermissionAll
  287. return
  288. }
  289. member, err := s.State.Member(guild.ID, userID)
  290. if err != nil || member == nil {
  291. member, err = s.GuildMember(guild.ID, userID)
  292. if err != nil {
  293. return
  294. }
  295. }
  296. return memberPermissions(guild, channel, userID, member.Roles), nil
  297. }
  298. // Calculates the permissions for a member.
  299. // https://support.discord.com/hc/en-us/articles/206141927-How-is-the-permission-hierarchy-structured-
  300. func memberPermissions(guild *Guild, channel *Channel, userID string, roles []string) (apermissions int64) {
  301. if userID == guild.OwnerID {
  302. apermissions = PermissionAll
  303. return
  304. }
  305. for _, role := range guild.Roles {
  306. if role.ID == guild.ID {
  307. apermissions |= role.Permissions
  308. break
  309. }
  310. }
  311. for _, role := range guild.Roles {
  312. for _, roleID := range roles {
  313. if role.ID == roleID {
  314. apermissions |= role.Permissions
  315. break
  316. }
  317. }
  318. }
  319. if apermissions&PermissionAdministrator == PermissionAdministrator {
  320. apermissions |= PermissionAll
  321. }
  322. // Apply @everyone overrides from the channel.
  323. for _, overwrite := range channel.PermissionOverwrites {
  324. if guild.ID == overwrite.ID {
  325. apermissions &= ^overwrite.Deny
  326. apermissions |= overwrite.Allow
  327. break
  328. }
  329. }
  330. var denies, allows int64
  331. // Member overwrites can override role overrides, so do two passes
  332. for _, overwrite := range channel.PermissionOverwrites {
  333. for _, roleID := range roles {
  334. if overwrite.Type == PermissionOverwriteTypeRole && roleID == overwrite.ID {
  335. denies |= overwrite.Deny
  336. allows |= overwrite.Allow
  337. break
  338. }
  339. }
  340. }
  341. apermissions &= ^denies
  342. apermissions |= allows
  343. for _, overwrite := range channel.PermissionOverwrites {
  344. if overwrite.Type == PermissionOverwriteTypeMember && overwrite.ID == userID {
  345. apermissions &= ^overwrite.Deny
  346. apermissions |= overwrite.Allow
  347. break
  348. }
  349. }
  350. if apermissions&PermissionAdministrator == PermissionAdministrator {
  351. apermissions |= PermissionAllChannel
  352. }
  353. return apermissions
  354. }
  355. // ------------------------------------------------------------------------------------------------
  356. // Functions specific to Discord Guilds
  357. // ------------------------------------------------------------------------------------------------
  358. // Guild returns a Guild structure of a specific Guild.
  359. // guildID : The ID of a Guild
  360. func (s *Session) Guild(guildID string) (st *Guild, err error) {
  361. body, err := s.RequestWithBucketID("GET", EndpointGuild(guildID), nil, EndpointGuild(guildID))
  362. if err != nil {
  363. return
  364. }
  365. err = unmarshal(body, &st)
  366. return
  367. }
  368. // GuildPreview returns a GuildPreview structure of a specific public Guild.
  369. // guildID : The ID of a Guild
  370. func (s *Session) GuildPreview(guildID string) (st *GuildPreview, err error) {
  371. body, err := s.RequestWithBucketID("GET", EndpointGuildPreview(guildID), nil, EndpointGuildPreview(guildID))
  372. if err != nil {
  373. return
  374. }
  375. err = unmarshal(body, &st)
  376. return
  377. }
  378. // GuildCreate creates a new Guild
  379. // name : A name for the Guild (2-100 characters)
  380. func (s *Session) GuildCreate(name string) (st *Guild, err error) {
  381. data := struct {
  382. Name string `json:"name"`
  383. }{name}
  384. body, err := s.RequestWithBucketID("POST", EndpointGuildCreate, data, EndpointGuildCreate)
  385. if err != nil {
  386. return
  387. }
  388. err = unmarshal(body, &st)
  389. return
  390. }
  391. // GuildEdit edits a new Guild
  392. // guildID : The ID of a Guild
  393. // g : A GuildParams struct with the values Name, Region and VerificationLevel defined.
  394. func (s *Session) GuildEdit(guildID string, g GuildParams) (st *Guild, err error) {
  395. // Bounds checking for VerificationLevel, interval: [0, 4]
  396. if g.VerificationLevel != nil {
  397. val := *g.VerificationLevel
  398. if val < 0 || val > 4 {
  399. err = ErrVerificationLevelBounds
  400. return
  401. }
  402. }
  403. //Bounds checking for regions
  404. if g.Region != "" {
  405. isValid := false
  406. regions, _ := s.VoiceRegions()
  407. for _, r := range regions {
  408. if g.Region == r.ID {
  409. isValid = true
  410. }
  411. }
  412. if !isValid {
  413. var valid []string
  414. for _, r := range regions {
  415. valid = append(valid, r.ID)
  416. }
  417. err = fmt.Errorf("Region not a valid region (%q)", valid)
  418. return
  419. }
  420. }
  421. body, err := s.RequestWithBucketID("PATCH", EndpointGuild(guildID), g, EndpointGuild(guildID))
  422. if err != nil {
  423. return
  424. }
  425. err = unmarshal(body, &st)
  426. return
  427. }
  428. // GuildDelete deletes a Guild.
  429. // guildID : The ID of a Guild
  430. func (s *Session) GuildDelete(guildID string) (st *Guild, err error) {
  431. body, err := s.RequestWithBucketID("DELETE", EndpointGuild(guildID), nil, EndpointGuild(guildID))
  432. if err != nil {
  433. return
  434. }
  435. err = unmarshal(body, &st)
  436. return
  437. }
  438. // GuildLeave leaves a Guild.
  439. // guildID : The ID of a Guild
  440. func (s *Session) GuildLeave(guildID string) (err error) {
  441. _, err = s.RequestWithBucketID("DELETE", EndpointUserGuild("@me", guildID), nil, EndpointUserGuild("", guildID))
  442. return
  443. }
  444. // GuildBans returns an array of GuildBan structures for all bans of a
  445. // given guild.
  446. // guildID : The ID of a Guild.
  447. func (s *Session) GuildBans(guildID string) (st []*GuildBan, err error) {
  448. body, err := s.RequestWithBucketID("GET", EndpointGuildBans(guildID), nil, EndpointGuildBans(guildID))
  449. if err != nil {
  450. return
  451. }
  452. err = unmarshal(body, &st)
  453. return
  454. }
  455. // GuildBanCreate bans the given user from the given guild.
  456. // guildID : The ID of a Guild.
  457. // userID : The ID of a User
  458. // days : The number of days of previous comments to delete.
  459. func (s *Session) GuildBanCreate(guildID, userID string, days int) (err error) {
  460. return s.GuildBanCreateWithReason(guildID, userID, "", days)
  461. }
  462. // GuildBan finds ban by given guild and user id and returns GuildBan structure
  463. func (s *Session) GuildBan(guildID, userID string) (st *GuildBan, err error) {
  464. body, err := s.RequestWithBucketID("GET", EndpointGuildBan(guildID, userID), nil, EndpointGuildBan(guildID, userID))
  465. if err != nil {
  466. return
  467. }
  468. err = unmarshal(body, &st)
  469. return
  470. }
  471. // GuildBanCreateWithReason bans the given user from the given guild also providing a reaso.
  472. // guildID : The ID of a Guild.
  473. // userID : The ID of a User
  474. // reason : The reason for this ban
  475. // days : The number of days of previous comments to delete.
  476. func (s *Session) GuildBanCreateWithReason(guildID, userID, reason string, days int) (err error) {
  477. uri := EndpointGuildBan(guildID, userID)
  478. queryParams := url.Values{}
  479. if days > 0 {
  480. queryParams.Set("delete_message_days", strconv.Itoa(days))
  481. }
  482. if reason != "" {
  483. queryParams.Set("reason", reason)
  484. }
  485. if len(queryParams) > 0 {
  486. uri += "?" + queryParams.Encode()
  487. }
  488. _, err = s.RequestWithBucketID("PUT", uri, nil, EndpointGuildBan(guildID, ""))
  489. return
  490. }
  491. // GuildBanDelete removes the given user from the guild bans
  492. // guildID : The ID of a Guild.
  493. // userID : The ID of a User
  494. func (s *Session) GuildBanDelete(guildID, userID string) (err error) {
  495. _, err = s.RequestWithBucketID("DELETE", EndpointGuildBan(guildID, userID), nil, EndpointGuildBan(guildID, ""))
  496. return
  497. }
  498. // GuildMembers returns a list of members for a guild.
  499. // guildID : The ID of a Guild.
  500. // after : The id of the member to return members after
  501. // limit : max number of members to return (max 1000)
  502. func (s *Session) GuildMembers(guildID string, after string, limit int) (st []*Member, err error) {
  503. uri := EndpointGuildMembers(guildID)
  504. v := url.Values{}
  505. if after != "" {
  506. v.Set("after", after)
  507. }
  508. if limit > 0 {
  509. v.Set("limit", strconv.Itoa(limit))
  510. }
  511. if len(v) > 0 {
  512. uri += "?" + v.Encode()
  513. }
  514. body, err := s.RequestWithBucketID("GET", uri, nil, EndpointGuildMembers(guildID))
  515. if err != nil {
  516. return
  517. }
  518. err = unmarshal(body, &st)
  519. return
  520. }
  521. // GuildMember returns a member of a guild.
  522. // guildID : The ID of a Guild.
  523. // userID : The ID of a User
  524. func (s *Session) GuildMember(guildID, userID string) (st *Member, err error) {
  525. body, err := s.RequestWithBucketID("GET", EndpointGuildMember(guildID, userID), nil, EndpointGuildMember(guildID, ""))
  526. if err != nil {
  527. return
  528. }
  529. err = unmarshal(body, &st)
  530. // The returned object doesn't have the GuildID attribute so we will set it here.
  531. st.GuildID = guildID
  532. return
  533. }
  534. // GuildMemberAdd force joins a user to the guild.
  535. // accessToken : Valid access_token for the user.
  536. // guildID : The ID of a Guild.
  537. // userID : The ID of a User.
  538. // nick : Value to set users nickname to
  539. // roles : A list of role ID's to set on the member.
  540. // mute : If the user is muted.
  541. // deaf : If the user is deafened.
  542. func (s *Session) GuildMemberAdd(accessToken, guildID, userID, nick string, roles []string, mute, deaf bool) (err error) {
  543. data := struct {
  544. AccessToken string `json:"access_token"`
  545. Nick string `json:"nick,omitempty"`
  546. Roles []string `json:"roles,omitempty"`
  547. Mute bool `json:"mute,omitempty"`
  548. Deaf bool `json:"deaf,omitempty"`
  549. }{accessToken, nick, roles, mute, deaf}
  550. _, err = s.RequestWithBucketID("PUT", EndpointGuildMember(guildID, userID), data, EndpointGuildMember(guildID, ""))
  551. if err != nil {
  552. return err
  553. }
  554. return err
  555. }
  556. // GuildMemberDelete removes the given user from the given guild.
  557. // guildID : The ID of a Guild.
  558. // userID : The ID of a User
  559. func (s *Session) GuildMemberDelete(guildID, userID string) (err error) {
  560. return s.GuildMemberDeleteWithReason(guildID, userID, "")
  561. }
  562. // GuildMemberDeleteWithReason removes the given user from the given guild.
  563. // guildID : The ID of a Guild.
  564. // userID : The ID of a User
  565. // reason : The reason for the kick
  566. func (s *Session) GuildMemberDeleteWithReason(guildID, userID, reason string) (err error) {
  567. uri := EndpointGuildMember(guildID, userID)
  568. if reason != "" {
  569. uri += "?reason=" + url.QueryEscape(reason)
  570. }
  571. _, err = s.RequestWithBucketID("DELETE", uri, nil, EndpointGuildMember(guildID, ""))
  572. return
  573. }
  574. // GuildMemberEdit edits the roles of a member.
  575. // guildID : The ID of a Guild.
  576. // userID : The ID of a User.
  577. // roles : A list of role ID's to set on the member.
  578. func (s *Session) GuildMemberEdit(guildID, userID string, roles []string) (err error) {
  579. data := struct {
  580. Roles []string `json:"roles"`
  581. }{roles}
  582. _, err = s.RequestWithBucketID("PATCH", EndpointGuildMember(guildID, userID), data, EndpointGuildMember(guildID, ""))
  583. return
  584. }
  585. // GuildMemberMove moves a guild member from one voice channel to another/none
  586. // guildID : The ID of a Guild.
  587. // userID : The ID of a User.
  588. // channelID : The ID of a channel to move user to or nil to remove from voice channel
  589. // NOTE : I am not entirely set on the name of this function and it may change
  590. // prior to the final 1.0.0 release of Discordgo
  591. func (s *Session) GuildMemberMove(guildID string, userID string, channelID *string) (err error) {
  592. data := struct {
  593. ChannelID *string `json:"channel_id"`
  594. }{channelID}
  595. _, err = s.RequestWithBucketID("PATCH", EndpointGuildMember(guildID, userID), data, EndpointGuildMember(guildID, ""))
  596. return
  597. }
  598. // GuildMemberNickname updates the nickname of a guild member
  599. // guildID : The ID of a guild
  600. // userID : The ID of a user
  601. // userID : The ID of a user or "@me" which is a shortcut of the current user ID
  602. // nickname : The nickname of the member, "" will reset their nickname
  603. func (s *Session) GuildMemberNickname(guildID, userID, nickname string) (err error) {
  604. data := struct {
  605. Nick string `json:"nick"`
  606. }{nickname}
  607. if userID == "@me" {
  608. userID += "/nick"
  609. }
  610. _, err = s.RequestWithBucketID("PATCH", EndpointGuildMember(guildID, userID), data, EndpointGuildMember(guildID, ""))
  611. return
  612. }
  613. // GuildMemberMute server mutes a guild member
  614. // guildID : The ID of a Guild.
  615. // userID : The ID of a User.
  616. // mute : boolean value for if the user should be muted
  617. func (s *Session) GuildMemberMute(guildID string, userID string, mute bool) (err error) {
  618. data := struct {
  619. Mute bool `json:"mute"`
  620. }{mute}
  621. _, err = s.RequestWithBucketID("PATCH", EndpointGuildMember(guildID, userID), data, EndpointGuildMember(guildID, ""))
  622. return
  623. }
  624. // GuildMemberTimeout times out a guild member
  625. // guildID : The ID of a Guild.
  626. // userID : The ID of a User.
  627. // until : The timestamp for how long a member should be timed out.
  628. // Set to nil to remove timeout.
  629. func (s *Session) GuildMemberTimeout(guildID string, userID string, until *time.Time) (err error) {
  630. data := struct {
  631. CommunicationDisabledUntil *time.Time `json:"communication_disabled_until"`
  632. }{until}
  633. _, err = s.RequestWithBucketID("PATCH", EndpointGuildMember(guildID, userID), data, EndpointGuildMember(guildID, ""))
  634. return
  635. }
  636. // GuildMemberDeafen server deafens a guild member
  637. // guildID : The ID of a Guild.
  638. // userID : The ID of a User.
  639. // deaf : boolean value for if the user should be deafened
  640. func (s *Session) GuildMemberDeafen(guildID string, userID string, deaf bool) (err error) {
  641. data := struct {
  642. Deaf bool `json:"deaf"`
  643. }{deaf}
  644. _, err = s.RequestWithBucketID("PATCH", EndpointGuildMember(guildID, userID), data, EndpointGuildMember(guildID, ""))
  645. return
  646. }
  647. // GuildMemberRoleAdd adds the specified role to a given member
  648. // guildID : The ID of a Guild.
  649. // userID : The ID of a User.
  650. // roleID : The ID of a Role to be assigned to the user.
  651. func (s *Session) GuildMemberRoleAdd(guildID, userID, roleID string) (err error) {
  652. _, err = s.RequestWithBucketID("PUT", EndpointGuildMemberRole(guildID, userID, roleID), nil, EndpointGuildMemberRole(guildID, "", ""))
  653. return
  654. }
  655. // GuildMemberRoleRemove removes the specified role to a given member
  656. // guildID : The ID of a Guild.
  657. // userID : The ID of a User.
  658. // roleID : The ID of a Role to be removed from the user.
  659. func (s *Session) GuildMemberRoleRemove(guildID, userID, roleID string) (err error) {
  660. _, err = s.RequestWithBucketID("DELETE", EndpointGuildMemberRole(guildID, userID, roleID), nil, EndpointGuildMemberRole(guildID, "", ""))
  661. return
  662. }
  663. // GuildChannels returns an array of Channel structures for all channels of a
  664. // given guild.
  665. // guildID : The ID of a Guild.
  666. func (s *Session) GuildChannels(guildID string) (st []*Channel, err error) {
  667. body, err := s.request("GET", EndpointGuildChannels(guildID), "", nil, EndpointGuildChannels(guildID), 0)
  668. if err != nil {
  669. return
  670. }
  671. err = unmarshal(body, &st)
  672. return
  673. }
  674. // GuildChannelCreateData is provided to GuildChannelCreateComplex
  675. type GuildChannelCreateData struct {
  676. Name string `json:"name"`
  677. Type ChannelType `json:"type"`
  678. Topic string `json:"topic,omitempty"`
  679. Bitrate int `json:"bitrate,omitempty"`
  680. UserLimit int `json:"user_limit,omitempty"`
  681. RateLimitPerUser int `json:"rate_limit_per_user,omitempty"`
  682. Position int `json:"position,omitempty"`
  683. PermissionOverwrites []*PermissionOverwrite `json:"permission_overwrites,omitempty"`
  684. ParentID string `json:"parent_id,omitempty"`
  685. NSFW bool `json:"nsfw,omitempty"`
  686. }
  687. // GuildChannelCreateComplex creates a new channel in the given guild
  688. // guildID : The ID of a Guild
  689. // data : A data struct describing the new Channel, Name and Type are mandatory, other fields depending on the type
  690. func (s *Session) GuildChannelCreateComplex(guildID string, data GuildChannelCreateData) (st *Channel, err error) {
  691. body, err := s.RequestWithBucketID("POST", EndpointGuildChannels(guildID), data, EndpointGuildChannels(guildID))
  692. if err != nil {
  693. return
  694. }
  695. err = unmarshal(body, &st)
  696. return
  697. }
  698. // GuildChannelCreate creates a new channel in the given guild
  699. // guildID : The ID of a Guild.
  700. // name : Name of the channel (2-100 chars length)
  701. // ctype : Type of the channel
  702. func (s *Session) GuildChannelCreate(guildID, name string, ctype ChannelType) (st *Channel, err error) {
  703. return s.GuildChannelCreateComplex(guildID, GuildChannelCreateData{
  704. Name: name,
  705. Type: ctype,
  706. })
  707. }
  708. // GuildChannelsReorder updates the order of channels in a guild
  709. // guildID : The ID of a Guild.
  710. // channels : Updated channels.
  711. func (s *Session) GuildChannelsReorder(guildID string, channels []*Channel) (err error) {
  712. data := make([]struct {
  713. ID string `json:"id"`
  714. Position int `json:"position"`
  715. }, len(channels))
  716. for i, c := range channels {
  717. data[i].ID = c.ID
  718. data[i].Position = c.Position
  719. }
  720. _, err = s.RequestWithBucketID("PATCH", EndpointGuildChannels(guildID), data, EndpointGuildChannels(guildID))
  721. return
  722. }
  723. // GuildInvites returns an array of Invite structures for the given guild
  724. // guildID : The ID of a Guild.
  725. func (s *Session) GuildInvites(guildID string) (st []*Invite, err error) {
  726. body, err := s.RequestWithBucketID("GET", EndpointGuildInvites(guildID), nil, EndpointGuildInvites(guildID))
  727. if err != nil {
  728. return
  729. }
  730. err = unmarshal(body, &st)
  731. return
  732. }
  733. // GuildRoles returns all roles for a given guild.
  734. // guildID : The ID of a Guild.
  735. func (s *Session) GuildRoles(guildID string) (st []*Role, err error) {
  736. body, err := s.RequestWithBucketID("GET", EndpointGuildRoles(guildID), nil, EndpointGuildRoles(guildID))
  737. if err != nil {
  738. return
  739. }
  740. err = unmarshal(body, &st)
  741. return // TODO return pointer
  742. }
  743. // GuildRoleCreate returns a new Guild Role.
  744. // guildID: The ID of a Guild.
  745. func (s *Session) GuildRoleCreate(guildID string) (st *Role, err error) {
  746. body, err := s.RequestWithBucketID("POST", EndpointGuildRoles(guildID), nil, EndpointGuildRoles(guildID))
  747. if err != nil {
  748. return
  749. }
  750. err = unmarshal(body, &st)
  751. return
  752. }
  753. // GuildRoleEdit updates an existing Guild Role with new values
  754. // guildID : The ID of a Guild.
  755. // roleID : The ID of a Role.
  756. // name : The name of the Role.
  757. // color : The color of the role (decimal, not hex).
  758. // hoist : Whether to display the role's users separately.
  759. // perm : The permissions for the role.
  760. // mention : Whether this role is mentionable
  761. func (s *Session) GuildRoleEdit(guildID, roleID, name string, color int, hoist bool, perm int64, mention bool) (st *Role, err error) {
  762. // Prevent sending a color int that is too big.
  763. if color > 0xFFFFFF {
  764. err = fmt.Errorf("color value cannot be larger than 0xFFFFFF")
  765. return nil, err
  766. }
  767. data := struct {
  768. Name string `json:"name"` // The role's name (overwrites existing)
  769. Color int `json:"color"` // The color the role should have (as a decimal, not hex)
  770. Hoist bool `json:"hoist"` // Whether to display the role's users separately
  771. Permissions int64 `json:"permissions,string"` // The overall permissions number of the role (overwrites existing)
  772. Mentionable bool `json:"mentionable"` // Whether this role is mentionable
  773. }{name, color, hoist, perm, mention}
  774. body, err := s.RequestWithBucketID("PATCH", EndpointGuildRole(guildID, roleID), data, EndpointGuildRole(guildID, ""))
  775. if err != nil {
  776. return
  777. }
  778. err = unmarshal(body, &st)
  779. return
  780. }
  781. // GuildRoleReorder reoders guild roles
  782. // guildID : The ID of a Guild.
  783. // roles : A list of ordered roles.
  784. func (s *Session) GuildRoleReorder(guildID string, roles []*Role) (st []*Role, err error) {
  785. body, err := s.RequestWithBucketID("PATCH", EndpointGuildRoles(guildID), roles, EndpointGuildRoles(guildID))
  786. if err != nil {
  787. return
  788. }
  789. err = unmarshal(body, &st)
  790. return
  791. }
  792. // GuildRoleDelete deletes an existing role.
  793. // guildID : The ID of a Guild.
  794. // roleID : The ID of a Role.
  795. func (s *Session) GuildRoleDelete(guildID, roleID string) (err error) {
  796. _, err = s.RequestWithBucketID("DELETE", EndpointGuildRole(guildID, roleID), nil, EndpointGuildRole(guildID, ""))
  797. return
  798. }
  799. // GuildPruneCount Returns the number of members that would be removed in a prune operation.
  800. // Requires 'KICK_MEMBER' permission.
  801. // guildID : The ID of a Guild.
  802. // days : The number of days to count prune for (1 or more).
  803. func (s *Session) GuildPruneCount(guildID string, days uint32) (count uint32, err error) {
  804. count = 0
  805. if days <= 0 {
  806. err = ErrPruneDaysBounds
  807. return
  808. }
  809. p := struct {
  810. Pruned uint32 `json:"pruned"`
  811. }{}
  812. uri := EndpointGuildPrune(guildID) + "?days=" + strconv.FormatUint(uint64(days), 10)
  813. body, err := s.RequestWithBucketID("GET", uri, nil, EndpointGuildPrune(guildID))
  814. if err != nil {
  815. return
  816. }
  817. err = unmarshal(body, &p)
  818. if err != nil {
  819. return
  820. }
  821. count = p.Pruned
  822. return
  823. }
  824. // GuildPrune Begin as prune operation. Requires the 'KICK_MEMBERS' permission.
  825. // Returns an object with one 'pruned' key indicating the number of members that were removed in the prune operation.
  826. // guildID : The ID of a Guild.
  827. // days : The number of days to count prune for (1 or more).
  828. func (s *Session) GuildPrune(guildID string, days uint32) (count uint32, err error) {
  829. count = 0
  830. if days <= 0 {
  831. err = ErrPruneDaysBounds
  832. return
  833. }
  834. data := struct {
  835. days uint32
  836. }{days}
  837. p := struct {
  838. Pruned uint32 `json:"pruned"`
  839. }{}
  840. body, err := s.RequestWithBucketID("POST", EndpointGuildPrune(guildID), data, EndpointGuildPrune(guildID))
  841. if err != nil {
  842. return
  843. }
  844. err = unmarshal(body, &p)
  845. if err != nil {
  846. return
  847. }
  848. count = p.Pruned
  849. return
  850. }
  851. // GuildIntegrations returns an array of Integrations for a guild.
  852. // guildID : The ID of a Guild.
  853. func (s *Session) GuildIntegrations(guildID string) (st []*Integration, err error) {
  854. body, err := s.RequestWithBucketID("GET", EndpointGuildIntegrations(guildID), nil, EndpointGuildIntegrations(guildID))
  855. if err != nil {
  856. return
  857. }
  858. err = unmarshal(body, &st)
  859. return
  860. }
  861. // GuildIntegrationCreate creates a Guild Integration.
  862. // guildID : The ID of a Guild.
  863. // integrationType : The Integration type.
  864. // integrationID : The ID of an integration.
  865. func (s *Session) GuildIntegrationCreate(guildID, integrationType, integrationID string) (err error) {
  866. data := struct {
  867. Type string `json:"type"`
  868. ID string `json:"id"`
  869. }{integrationType, integrationID}
  870. _, err = s.RequestWithBucketID("POST", EndpointGuildIntegrations(guildID), data, EndpointGuildIntegrations(guildID))
  871. return
  872. }
  873. // GuildIntegrationEdit edits a Guild Integration.
  874. // guildID : The ID of a Guild.
  875. // integrationType : The Integration type.
  876. // integrationID : The ID of an integration.
  877. // expireBehavior : The behavior when an integration subscription lapses (see the integration object documentation).
  878. // expireGracePeriod : Period (in seconds) where the integration will ignore lapsed subscriptions.
  879. // enableEmoticons : Whether emoticons should be synced for this integration (twitch only currently).
  880. func (s *Session) GuildIntegrationEdit(guildID, integrationID string, expireBehavior, expireGracePeriod int, enableEmoticons bool) (err error) {
  881. data := struct {
  882. ExpireBehavior int `json:"expire_behavior"`
  883. ExpireGracePeriod int `json:"expire_grace_period"`
  884. EnableEmoticons bool `json:"enable_emoticons"`
  885. }{expireBehavior, expireGracePeriod, enableEmoticons}
  886. _, err = s.RequestWithBucketID("PATCH", EndpointGuildIntegration(guildID, integrationID), data, EndpointGuildIntegration(guildID, ""))
  887. return
  888. }
  889. // GuildIntegrationDelete removes the given integration from the Guild.
  890. // guildID : The ID of a Guild.
  891. // integrationID : The ID of an integration.
  892. func (s *Session) GuildIntegrationDelete(guildID, integrationID string) (err error) {
  893. _, err = s.RequestWithBucketID("DELETE", EndpointGuildIntegration(guildID, integrationID), nil, EndpointGuildIntegration(guildID, ""))
  894. return
  895. }
  896. // GuildIcon returns an image.Image of a guild icon.
  897. // guildID : The ID of a Guild.
  898. func (s *Session) GuildIcon(guildID string) (img image.Image, err error) {
  899. g, err := s.Guild(guildID)
  900. if err != nil {
  901. return
  902. }
  903. if g.Icon == "" {
  904. err = ErrGuildNoIcon
  905. return
  906. }
  907. body, err := s.RequestWithBucketID("GET", EndpointGuildIcon(guildID, g.Icon), nil, EndpointGuildIcon(guildID, ""))
  908. if err != nil {
  909. return
  910. }
  911. img, _, err = image.Decode(bytes.NewReader(body))
  912. return
  913. }
  914. // GuildSplash returns an image.Image of a guild splash image.
  915. // guildID : The ID of a Guild.
  916. func (s *Session) GuildSplash(guildID string) (img image.Image, err error) {
  917. g, err := s.Guild(guildID)
  918. if err != nil {
  919. return
  920. }
  921. if g.Splash == "" {
  922. err = ErrGuildNoSplash
  923. return
  924. }
  925. body, err := s.RequestWithBucketID("GET", EndpointGuildSplash(guildID, g.Splash), nil, EndpointGuildSplash(guildID, ""))
  926. if err != nil {
  927. return
  928. }
  929. img, _, err = image.Decode(bytes.NewReader(body))
  930. return
  931. }
  932. // GuildEmbed returns the embed for a Guild.
  933. // guildID : The ID of a Guild.
  934. func (s *Session) GuildEmbed(guildID string) (st *GuildEmbed, err error) {
  935. body, err := s.RequestWithBucketID("GET", EndpointGuildEmbed(guildID), nil, EndpointGuildEmbed(guildID))
  936. if err != nil {
  937. return
  938. }
  939. err = unmarshal(body, &st)
  940. return
  941. }
  942. // GuildEmbedEdit returns the embed for a Guild.
  943. // guildID : The ID of a Guild.
  944. func (s *Session) GuildEmbedEdit(guildID string, enabled bool, channelID string) (err error) {
  945. data := GuildEmbed{enabled, channelID}
  946. _, err = s.RequestWithBucketID("PATCH", EndpointGuildEmbed(guildID), data, EndpointGuildEmbed(guildID))
  947. return
  948. }
  949. // GuildAuditLog returns the audit log for a Guild.
  950. // guildID : The ID of a Guild.
  951. // userID : If provided the log will be filtered for the given ID.
  952. // beforeID : If provided all log entries returned will be before the given ID.
  953. // actionType : If provided the log will be filtered for the given Action Type.
  954. // limit : The number messages that can be returned. (default 50, min 1, max 100)
  955. func (s *Session) GuildAuditLog(guildID, userID, beforeID string, actionType, limit int) (st *GuildAuditLog, err error) {
  956. uri := EndpointGuildAuditLogs(guildID)
  957. v := url.Values{}
  958. if userID != "" {
  959. v.Set("user_id", userID)
  960. }
  961. if beforeID != "" {
  962. v.Set("before", beforeID)
  963. }
  964. if actionType > 0 {
  965. v.Set("action_type", strconv.Itoa(actionType))
  966. }
  967. if limit > 0 {
  968. v.Set("limit", strconv.Itoa(limit))
  969. }
  970. if len(v) > 0 {
  971. uri = fmt.Sprintf("%s?%s", uri, v.Encode())
  972. }
  973. body, err := s.RequestWithBucketID("GET", uri, nil, EndpointGuildAuditLogs(guildID))
  974. if err != nil {
  975. return
  976. }
  977. err = unmarshal(body, &st)
  978. return
  979. }
  980. // GuildEmojis returns all emoji
  981. // guildID : The ID of a Guild.
  982. func (s *Session) GuildEmojis(guildID string) (emoji []*Emoji, err error) {
  983. body, err := s.RequestWithBucketID("GET", EndpointGuildEmojis(guildID), nil, EndpointGuildEmojis(guildID))
  984. if err != nil {
  985. return
  986. }
  987. err = unmarshal(body, &emoji)
  988. return
  989. }
  990. // GuildEmojiCreate creates a new emoji
  991. // guildID : The ID of a Guild.
  992. // name : The Name of the Emoji.
  993. // image : The base64 encoded emoji image, has to be smaller than 256KB.
  994. // roles : The roles for which this emoji will be whitelisted, can be nil.
  995. func (s *Session) GuildEmojiCreate(guildID, name, image string, roles []string) (emoji *Emoji, err error) {
  996. data := struct {
  997. Name string `json:"name"`
  998. Image string `json:"image"`
  999. Roles []string `json:"roles,omitempty"`
  1000. }{name, image, roles}
  1001. body, err := s.RequestWithBucketID("POST", EndpointGuildEmojis(guildID), data, EndpointGuildEmojis(guildID))
  1002. if err != nil {
  1003. return
  1004. }
  1005. err = unmarshal(body, &emoji)
  1006. return
  1007. }
  1008. // GuildEmojiEdit modifies an emoji
  1009. // guildID : The ID of a Guild.
  1010. // emojiID : The ID of an Emoji.
  1011. // name : The Name of the Emoji.
  1012. // roles : The roles for which this emoji will be whitelisted, can be nil.
  1013. func (s *Session) GuildEmojiEdit(guildID, emojiID, name string, roles []string) (emoji *Emoji, err error) {
  1014. data := struct {
  1015. Name string `json:"name"`
  1016. Roles []string `json:"roles,omitempty"`
  1017. }{name, roles}
  1018. body, err := s.RequestWithBucketID("PATCH", EndpointGuildEmoji(guildID, emojiID), data, EndpointGuildEmojis(guildID))
  1019. if err != nil {
  1020. return
  1021. }
  1022. err = unmarshal(body, &emoji)
  1023. return
  1024. }
  1025. // GuildEmojiDelete deletes an Emoji.
  1026. // guildID : The ID of a Guild.
  1027. // emojiID : The ID of an Emoji.
  1028. func (s *Session) GuildEmojiDelete(guildID, emojiID string) (err error) {
  1029. _, err = s.RequestWithBucketID("DELETE", EndpointGuildEmoji(guildID, emojiID), nil, EndpointGuildEmojis(guildID))
  1030. return
  1031. }
  1032. // GuildTemplate returns a GuildTemplate for the given code
  1033. // templateCode: The Code of a GuildTemplate
  1034. func (s *Session) GuildTemplate(templateCode string) (st *GuildTemplate, err error) {
  1035. body, err := s.RequestWithBucketID("GET", EndpointGuildTemplate(templateCode), nil, EndpointGuildTemplate(templateCode))
  1036. if err != nil {
  1037. return
  1038. }
  1039. err = unmarshal(body, &st)
  1040. return
  1041. }
  1042. // GuildCreateWithTemplate creates a guild based on a GuildTemplate
  1043. // templateCode: The Code of a GuildTemplate
  1044. // name: The name of the guild (2-100) characters
  1045. // icon: base64 encoded 128x128 image for the guild icon
  1046. func (s *Session) GuildCreateWithTemplate(templateCode, name, icon string) (st *Guild, err error) {
  1047. data := struct {
  1048. Name string `json:"name"`
  1049. Icon string `json:"icon"`
  1050. }{name, icon}
  1051. body, err := s.RequestWithBucketID("POST", EndpointGuildTemplate(templateCode), data, EndpointGuildTemplate(templateCode))
  1052. if err != nil {
  1053. return
  1054. }
  1055. err = unmarshal(body, &st)
  1056. return
  1057. }
  1058. // GuildTemplates returns all of GuildTemplates
  1059. // guildID: The ID of the guild
  1060. func (s *Session) GuildTemplates(guildID string) (st []*GuildTemplate, err error) {
  1061. body, err := s.RequestWithBucketID("GET", EndpointGuildTemplates(guildID), nil, EndpointGuildTemplates(guildID))
  1062. if err != nil {
  1063. return
  1064. }
  1065. err = unmarshal(body, &st)
  1066. return
  1067. }
  1068. // GuildTemplateCreate creates a template for the guild
  1069. // guildID: The ID of the guild
  1070. // name: The name of the template (1-100 characters)
  1071. // description: The description for the template (0-120 characters)
  1072. func (s *Session) GuildTemplateCreate(guildID, name, description string) (st *GuildTemplate) {
  1073. data := struct {
  1074. Name string `json:"name"`
  1075. Description string `json:"description"`
  1076. }{name, description}
  1077. body, err := s.RequestWithBucketID("POST", EndpointGuildTemplates(guildID), data, EndpointGuildTemplates(guildID))
  1078. if err != nil {
  1079. return
  1080. }
  1081. err = unmarshal(body, &st)
  1082. return
  1083. }
  1084. // GuildTemplateSync syncs the template to the guild's current state
  1085. // guildID: The ID of the guild
  1086. // templateCode: The code of the template
  1087. func (s *Session) GuildTemplateSync(guildID, templateCode string) (err error) {
  1088. _, err = s.RequestWithBucketID("PUT", EndpointGuildTemplateSync(guildID, templateCode), nil, EndpointGuildTemplateSync(guildID, ""))
  1089. return
  1090. }
  1091. // GuildTemplateEdit modifies the template's metadata
  1092. // guildID: The ID of the guild
  1093. // templateCode: The code of the template
  1094. // name: The name of the template (1-100 characters)
  1095. // description: The description for the template (0-120 characters)
  1096. func (s *Session) GuildTemplateEdit(guildID, templateCode, name, description string) (st *GuildTemplate, err error) {
  1097. data := struct {
  1098. Name string `json:"name,omitempty"`
  1099. Description string `json:"description,omitempty"`
  1100. }{name, description}
  1101. body, err := s.RequestWithBucketID("PATCH", EndpointGuildTemplateSync(guildID, templateCode), data, EndpointGuildTemplateSync(guildID, ""))
  1102. if err != nil {
  1103. return
  1104. }
  1105. err = unmarshal(body, &st)
  1106. return
  1107. }
  1108. // GuildTemplateDelete deletes the template
  1109. // guildID: The ID of the guild
  1110. // templateCode: The code of the template
  1111. func (s *Session) GuildTemplateDelete(guildID, templateCode string) (err error) {
  1112. _, err = s.RequestWithBucketID("DELETE", EndpointGuildTemplateSync(guildID, templateCode), nil, EndpointGuildTemplateSync(guildID, ""))
  1113. return
  1114. }
  1115. // ------------------------------------------------------------------------------------------------
  1116. // Functions specific to Discord Channels
  1117. // ------------------------------------------------------------------------------------------------
  1118. // Channel returns a Channel structure of a specific Channel.
  1119. // channelID : The ID of the Channel you want returned.
  1120. func (s *Session) Channel(channelID string) (st *Channel, err error) {
  1121. body, err := s.RequestWithBucketID("GET", EndpointChannel(channelID), nil, EndpointChannel(channelID))
  1122. if err != nil {
  1123. return
  1124. }
  1125. err = unmarshal(body, &st)
  1126. return
  1127. }
  1128. // ChannelEdit edits the given channel
  1129. // channelID : The ID of a Channel
  1130. // name : The new name to assign the channel.
  1131. func (s *Session) ChannelEdit(channelID, name string) (*Channel, error) {
  1132. return s.ChannelEditComplex(channelID, &ChannelEdit{
  1133. Name: name,
  1134. })
  1135. }
  1136. // ChannelEditComplex edits an existing channel, replacing the parameters entirely with ChannelEdit struct
  1137. // channelID : The ID of a Channel
  1138. // data : The channel struct to send
  1139. func (s *Session) ChannelEditComplex(channelID string, data *ChannelEdit) (st *Channel, err error) {
  1140. body, err := s.RequestWithBucketID("PATCH", EndpointChannel(channelID), data, EndpointChannel(channelID))
  1141. if err != nil {
  1142. return
  1143. }
  1144. err = unmarshal(body, &st)
  1145. return
  1146. }
  1147. // ChannelDelete deletes the given channel
  1148. // channelID : The ID of a Channel
  1149. func (s *Session) ChannelDelete(channelID string) (st *Channel, err error) {
  1150. body, err := s.RequestWithBucketID("DELETE", EndpointChannel(channelID), nil, EndpointChannel(channelID))
  1151. if err != nil {
  1152. return
  1153. }
  1154. err = unmarshal(body, &st)
  1155. return
  1156. }
  1157. // ChannelTyping broadcasts to all members that authenticated user is typing in
  1158. // the given channel.
  1159. // channelID : The ID of a Channel
  1160. func (s *Session) ChannelTyping(channelID string) (err error) {
  1161. _, err = s.RequestWithBucketID("POST", EndpointChannelTyping(channelID), nil, EndpointChannelTyping(channelID))
  1162. return
  1163. }
  1164. // ChannelMessages returns an array of Message structures for messages within
  1165. // a given channel.
  1166. // channelID : The ID of a Channel.
  1167. // limit : The number messages that can be returned. (max 100)
  1168. // beforeID : If provided all messages returned will be before given ID.
  1169. // afterID : If provided all messages returned will be after given ID.
  1170. // aroundID : If provided all messages returned will be around given ID.
  1171. func (s *Session) ChannelMessages(channelID string, limit int, beforeID, afterID, aroundID string) (st []*Message, err error) {
  1172. uri := EndpointChannelMessages(channelID)
  1173. v := url.Values{}
  1174. if limit > 0 {
  1175. v.Set("limit", strconv.Itoa(limit))
  1176. }
  1177. if afterID != "" {
  1178. v.Set("after", afterID)
  1179. }
  1180. if beforeID != "" {
  1181. v.Set("before", beforeID)
  1182. }
  1183. if aroundID != "" {
  1184. v.Set("around", aroundID)
  1185. }
  1186. if len(v) > 0 {
  1187. uri += "?" + v.Encode()
  1188. }
  1189. body, err := s.RequestWithBucketID("GET", uri, nil, EndpointChannelMessages(channelID))
  1190. if err != nil {
  1191. return
  1192. }
  1193. err = unmarshal(body, &st)
  1194. return
  1195. }
  1196. // ChannelMessage gets a single message by ID from a given channel.
  1197. // channeld : The ID of a Channel
  1198. // messageID : the ID of a Message
  1199. func (s *Session) ChannelMessage(channelID, messageID string) (st *Message, err error) {
  1200. response, err := s.RequestWithBucketID("GET", EndpointChannelMessage(channelID, messageID), nil, EndpointChannelMessage(channelID, ""))
  1201. if err != nil {
  1202. return
  1203. }
  1204. err = unmarshal(response, &st)
  1205. return
  1206. }
  1207. // ChannelMessageSend sends a message to the given channel.
  1208. // channelID : The ID of a Channel.
  1209. // content : The message to send.
  1210. func (s *Session) ChannelMessageSend(channelID string, content string) (*Message, error) {
  1211. return s.ChannelMessageSendComplex(channelID, &MessageSend{
  1212. Content: content,
  1213. })
  1214. }
  1215. var quoteEscaper = strings.NewReplacer("\\", "\\\\", `"`, "\\\"")
  1216. // ChannelMessageSendComplex sends a message to the given channel.
  1217. // channelID : The ID of a Channel.
  1218. // data : The message struct to send.
  1219. func (s *Session) ChannelMessageSendComplex(channelID string, data *MessageSend) (st *Message, err error) {
  1220. // TODO: Remove this when compatibility is not required.
  1221. if data.Embed != nil {
  1222. if data.Embeds == nil {
  1223. data.Embeds = []*MessageEmbed{data.Embed}
  1224. } else {
  1225. err = fmt.Errorf("cannot specify both Embed and Embeds")
  1226. return
  1227. }
  1228. }
  1229. for _, embed := range data.Embeds {
  1230. if embed.Type == "" {
  1231. embed.Type = "rich"
  1232. }
  1233. }
  1234. endpoint := EndpointChannelMessages(channelID)
  1235. // TODO: Remove this when compatibility is not required.
  1236. files := data.Files
  1237. if data.File != nil {
  1238. if files == nil {
  1239. files = []*File{data.File}
  1240. } else {
  1241. err = fmt.Errorf("cannot specify both File and Files")
  1242. return
  1243. }
  1244. }
  1245. var response []byte
  1246. if len(files) > 0 {
  1247. contentType, body, encodeErr := MultipartBodyWithJSON(data, files)
  1248. if encodeErr != nil {
  1249. return st, encodeErr
  1250. }
  1251. response, err = s.request("POST", endpoint, contentType, body, endpoint, 0)
  1252. } else {
  1253. response, err = s.RequestWithBucketID("POST", endpoint, data, endpoint)
  1254. }
  1255. if err != nil {
  1256. return
  1257. }
  1258. err = unmarshal(response, &st)
  1259. return
  1260. }
  1261. // ChannelMessageSendTTS sends a message to the given channel with Text to Speech.
  1262. // channelID : The ID of a Channel.
  1263. // content : The message to send.
  1264. func (s *Session) ChannelMessageSendTTS(channelID string, content string) (*Message, error) {
  1265. return s.ChannelMessageSendComplex(channelID, &MessageSend{
  1266. Content: content,
  1267. TTS: true,
  1268. })
  1269. }
  1270. // ChannelMessageSendEmbed sends a message to the given channel with embedded data.
  1271. // channelID : The ID of a Channel.
  1272. // embed : The embed data to send.
  1273. func (s *Session) ChannelMessageSendEmbed(channelID string, embed *MessageEmbed) (*Message, error) {
  1274. return s.ChannelMessageSendEmbeds(channelID, []*MessageEmbed{embed})
  1275. }
  1276. // ChannelMessageSendEmbeds sends a message to the given channel with multiple embedded data.
  1277. // channelID : The ID of a Channel.
  1278. // embeds : The embeds data to send.
  1279. func (s *Session) ChannelMessageSendEmbeds(channelID string, embeds []*MessageEmbed) (*Message, error) {
  1280. return s.ChannelMessageSendComplex(channelID, &MessageSend{
  1281. Embeds: embeds,
  1282. })
  1283. }
  1284. // ChannelMessageSendReply sends a message to the given channel with reference data.
  1285. // channelID : The ID of a Channel.
  1286. // content : The message to send.
  1287. // reference : The message reference to send.
  1288. func (s *Session) ChannelMessageSendReply(channelID string, content string, reference *MessageReference) (*Message, error) {
  1289. if reference == nil {
  1290. return nil, fmt.Errorf("reply attempted with nil message reference")
  1291. }
  1292. return s.ChannelMessageSendComplex(channelID, &MessageSend{
  1293. Content: content,
  1294. Reference: reference,
  1295. })
  1296. }
  1297. // ChannelMessageEdit edits an existing message, replacing it entirely with
  1298. // the given content.
  1299. // channelID : The ID of a Channel
  1300. // messageID : The ID of a Message
  1301. // content : The contents of the message
  1302. func (s *Session) ChannelMessageEdit(channelID, messageID, content string) (*Message, error) {
  1303. return s.ChannelMessageEditComplex(NewMessageEdit(channelID, messageID).SetContent(content))
  1304. }
  1305. // ChannelMessageEditComplex edits an existing message, replacing it entirely with
  1306. // the given MessageEdit struct
  1307. func (s *Session) ChannelMessageEditComplex(m *MessageEdit) (st *Message, err error) {
  1308. // TODO: Remove this when compatibility is not required.
  1309. if m.Embed != nil {
  1310. if m.Embeds == nil {
  1311. m.Embeds = []*MessageEmbed{m.Embed}
  1312. } else {
  1313. err = fmt.Errorf("cannot specify both Embed and Embeds")
  1314. return
  1315. }
  1316. }
  1317. for _, embed := range m.Embeds {
  1318. if embed.Type == "" {
  1319. embed.Type = "rich"
  1320. }
  1321. }
  1322. response, err := s.RequestWithBucketID("PATCH", EndpointChannelMessage(m.Channel, m.ID), m, EndpointChannelMessage(m.Channel, ""))
  1323. if err != nil {
  1324. return
  1325. }
  1326. err = unmarshal(response, &st)
  1327. return
  1328. }
  1329. // ChannelMessageEditEmbed edits an existing message with embedded data.
  1330. // channelID : The ID of a Channel
  1331. // messageID : The ID of a Message
  1332. // embed : The embed data to send
  1333. func (s *Session) ChannelMessageEditEmbed(channelID, messageID string, embed *MessageEmbed) (*Message, error) {
  1334. return s.ChannelMessageEditEmbeds(channelID, messageID, []*MessageEmbed{embed})
  1335. }
  1336. // ChannelMessageEditEmbeds edits an existing message with multiple embedded data.
  1337. // channelID : The ID of a Channel
  1338. // messageID : The ID of a Message
  1339. // embeds : The embeds data to send
  1340. func (s *Session) ChannelMessageEditEmbeds(channelID, messageID string, embeds []*MessageEmbed) (*Message, error) {
  1341. return s.ChannelMessageEditComplex(NewMessageEdit(channelID, messageID).SetEmbeds(embeds))
  1342. }
  1343. // ChannelMessageDelete deletes a message from the Channel.
  1344. func (s *Session) ChannelMessageDelete(channelID, messageID string) (err error) {
  1345. _, err = s.RequestWithBucketID("DELETE", EndpointChannelMessage(channelID, messageID), nil, EndpointChannelMessage(channelID, ""))
  1346. return
  1347. }
  1348. // ChannelMessagesBulkDelete bulk deletes the messages from the channel for the provided messageIDs.
  1349. // If only one messageID is in the slice call channelMessageDelete function.
  1350. // If the slice is empty do nothing.
  1351. // channelID : The ID of the channel for the messages to delete.
  1352. // messages : The IDs of the messages to be deleted. A slice of string IDs. A maximum of 100 messages.
  1353. func (s *Session) ChannelMessagesBulkDelete(channelID string, messages []string) (err error) {
  1354. if len(messages) == 0 {
  1355. return
  1356. }
  1357. if len(messages) == 1 {
  1358. err = s.ChannelMessageDelete(channelID, messages[0])
  1359. return
  1360. }
  1361. if len(messages) > 100 {
  1362. messages = messages[:100]
  1363. }
  1364. data := struct {
  1365. Messages []string `json:"messages"`
  1366. }{messages}
  1367. _, err = s.RequestWithBucketID("POST", EndpointChannelMessagesBulkDelete(channelID), data, EndpointChannelMessagesBulkDelete(channelID))
  1368. return
  1369. }
  1370. // ChannelMessagePin pins a message within a given channel.
  1371. // channelID: The ID of a channel.
  1372. // messageID: The ID of a message.
  1373. func (s *Session) ChannelMessagePin(channelID, messageID string) (err error) {
  1374. _, err = s.RequestWithBucketID("PUT", EndpointChannelMessagePin(channelID, messageID), nil, EndpointChannelMessagePin(channelID, ""))
  1375. return
  1376. }
  1377. // ChannelMessageUnpin unpins a message within a given channel.
  1378. // channelID: The ID of a channel.
  1379. // messageID: The ID of a message.
  1380. func (s *Session) ChannelMessageUnpin(channelID, messageID string) (err error) {
  1381. _, err = s.RequestWithBucketID("DELETE", EndpointChannelMessagePin(channelID, messageID), nil, EndpointChannelMessagePin(channelID, ""))
  1382. return
  1383. }
  1384. // ChannelMessagesPinned returns an array of Message structures for pinned messages
  1385. // within a given channel
  1386. // channelID : The ID of a Channel.
  1387. func (s *Session) ChannelMessagesPinned(channelID string) (st []*Message, err error) {
  1388. body, err := s.RequestWithBucketID("GET", EndpointChannelMessagesPins(channelID), nil, EndpointChannelMessagesPins(channelID))
  1389. if err != nil {
  1390. return
  1391. }
  1392. err = unmarshal(body, &st)
  1393. return
  1394. }
  1395. // ChannelFileSend sends a file to the given channel.
  1396. // channelID : The ID of a Channel.
  1397. // name: The name of the file.
  1398. // io.Reader : A reader for the file contents.
  1399. func (s *Session) ChannelFileSend(channelID, name string, r io.Reader) (*Message, error) {
  1400. return s.ChannelMessageSendComplex(channelID, &MessageSend{File: &File{Name: name, Reader: r}})
  1401. }
  1402. // ChannelFileSendWithMessage sends a file to the given channel with an message.
  1403. // DEPRECATED. Use ChannelMessageSendComplex instead.
  1404. // channelID : The ID of a Channel.
  1405. // content: Optional Message content.
  1406. // name: The name of the file.
  1407. // io.Reader : A reader for the file contents.
  1408. func (s *Session) ChannelFileSendWithMessage(channelID, content string, name string, r io.Reader) (*Message, error) {
  1409. return s.ChannelMessageSendComplex(channelID, &MessageSend{File: &File{Name: name, Reader: r}, Content: content})
  1410. }
  1411. // ChannelInvites returns an array of Invite structures for the given channel
  1412. // channelID : The ID of a Channel
  1413. func (s *Session) ChannelInvites(channelID string) (st []*Invite, err error) {
  1414. body, err := s.RequestWithBucketID("GET", EndpointChannelInvites(channelID), nil, EndpointChannelInvites(channelID))
  1415. if err != nil {
  1416. return
  1417. }
  1418. err = unmarshal(body, &st)
  1419. return
  1420. }
  1421. // ChannelInviteCreate creates a new invite for the given channel.
  1422. // channelID : The ID of a Channel
  1423. // i : An Invite struct with the values MaxAge, MaxUses and Temporary defined.
  1424. func (s *Session) ChannelInviteCreate(channelID string, i Invite) (st *Invite, err error) {
  1425. data := struct {
  1426. MaxAge int `json:"max_age"`
  1427. MaxUses int `json:"max_uses"`
  1428. Temporary bool `json:"temporary"`
  1429. Unique bool `json:"unique"`
  1430. }{i.MaxAge, i.MaxUses, i.Temporary, i.Unique}
  1431. body, err := s.RequestWithBucketID("POST", EndpointChannelInvites(channelID), data, EndpointChannelInvites(channelID))
  1432. if err != nil {
  1433. return
  1434. }
  1435. err = unmarshal(body, &st)
  1436. return
  1437. }
  1438. // ChannelPermissionSet creates a Permission Override for the given channel.
  1439. // NOTE: This func name may changed. Using Set instead of Create because
  1440. // you can both create a new override or update an override with this function.
  1441. func (s *Session) ChannelPermissionSet(channelID, targetID string, targetType PermissionOverwriteType, allow, deny int64) (err error) {
  1442. data := struct {
  1443. ID string `json:"id"`
  1444. Type PermissionOverwriteType `json:"type"`
  1445. Allow int64 `json:"allow,string"`
  1446. Deny int64 `json:"deny,string"`
  1447. }{targetID, targetType, allow, deny}
  1448. _, err = s.RequestWithBucketID("PUT", EndpointChannelPermission(channelID, targetID), data, EndpointChannelPermission(channelID, ""))
  1449. return
  1450. }
  1451. // ChannelPermissionDelete deletes a specific permission override for the given channel.
  1452. // NOTE: Name of this func may change.
  1453. func (s *Session) ChannelPermissionDelete(channelID, targetID string) (err error) {
  1454. _, err = s.RequestWithBucketID("DELETE", EndpointChannelPermission(channelID, targetID), nil, EndpointChannelPermission(channelID, ""))
  1455. return
  1456. }
  1457. // ChannelMessageCrosspost cross posts a message in a news channel to followers
  1458. // of the channel
  1459. // channelID : The ID of a Channel
  1460. // messageID : The ID of a Message
  1461. func (s *Session) ChannelMessageCrosspost(channelID, messageID string) (st *Message, err error) {
  1462. endpoint := EndpointChannelMessageCrosspost(channelID, messageID)
  1463. body, err := s.RequestWithBucketID("POST", endpoint, nil, endpoint)
  1464. if err != nil {
  1465. return
  1466. }
  1467. err = unmarshal(body, &st)
  1468. return
  1469. }
  1470. // ChannelNewsFollow follows a news channel in the targetID
  1471. // channelID : The ID of a News Channel
  1472. // targetID : The ID of a Channel where the News Channel should post to
  1473. func (s *Session) ChannelNewsFollow(channelID, targetID string) (st *ChannelFollow, err error) {
  1474. endpoint := EndpointChannelFollow(channelID)
  1475. data := struct {
  1476. WebhookChannelID string `json:"webhook_channel_id"`
  1477. }{targetID}
  1478. body, err := s.RequestWithBucketID("POST", endpoint, data, endpoint)
  1479. if err != nil {
  1480. return
  1481. }
  1482. err = unmarshal(body, &st)
  1483. return
  1484. }
  1485. // ------------------------------------------------------------------------------------------------
  1486. // Functions specific to Discord Invites
  1487. // ------------------------------------------------------------------------------------------------
  1488. // Invite returns an Invite structure of the given invite
  1489. // inviteID : The invite code
  1490. func (s *Session) Invite(inviteID string) (st *Invite, err error) {
  1491. body, err := s.RequestWithBucketID("GET", EndpointInvite(inviteID), nil, EndpointInvite(""))
  1492. if err != nil {
  1493. return
  1494. }
  1495. err = unmarshal(body, &st)
  1496. return
  1497. }
  1498. // InviteWithCounts returns an Invite structure of the given invite including approximate member counts
  1499. // inviteID : The invite code
  1500. func (s *Session) InviteWithCounts(inviteID string) (st *Invite, err error) {
  1501. body, err := s.RequestWithBucketID("GET", EndpointInvite(inviteID)+"?with_counts=true", nil, EndpointInvite(""))
  1502. if err != nil {
  1503. return
  1504. }
  1505. err = unmarshal(body, &st)
  1506. return
  1507. }
  1508. // InviteDelete deletes an existing invite
  1509. // inviteID : the code of an invite
  1510. func (s *Session) InviteDelete(inviteID string) (st *Invite, err error) {
  1511. body, err := s.RequestWithBucketID("DELETE", EndpointInvite(inviteID), nil, EndpointInvite(""))
  1512. if err != nil {
  1513. return
  1514. }
  1515. err = unmarshal(body, &st)
  1516. return
  1517. }
  1518. // InviteAccept accepts an Invite to a Guild or Channel
  1519. // inviteID : The invite code
  1520. func (s *Session) InviteAccept(inviteID string) (st *Invite, err error) {
  1521. body, err := s.RequestWithBucketID("POST", EndpointInvite(inviteID), nil, EndpointInvite(""))
  1522. if err != nil {
  1523. return
  1524. }
  1525. err = unmarshal(body, &st)
  1526. return
  1527. }
  1528. // ------------------------------------------------------------------------------------------------
  1529. // Functions specific to Discord Voice
  1530. // ------------------------------------------------------------------------------------------------
  1531. // VoiceRegions returns the voice server regions
  1532. func (s *Session) VoiceRegions() (st []*VoiceRegion, err error) {
  1533. body, err := s.RequestWithBucketID("GET", EndpointVoiceRegions, nil, EndpointVoiceRegions)
  1534. if err != nil {
  1535. return
  1536. }
  1537. err = unmarshal(body, &st)
  1538. return
  1539. }
  1540. // ------------------------------------------------------------------------------------------------
  1541. // Functions specific to Discord Websockets
  1542. // ------------------------------------------------------------------------------------------------
  1543. // Gateway returns the websocket Gateway address
  1544. func (s *Session) Gateway() (gateway string, err error) {
  1545. response, err := s.RequestWithBucketID("GET", EndpointGateway, nil, EndpointGateway)
  1546. if err != nil {
  1547. return
  1548. }
  1549. temp := struct {
  1550. URL string `json:"url"`
  1551. }{}
  1552. err = unmarshal(response, &temp)
  1553. if err != nil {
  1554. return
  1555. }
  1556. gateway = temp.URL
  1557. // Ensure the gateway always has a trailing slash.
  1558. // MacOS will fail to connect if we add query params without a trailing slash on the base domain.
  1559. if !strings.HasSuffix(gateway, "/") {
  1560. gateway += "/"
  1561. }
  1562. return
  1563. }
  1564. // GatewayBot returns the websocket Gateway address and the recommended number of shards
  1565. func (s *Session) GatewayBot() (st *GatewayBotResponse, err error) {
  1566. response, err := s.RequestWithBucketID("GET", EndpointGatewayBot, nil, EndpointGatewayBot)
  1567. if err != nil {
  1568. return
  1569. }
  1570. err = unmarshal(response, &st)
  1571. if err != nil {
  1572. return
  1573. }
  1574. // Ensure the gateway always has a trailing slash.
  1575. // MacOS will fail to connect if we add query params without a trailing slash on the base domain.
  1576. if !strings.HasSuffix(st.URL, "/") {
  1577. st.URL += "/"
  1578. }
  1579. return
  1580. }
  1581. // Functions specific to Webhooks
  1582. // WebhookCreate returns a new Webhook.
  1583. // channelID: The ID of a Channel.
  1584. // name : The name of the webhook.
  1585. // avatar : The avatar of the webhook.
  1586. func (s *Session) WebhookCreate(channelID, name, avatar string) (st *Webhook, err error) {
  1587. data := struct {
  1588. Name string `json:"name"`
  1589. Avatar string `json:"avatar,omitempty"`
  1590. }{name, avatar}
  1591. body, err := s.RequestWithBucketID("POST", EndpointChannelWebhooks(channelID), data, EndpointChannelWebhooks(channelID))
  1592. if err != nil {
  1593. return
  1594. }
  1595. err = unmarshal(body, &st)
  1596. return
  1597. }
  1598. // ChannelWebhooks returns all webhooks for a given channel.
  1599. // channelID: The ID of a channel.
  1600. func (s *Session) ChannelWebhooks(channelID string) (st []*Webhook, err error) {
  1601. body, err := s.RequestWithBucketID("GET", EndpointChannelWebhooks(channelID), nil, EndpointChannelWebhooks(channelID))
  1602. if err != nil {
  1603. return
  1604. }
  1605. err = unmarshal(body, &st)
  1606. return
  1607. }
  1608. // GuildWebhooks returns all webhooks for a given guild.
  1609. // guildID: The ID of a Guild.
  1610. func (s *Session) GuildWebhooks(guildID string) (st []*Webhook, err error) {
  1611. body, err := s.RequestWithBucketID("GET", EndpointGuildWebhooks(guildID), nil, EndpointGuildWebhooks(guildID))
  1612. if err != nil {
  1613. return
  1614. }
  1615. err = unmarshal(body, &st)
  1616. return
  1617. }
  1618. // Webhook returns a webhook for a given ID
  1619. // webhookID: The ID of a webhook.
  1620. func (s *Session) Webhook(webhookID string) (st *Webhook, err error) {
  1621. body, err := s.RequestWithBucketID("GET", EndpointWebhook(webhookID), nil, EndpointWebhooks)
  1622. if err != nil {
  1623. return
  1624. }
  1625. err = unmarshal(body, &st)
  1626. return
  1627. }
  1628. // WebhookWithToken returns a webhook for a given ID
  1629. // webhookID: The ID of a webhook.
  1630. // token : The auth token for the webhook.
  1631. func (s *Session) WebhookWithToken(webhookID, token string) (st *Webhook, err error) {
  1632. body, err := s.RequestWithBucketID("GET", EndpointWebhookToken(webhookID, token), nil, EndpointWebhookToken("", ""))
  1633. if err != nil {
  1634. return
  1635. }
  1636. err = unmarshal(body, &st)
  1637. return
  1638. }
  1639. // WebhookEdit updates an existing Webhook.
  1640. // webhookID: The ID of a webhook.
  1641. // name : The name of the webhook.
  1642. // avatar : The avatar of the webhook.
  1643. func (s *Session) WebhookEdit(webhookID, name, avatar, channelID string) (st *Role, err error) {
  1644. data := struct {
  1645. Name string `json:"name,omitempty"`
  1646. Avatar string `json:"avatar,omitempty"`
  1647. ChannelID string `json:"channel_id,omitempty"`
  1648. }{name, avatar, channelID}
  1649. body, err := s.RequestWithBucketID("PATCH", EndpointWebhook(webhookID), data, EndpointWebhooks)
  1650. if err != nil {
  1651. return
  1652. }
  1653. err = unmarshal(body, &st)
  1654. return
  1655. }
  1656. // WebhookEditWithToken updates an existing Webhook with an auth token.
  1657. // webhookID: The ID of a webhook.
  1658. // token : The auth token for the webhook.
  1659. // name : The name of the webhook.
  1660. // avatar : The avatar of the webhook.
  1661. func (s *Session) WebhookEditWithToken(webhookID, token, name, avatar string) (st *Role, err error) {
  1662. data := struct {
  1663. Name string `json:"name,omitempty"`
  1664. Avatar string `json:"avatar,omitempty"`
  1665. }{name, avatar}
  1666. body, err := s.RequestWithBucketID("PATCH", EndpointWebhookToken(webhookID, token), data, EndpointWebhookToken("", ""))
  1667. if err != nil {
  1668. return
  1669. }
  1670. err = unmarshal(body, &st)
  1671. return
  1672. }
  1673. // WebhookDelete deletes a webhook for a given ID
  1674. // webhookID: The ID of a webhook.
  1675. func (s *Session) WebhookDelete(webhookID string) (err error) {
  1676. _, err = s.RequestWithBucketID("DELETE", EndpointWebhook(webhookID), nil, EndpointWebhooks)
  1677. return
  1678. }
  1679. // WebhookDeleteWithToken deletes a webhook for a given ID with an auth token.
  1680. // webhookID: The ID of a webhook.
  1681. // token : The auth token for the webhook.
  1682. func (s *Session) WebhookDeleteWithToken(webhookID, token string) (st *Webhook, err error) {
  1683. body, err := s.RequestWithBucketID("DELETE", EndpointWebhookToken(webhookID, token), nil, EndpointWebhookToken("", ""))
  1684. if err != nil {
  1685. return
  1686. }
  1687. err = unmarshal(body, &st)
  1688. return
  1689. }
  1690. func (s *Session) webhookExecute(webhookID, token string, wait bool, threadID string, data *WebhookParams) (st *Message, err error) {
  1691. uri := EndpointWebhookToken(webhookID, token)
  1692. v := url.Values{}
  1693. if wait {
  1694. v.Set("wait", "true")
  1695. }
  1696. if threadID != "" {
  1697. v.Set("thread_id", threadID)
  1698. }
  1699. if len(v) != 0 {
  1700. uri += "?" + v.Encode()
  1701. }
  1702. var response []byte
  1703. if len(data.Files) > 0 {
  1704. contentType, body, encodeErr := MultipartBodyWithJSON(data, data.Files)
  1705. if encodeErr != nil {
  1706. return st, encodeErr
  1707. }
  1708. response, err = s.request("POST", uri, contentType, body, uri, 0)
  1709. } else {
  1710. response, err = s.RequestWithBucketID("POST", uri, data, uri)
  1711. }
  1712. if !wait || err != nil {
  1713. return
  1714. }
  1715. err = unmarshal(response, &st)
  1716. return
  1717. }
  1718. // WebhookExecute executes a webhook.
  1719. // webhookID: The ID of a webhook.
  1720. // token : The auth token for the webhook
  1721. // wait : Waits for server confirmation of message send and ensures that the return struct is populated (it is nil otherwise)
  1722. func (s *Session) WebhookExecute(webhookID, token string, wait bool, data *WebhookParams) (st *Message, err error) {
  1723. return s.webhookExecute(webhookID, token, wait, "", data)
  1724. }
  1725. // WebhookThreadExecute executes a webhook in a thread.
  1726. // webhookID: The ID of a webhook.
  1727. // token : The auth token for the webhook
  1728. // wait : Waits for server confirmation of message send and ensures that the return struct is populated (it is nil otherwise)
  1729. // threadID : Sends a message to the specified thread within a webhook's channel. The thread will automatically be unarchived.
  1730. func (s *Session) WebhookThreadExecute(webhookID, token string, wait bool, threadID string, data *WebhookParams) (st *Message, err error) {
  1731. return s.webhookExecute(webhookID, token, wait, threadID, data)
  1732. }
  1733. // WebhookMessage gets a webhook message.
  1734. // webhookID : The ID of a webhook
  1735. // token : The auth token for the webhook
  1736. // messageID : The ID of message to get
  1737. func (s *Session) WebhookMessage(webhookID, token, messageID string) (message *Message, err error) {
  1738. uri := EndpointWebhookMessage(webhookID, token, messageID)
  1739. body, err := s.RequestWithBucketID("GET", uri, nil, EndpointWebhookToken("", ""))
  1740. if err != nil {
  1741. return
  1742. }
  1743. err = json.Unmarshal(body, &message)
  1744. return
  1745. }
  1746. // WebhookMessageEdit edits a webhook message and returns a new one.
  1747. // webhookID : The ID of a webhook
  1748. // token : The auth token for the webhook
  1749. // messageID : The ID of message to edit
  1750. func (s *Session) WebhookMessageEdit(webhookID, token, messageID string, data *WebhookEdit) (st *Message, err error) {
  1751. uri := EndpointWebhookMessage(webhookID, token, messageID)
  1752. var response []byte
  1753. if len(data.Files) > 0 {
  1754. contentType, body, err := MultipartBodyWithJSON(data, data.Files)
  1755. if err != nil {
  1756. return nil, err
  1757. }
  1758. response, err = s.request("PATCH", uri, contentType, body, uri, 0)
  1759. if err != nil {
  1760. return nil, err
  1761. }
  1762. } else {
  1763. response, err = s.RequestWithBucketID("PATCH", uri, data, EndpointWebhookToken("", ""))
  1764. if err != nil {
  1765. return nil, err
  1766. }
  1767. }
  1768. err = unmarshal(response, &st)
  1769. return
  1770. }
  1771. // WebhookMessageDelete deletes a webhook message.
  1772. // webhookID : The ID of a webhook
  1773. // token : The auth token for the webhook
  1774. // messageID : The ID of a message to edit
  1775. func (s *Session) WebhookMessageDelete(webhookID, token, messageID string) (err error) {
  1776. uri := EndpointWebhookMessage(webhookID, token, messageID)
  1777. _, err = s.RequestWithBucketID("DELETE", uri, nil, EndpointWebhookToken("", ""))
  1778. return
  1779. }
  1780. // MessageReactionAdd creates an emoji reaction to a message.
  1781. // channelID : The channel ID.
  1782. // messageID : The message ID.
  1783. // emojiID : Either the unicode emoji for the reaction, or a guild emoji identifier.
  1784. func (s *Session) MessageReactionAdd(channelID, messageID, emojiID string) error {
  1785. // emoji such as #⃣ need to have # escaped
  1786. emojiID = strings.Replace(emojiID, "#", "%23", -1)
  1787. _, err := s.RequestWithBucketID("PUT", EndpointMessageReaction(channelID, messageID, emojiID, "@me"), nil, EndpointMessageReaction(channelID, "", "", ""))
  1788. return err
  1789. }
  1790. // MessageReactionRemove deletes an emoji reaction to a message.
  1791. // channelID : The channel ID.
  1792. // messageID : The message ID.
  1793. // emojiID : Either the unicode emoji for the reaction, or a guild emoji identifier.
  1794. // userID : @me or ID of the user to delete the reaction for.
  1795. func (s *Session) MessageReactionRemove(channelID, messageID, emojiID, userID string) error {
  1796. // emoji such as #⃣ need to have # escaped
  1797. emojiID = strings.Replace(emojiID, "#", "%23", -1)
  1798. _, err := s.RequestWithBucketID("DELETE", EndpointMessageReaction(channelID, messageID, emojiID, userID), nil, EndpointMessageReaction(channelID, "", "", ""))
  1799. return err
  1800. }
  1801. // MessageReactionsRemoveAll deletes all reactions from a message
  1802. // channelID : The channel ID
  1803. // messageID : The message ID.
  1804. func (s *Session) MessageReactionsRemoveAll(channelID, messageID string) error {
  1805. _, err := s.RequestWithBucketID("DELETE", EndpointMessageReactionsAll(channelID, messageID), nil, EndpointMessageReactionsAll(channelID, messageID))
  1806. return err
  1807. }
  1808. // MessageReactionsRemoveEmoji deletes all reactions of a certain emoji from a message
  1809. // channelID : The channel ID
  1810. // messageID : The message ID
  1811. // emojiID : The emoji ID
  1812. func (s *Session) MessageReactionsRemoveEmoji(channelID, messageID, emojiID string) error {
  1813. // emoji such as #⃣ need to have # escaped
  1814. emojiID = strings.Replace(emojiID, "#", "%23", -1)
  1815. _, err := s.RequestWithBucketID("DELETE", EndpointMessageReactions(channelID, messageID, emojiID), nil, EndpointMessageReactions(channelID, messageID, emojiID))
  1816. return err
  1817. }
  1818. // MessageReactions gets all the users reactions for a specific emoji.
  1819. // channelID : The channel ID.
  1820. // messageID : The message ID.
  1821. // emojiID : Either the unicode emoji for the reaction, or a guild emoji identifier.
  1822. // limit : max number of users to return (max 100)
  1823. // beforeID : If provided all reactions returned will be before given ID.
  1824. // afterID : If provided all reactions returned will be after given ID.
  1825. func (s *Session) MessageReactions(channelID, messageID, emojiID string, limit int, beforeID, afterID string) (st []*User, err error) {
  1826. // emoji such as #⃣ need to have # escaped
  1827. emojiID = strings.Replace(emojiID, "#", "%23", -1)
  1828. uri := EndpointMessageReactions(channelID, messageID, emojiID)
  1829. v := url.Values{}
  1830. if limit > 0 {
  1831. v.Set("limit", strconv.Itoa(limit))
  1832. }
  1833. if afterID != "" {
  1834. v.Set("after", afterID)
  1835. }
  1836. if beforeID != "" {
  1837. v.Set("before", beforeID)
  1838. }
  1839. if len(v) > 0 {
  1840. uri += "?" + v.Encode()
  1841. }
  1842. body, err := s.RequestWithBucketID("GET", uri, nil, EndpointMessageReaction(channelID, "", "", ""))
  1843. if err != nil {
  1844. return
  1845. }
  1846. err = unmarshal(body, &st)
  1847. return
  1848. }
  1849. // ------------------------------------------------------------------------------------------------
  1850. // Functions specific to threads
  1851. // ------------------------------------------------------------------------------------------------
  1852. // MessageThreadStartComplex creates a new thread from an existing message.
  1853. // channelID : Channel to create thread in
  1854. // messageID : Message to start thread from
  1855. // data : Parameters of the thread
  1856. func (s *Session) MessageThreadStartComplex(channelID, messageID string, data *ThreadStart) (ch *Channel, err error) {
  1857. endpoint := EndpointChannelMessageThread(channelID, messageID)
  1858. var body []byte
  1859. body, err = s.RequestWithBucketID("POST", endpoint, data, endpoint)
  1860. if err != nil {
  1861. return
  1862. }
  1863. err = unmarshal(body, &ch)
  1864. return
  1865. }
  1866. // MessageThreadStart creates a new thread from an existing message.
  1867. // channelID : Channel to create thread in
  1868. // messageID : Message to start thread from
  1869. // name : Name of the thread
  1870. // archiveDuration : Auto archive duration (in minutes)
  1871. func (s *Session) MessageThreadStart(channelID, messageID string, name string, archiveDuration int) (ch *Channel, err error) {
  1872. return s.MessageThreadStartComplex(channelID, messageID, &ThreadStart{
  1873. Name: name,
  1874. AutoArchiveDuration: archiveDuration,
  1875. })
  1876. }
  1877. // ThreadStartComplex creates a new thread.
  1878. // channelID : Channel to create thread in
  1879. // data : Parameters of the thread
  1880. func (s *Session) ThreadStartComplex(channelID string, data *ThreadStart) (ch *Channel, err error) {
  1881. endpoint := EndpointChannelThreads(channelID)
  1882. var body []byte
  1883. body, err = s.RequestWithBucketID("POST", endpoint, data, endpoint)
  1884. if err != nil {
  1885. return
  1886. }
  1887. err = unmarshal(body, &ch)
  1888. return
  1889. }
  1890. // ThreadStart creates a new thread.
  1891. // channelID : Channel to create thread in
  1892. // name : Name of the thread
  1893. // archiveDuration : Auto archive duration (in minutes)
  1894. func (s *Session) ThreadStart(channelID, name string, typ ChannelType, archiveDuration int) (ch *Channel, err error) {
  1895. return s.ThreadStartComplex(channelID, &ThreadStart{
  1896. Name: name,
  1897. Type: typ,
  1898. AutoArchiveDuration: archiveDuration,
  1899. })
  1900. }
  1901. // ThreadJoin adds current user to a thread
  1902. func (s *Session) ThreadJoin(id string) error {
  1903. endpoint := EndpointThreadMember(id, "@me")
  1904. _, err := s.RequestWithBucketID("PUT", endpoint, nil, endpoint)
  1905. return err
  1906. }
  1907. // ThreadLeave removes current user to a thread
  1908. func (s *Session) ThreadLeave(id string) error {
  1909. endpoint := EndpointThreadMember(id, "@me")
  1910. _, err := s.RequestWithBucketID("DELETE", endpoint, nil, endpoint)
  1911. return err
  1912. }
  1913. // ThreadMemberAdd adds another member to a thread
  1914. func (s *Session) ThreadMemberAdd(threadID, memberID string) error {
  1915. endpoint := EndpointThreadMember(threadID, memberID)
  1916. _, err := s.RequestWithBucketID("PUT", endpoint, nil, endpoint)
  1917. return err
  1918. }
  1919. // ThreadMemberRemove removes another member from a thread
  1920. func (s *Session) ThreadMemberRemove(threadID, memberID string) error {
  1921. endpoint := EndpointThreadMember(threadID, memberID)
  1922. _, err := s.RequestWithBucketID("DELETE", endpoint, nil, endpoint)
  1923. return err
  1924. }
  1925. // ThreadMember returns thread member object for the specified member of a thread
  1926. func (s *Session) ThreadMember(threadID, memberID string) (member *ThreadMember, err error) {
  1927. endpoint := EndpointThreadMember(threadID, memberID)
  1928. var body []byte
  1929. body, err = s.RequestWithBucketID("GET", endpoint, nil, endpoint)
  1930. if err != nil {
  1931. return
  1932. }
  1933. err = unmarshal(body, &member)
  1934. return
  1935. }
  1936. // ThreadMembers returns all members of specified thread.
  1937. func (s *Session) ThreadMembers(threadID string) (members []*ThreadMember, err error) {
  1938. var body []byte
  1939. body, err = s.RequestWithBucketID("GET", EndpointThreadMembers(threadID), nil, EndpointThreadMembers(threadID))
  1940. if err != nil {
  1941. return
  1942. }
  1943. err = unmarshal(body, &members)
  1944. return
  1945. }
  1946. // ThreadsActive returns all active threads for specified channel.
  1947. func (s *Session) ThreadsActive(channelID string) (threads *ThreadsList, err error) {
  1948. var body []byte
  1949. body, err = s.RequestWithBucketID("GET", EndpointChannelActiveThreads(channelID), nil, EndpointChannelActiveThreads(channelID))
  1950. if err != nil {
  1951. return
  1952. }
  1953. err = unmarshal(body, &threads)
  1954. return
  1955. }
  1956. // GuildThreadsActive returns all active threads for specified guild.
  1957. func (s *Session) GuildThreadsActive(guildID string) (threads *ThreadsList, err error) {
  1958. var body []byte
  1959. body, err = s.RequestWithBucketID("GET", EndpointGuildActiveThreads(guildID), nil, EndpointGuildActiveThreads(guildID))
  1960. if err != nil {
  1961. return
  1962. }
  1963. err = unmarshal(body, &threads)
  1964. return
  1965. }
  1966. // ThreadsArchived returns archived threads for specified channel.
  1967. // before : If specified returns only threads before the timestamp
  1968. // limit : Optional maximum amount of threads to return.
  1969. func (s *Session) ThreadsArchived(channelID string, before *time.Time, limit int) (threads *ThreadsList, err error) {
  1970. endpoint := EndpointChannelPublicArchivedThreads(channelID)
  1971. v := url.Values{}
  1972. if before != nil {
  1973. v.Set("before", before.Format(time.RFC3339))
  1974. }
  1975. if limit > 0 {
  1976. v.Set("limit", strconv.Itoa(limit))
  1977. }
  1978. if len(v) > 0 {
  1979. endpoint += "?" + v.Encode()
  1980. }
  1981. var body []byte
  1982. body, err = s.RequestWithBucketID("GET", endpoint, nil, endpoint)
  1983. if err != nil {
  1984. return
  1985. }
  1986. err = unmarshal(body, &threads)
  1987. return
  1988. }
  1989. // ThreadsPrivateArchived returns archived private threads for specified channel.
  1990. // before : If specified returns only threads before the timestamp
  1991. // limit : Optional maximum amount of threads to return.
  1992. func (s *Session) ThreadsPrivateArchived(channelID string, before *time.Time, limit int) (threads *ThreadsList, err error) {
  1993. endpoint := EndpointChannelPrivateArchivedThreads(channelID)
  1994. v := url.Values{}
  1995. if before != nil {
  1996. v.Set("before", before.Format(time.RFC3339))
  1997. }
  1998. if limit > 0 {
  1999. v.Set("limit", strconv.Itoa(limit))
  2000. }
  2001. if len(v) > 0 {
  2002. endpoint += "?" + v.Encode()
  2003. }
  2004. var body []byte
  2005. body, err = s.RequestWithBucketID("GET", endpoint, nil, endpoint)
  2006. if err != nil {
  2007. return
  2008. }
  2009. err = unmarshal(body, &threads)
  2010. return
  2011. }
  2012. // ThreadsPrivateJoinedArchived returns archived joined private threads for specified channel.
  2013. // before : If specified returns only threads before the timestamp
  2014. // limit : Optional maximum amount of threads to return.
  2015. func (s *Session) ThreadsPrivateJoinedArchived(channelID string, before *time.Time, limit int) (threads *ThreadsList, err error) {
  2016. endpoint := EndpointChannelJoinedPrivateArchivedThreads(channelID)
  2017. v := url.Values{}
  2018. if before != nil {
  2019. v.Set("before", before.Format(time.RFC3339))
  2020. }
  2021. if limit > 0 {
  2022. v.Set("limit", strconv.Itoa(limit))
  2023. }
  2024. if len(v) > 0 {
  2025. endpoint += "?" + v.Encode()
  2026. }
  2027. var body []byte
  2028. body, err = s.RequestWithBucketID("GET", endpoint, nil, endpoint)
  2029. if err != nil {
  2030. return
  2031. }
  2032. err = unmarshal(body, &threads)
  2033. return
  2034. }
  2035. // ------------------------------------------------------------------------------------------------
  2036. // Functions specific to application (slash) commands
  2037. // ------------------------------------------------------------------------------------------------
  2038. // ApplicationCommandCreate creates a global application command and returns it.
  2039. // appID : The application ID.
  2040. // guildID : Guild ID to create guild-specific application command. If empty - creates global application command.
  2041. // cmd : New application command data.
  2042. func (s *Session) ApplicationCommandCreate(appID string, guildID string, cmd *ApplicationCommand) (ccmd *ApplicationCommand, err error) {
  2043. endpoint := EndpointApplicationGlobalCommands(appID)
  2044. if guildID != "" {
  2045. endpoint = EndpointApplicationGuildCommands(appID, guildID)
  2046. }
  2047. body, err := s.RequestWithBucketID("POST", endpoint, *cmd, endpoint)
  2048. if err != nil {
  2049. return
  2050. }
  2051. err = unmarshal(body, &ccmd)
  2052. return
  2053. }
  2054. // ApplicationCommandEdit edits application command and returns new command data.
  2055. // appID : The application ID.
  2056. // cmdID : Application command ID to edit.
  2057. // guildID : Guild ID to edit guild-specific application command. If empty - edits global application command.
  2058. // cmd : Updated application command data.
  2059. func (s *Session) ApplicationCommandEdit(appID, guildID, cmdID string, cmd *ApplicationCommand) (updated *ApplicationCommand, err error) {
  2060. endpoint := EndpointApplicationGlobalCommand(appID, cmdID)
  2061. if guildID != "" {
  2062. endpoint = EndpointApplicationGuildCommand(appID, guildID, cmdID)
  2063. }
  2064. body, err := s.RequestWithBucketID("PATCH", endpoint, *cmd, endpoint)
  2065. if err != nil {
  2066. return
  2067. }
  2068. err = unmarshal(body, &updated)
  2069. return
  2070. }
  2071. // ApplicationCommandBulkOverwrite Creates commands overwriting existing commands. Returns a list of commands.
  2072. // appID : The application ID.
  2073. // commands : The commands to create.
  2074. func (s *Session) ApplicationCommandBulkOverwrite(appID string, guildID string, commands []*ApplicationCommand) (createdCommands []*ApplicationCommand, err error) {
  2075. endpoint := EndpointApplicationGlobalCommands(appID)
  2076. if guildID != "" {
  2077. endpoint = EndpointApplicationGuildCommands(appID, guildID)
  2078. }
  2079. body, err := s.RequestWithBucketID("PUT", endpoint, commands, endpoint)
  2080. if err != nil {
  2081. return
  2082. }
  2083. err = unmarshal(body, &createdCommands)
  2084. return
  2085. }
  2086. // ApplicationCommandDelete deletes application command by ID.
  2087. // appID : The application ID.
  2088. // cmdID : Application command ID to delete.
  2089. // guildID : Guild ID to delete guild-specific application command. If empty - deletes global application command.
  2090. func (s *Session) ApplicationCommandDelete(appID, guildID, cmdID string) error {
  2091. endpoint := EndpointApplicationGlobalCommand(appID, cmdID)
  2092. if guildID != "" {
  2093. endpoint = EndpointApplicationGuildCommand(appID, guildID, cmdID)
  2094. }
  2095. _, err := s.RequestWithBucketID("DELETE", endpoint, nil, endpoint)
  2096. return err
  2097. }
  2098. // ApplicationCommand retrieves an application command by given ID.
  2099. // appID : The application ID.
  2100. // cmdID : Application command ID.
  2101. // guildID : Guild ID to retrieve guild-specific application command. If empty - retrieves global application command.
  2102. func (s *Session) ApplicationCommand(appID, guildID, cmdID string) (cmd *ApplicationCommand, err error) {
  2103. endpoint := EndpointApplicationGlobalCommand(appID, cmdID)
  2104. if guildID != "" {
  2105. endpoint = EndpointApplicationGuildCommand(appID, guildID, cmdID)
  2106. }
  2107. body, err := s.RequestWithBucketID("GET", endpoint, nil, endpoint)
  2108. if err != nil {
  2109. return
  2110. }
  2111. err = unmarshal(body, &cmd)
  2112. return
  2113. }
  2114. // ApplicationCommands retrieves all commands in application.
  2115. // appID : The application ID.
  2116. // guildID : Guild ID to retrieve all guild-specific application commands. If empty - retrieves global application commands.
  2117. func (s *Session) ApplicationCommands(appID, guildID string) (cmd []*ApplicationCommand, err error) {
  2118. endpoint := EndpointApplicationGlobalCommands(appID)
  2119. if guildID != "" {
  2120. endpoint = EndpointApplicationGuildCommands(appID, guildID)
  2121. }
  2122. body, err := s.RequestWithBucketID("GET", endpoint, nil, endpoint)
  2123. if err != nil {
  2124. return
  2125. }
  2126. err = unmarshal(body, &cmd)
  2127. return
  2128. }
  2129. // GuildApplicationCommandsPermissions returns permissions for application commands in a guild.
  2130. // appID : The application ID
  2131. // guildID : Guild ID to retrieve application commands permissions for.
  2132. func (s *Session) GuildApplicationCommandsPermissions(appID, guildID string) (permissions []*GuildApplicationCommandPermissions, err error) {
  2133. endpoint := EndpointApplicationCommandsGuildPermissions(appID, guildID)
  2134. var body []byte
  2135. body, err = s.RequestWithBucketID("GET", endpoint, nil, endpoint)
  2136. if err != nil {
  2137. return
  2138. }
  2139. err = unmarshal(body, &permissions)
  2140. return
  2141. }
  2142. // ApplicationCommandPermissions returns all permissions of an application command
  2143. // appID : The Application ID
  2144. // guildID : The guild ID containing the application command
  2145. // cmdID : The command ID to retrieve the permissions of
  2146. func (s *Session) ApplicationCommandPermissions(appID, guildID, cmdID string) (permissions *GuildApplicationCommandPermissions, err error) {
  2147. endpoint := EndpointApplicationCommandPermissions(appID, guildID, cmdID)
  2148. var body []byte
  2149. body, err = s.RequestWithBucketID("GET", endpoint, nil, endpoint)
  2150. if err != nil {
  2151. return
  2152. }
  2153. err = unmarshal(body, &permissions)
  2154. return
  2155. }
  2156. // ApplicationCommandPermissionsEdit edits the permissions of an application command
  2157. // appID : The Application ID
  2158. // guildID : The guild ID containing the application command
  2159. // cmdID : The command ID to edit the permissions of
  2160. // permissions : An object containing a list of permissions for the application command
  2161. func (s *Session) ApplicationCommandPermissionsEdit(appID, guildID, cmdID string, permissions *ApplicationCommandPermissionsList) (err error) {
  2162. endpoint := EndpointApplicationCommandPermissions(appID, guildID, cmdID)
  2163. _, err = s.RequestWithBucketID("PUT", endpoint, permissions, endpoint)
  2164. return
  2165. }
  2166. // ApplicationCommandPermissionsBatchEdit edits the permissions of a batch of commands
  2167. // appID : The Application ID
  2168. // guildID : The guild ID to batch edit commands of
  2169. // permissions : A list of permissions paired with a command ID, guild ID, and application ID per application command
  2170. func (s *Session) ApplicationCommandPermissionsBatchEdit(appID, guildID string, permissions []*GuildApplicationCommandPermissions) (err error) {
  2171. endpoint := EndpointApplicationCommandsGuildPermissions(appID, guildID)
  2172. _, err = s.RequestWithBucketID("PUT", endpoint, permissions, endpoint)
  2173. return
  2174. }
  2175. // InteractionRespond creates the response to an interaction.
  2176. // interaction : Interaction instance.
  2177. // resp : Response message data.
  2178. func (s *Session) InteractionRespond(interaction *Interaction, resp *InteractionResponse) (err error) {
  2179. endpoint := EndpointInteractionResponse(interaction.ID, interaction.Token)
  2180. if resp.Data != nil && len(resp.Data.Files) > 0 {
  2181. contentType, body, err := MultipartBodyWithJSON(resp, resp.Data.Files)
  2182. if err != nil {
  2183. return err
  2184. }
  2185. _, err = s.request("POST", endpoint, contentType, body, endpoint, 0)
  2186. } else {
  2187. _, err = s.RequestWithBucketID("POST", endpoint, *resp, endpoint)
  2188. }
  2189. return err
  2190. }
  2191. // InteractionResponse gets the response to an interaction.
  2192. // appID : The application ID.
  2193. // interaction : Interaction instance.
  2194. func (s *Session) InteractionResponse(appID string, interaction *Interaction) (*Message, error) {
  2195. return s.WebhookMessage(appID, interaction.Token, "@original")
  2196. }
  2197. // InteractionResponseEdit edits the response to an interaction.
  2198. // appID : The application ID.
  2199. // interaction : Interaction instance.
  2200. // newresp : Updated response message data.
  2201. func (s *Session) InteractionResponseEdit(appID string, interaction *Interaction, newresp *WebhookEdit) (*Message, error) {
  2202. return s.WebhookMessageEdit(appID, interaction.Token, "@original", newresp)
  2203. }
  2204. // InteractionResponseDelete deletes the response to an interaction.
  2205. // appID : The application ID.
  2206. // interaction : Interaction instance.
  2207. func (s *Session) InteractionResponseDelete(appID string, interaction *Interaction) error {
  2208. endpoint := EndpointInteractionResponseActions(appID, interaction.Token)
  2209. _, err := s.RequestWithBucketID("DELETE", endpoint, nil, endpoint)
  2210. return err
  2211. }
  2212. // FollowupMessageCreate creates the followup message for an interaction.
  2213. // appID : The application ID.
  2214. // interaction : Interaction instance.
  2215. // wait : Waits for server confirmation of message send and ensures that the return struct is populated (it is nil otherwise)
  2216. // data : Data of the message to send.
  2217. func (s *Session) FollowupMessageCreate(appID string, interaction *Interaction, wait bool, data *WebhookParams) (*Message, error) {
  2218. return s.WebhookExecute(appID, interaction.Token, wait, data)
  2219. }
  2220. // FollowupMessageEdit edits a followup message of an interaction.
  2221. // appID : The application ID.
  2222. // interaction : Interaction instance.
  2223. // messageID : The followup message ID.
  2224. // data : Data to update the message
  2225. func (s *Session) FollowupMessageEdit(appID string, interaction *Interaction, messageID string, data *WebhookEdit) (*Message, error) {
  2226. return s.WebhookMessageEdit(appID, interaction.Token, messageID, data)
  2227. }
  2228. // FollowupMessageDelete deletes a followup message of an interaction.
  2229. // appID : The application ID.
  2230. // interaction : Interaction instance.
  2231. // messageID : The followup message ID.
  2232. func (s *Session) FollowupMessageDelete(appID string, interaction *Interaction, messageID string) error {
  2233. return s.WebhookMessageDelete(appID, interaction.Token, messageID)
  2234. }
  2235. // ------------------------------------------------------------------------------------------------
  2236. // Functions specific to guilds scheduled events
  2237. // ------------------------------------------------------------------------------------------------
  2238. // GuildScheduledEvents returns an array of GuildScheduledEvent for a guild
  2239. // guildID : The ID of a Guild
  2240. // userCount : Whether to include the user count in the response
  2241. func (s *Session) GuildScheduledEvents(guildID string, userCount bool) (st []*GuildScheduledEvent, err error) {
  2242. uri := EndpointGuildScheduledEvents(guildID)
  2243. if userCount {
  2244. uri += "?with_user_count=true"
  2245. }
  2246. body, err := s.RequestWithBucketID("GET", uri, nil, EndpointGuildScheduledEvents(guildID))
  2247. if err != nil {
  2248. return
  2249. }
  2250. err = unmarshal(body, &st)
  2251. return
  2252. }
  2253. // GuildScheduledEvent returns a specific GuildScheduledEvent in a guild
  2254. // guildID : The ID of a Guild
  2255. // eventID : The ID of the event
  2256. // userCount : Whether to include the user count in the response
  2257. func (s *Session) GuildScheduledEvent(guildID, eventID string, userCount bool) (st *GuildScheduledEvent, err error) {
  2258. uri := EndpointGuildScheduledEvent(guildID, eventID)
  2259. if userCount {
  2260. uri += "?with_user_count=true"
  2261. }
  2262. body, err := s.RequestWithBucketID("GET", uri, nil, EndpointGuildScheduledEvent(guildID, eventID))
  2263. if err != nil {
  2264. return
  2265. }
  2266. err = unmarshal(body, &st)
  2267. return
  2268. }
  2269. // GuildScheduledEventCreate creates a GuildScheduledEvent for a guild and returns it
  2270. // guildID : The ID of a Guild
  2271. // eventID : The ID of the event
  2272. func (s *Session) GuildScheduledEventCreate(guildID string, event *GuildScheduledEventParams) (st *GuildScheduledEvent, err error) {
  2273. body, err := s.RequestWithBucketID("POST", EndpointGuildScheduledEvents(guildID), event, EndpointGuildScheduledEvents(guildID))
  2274. if err != nil {
  2275. return
  2276. }
  2277. err = unmarshal(body, &st)
  2278. return
  2279. }
  2280. // GuildScheduledEventEdit updates a specific event for a guild and returns it.
  2281. // guildID : The ID of a Guild
  2282. // eventID : The ID of the event
  2283. func (s *Session) GuildScheduledEventEdit(guildID, eventID string, event *GuildScheduledEventParams) (st *GuildScheduledEvent, err error) {
  2284. body, err := s.RequestWithBucketID("PATCH", EndpointGuildScheduledEvent(guildID, eventID), event, EndpointGuildScheduledEvent(guildID, eventID))
  2285. if err != nil {
  2286. return
  2287. }
  2288. err = unmarshal(body, &st)
  2289. return
  2290. }
  2291. // GuildScheduledEventDelete deletes a specific GuildScheduledEvent in a guild
  2292. // guildID : The ID of a Guild
  2293. // eventID : The ID of the event
  2294. func (s *Session) GuildScheduledEventDelete(guildID, eventID string) (err error) {
  2295. _, err = s.RequestWithBucketID("DELETE", EndpointGuildScheduledEvent(guildID, eventID), nil, EndpointGuildScheduledEvent(guildID, eventID))
  2296. return
  2297. }
  2298. // GuildScheduledEventUsers returns an array of GuildScheduledEventUser for a particular event in a guild
  2299. // guildID : The ID of a Guild
  2300. // eventID : The ID of the event
  2301. // limit : The maximum number of users to return (Max 100)
  2302. // withMember : Whether to include the member object in the response
  2303. // beforeID : If is not empty all returned users entries will be before the given ID
  2304. // afterID : If is not empty all returned users entries will be after the given ID
  2305. func (s *Session) GuildScheduledEventUsers(guildID, eventID string, limit int, withMember bool, beforeID, afterID string) (st []*GuildScheduledEventUser, err error) {
  2306. uri := EndpointGuildScheduledEventUsers(guildID, eventID)
  2307. queryParams := url.Values{}
  2308. if withMember {
  2309. queryParams.Set("with_member", "true")
  2310. }
  2311. if limit > 0 {
  2312. queryParams.Set("limit", strconv.Itoa(limit))
  2313. }
  2314. if beforeID != "" {
  2315. queryParams.Set("before", beforeID)
  2316. }
  2317. if afterID != "" {
  2318. queryParams.Set("after", afterID)
  2319. }
  2320. if len(queryParams) > 0 {
  2321. uri += "?" + queryParams.Encode()
  2322. }
  2323. body, err := s.RequestWithBucketID("GET", uri, nil, EndpointGuildScheduledEventUsers(guildID, eventID))
  2324. if err != nil {
  2325. return
  2326. }
  2327. err = unmarshal(body, &st)
  2328. return
  2329. }