restapi.go 91 KB

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