restapi.go 90 KB

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