restapi.go 73 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379
  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. return
  531. }
  532. // GuildMemberAdd force joins a user to the guild.
  533. // accessToken : Valid access_token for the user.
  534. // guildID : The ID of a Guild.
  535. // userID : The ID of a User.
  536. // nick : Value to set users nickname to
  537. // roles : A list of role ID's to set on the member.
  538. // mute : If the user is muted.
  539. // deaf : If the user is deafened.
  540. func (s *Session) GuildMemberAdd(accessToken, guildID, userID, nick string, roles []string, mute, deaf bool) (err error) {
  541. data := struct {
  542. AccessToken string `json:"access_token"`
  543. Nick string `json:"nick,omitempty"`
  544. Roles []string `json:"roles,omitempty"`
  545. Mute bool `json:"mute,omitempty"`
  546. Deaf bool `json:"deaf,omitempty"`
  547. }{accessToken, nick, roles, mute, deaf}
  548. _, err = s.RequestWithBucketID("PUT", EndpointGuildMember(guildID, userID), data, EndpointGuildMember(guildID, ""))
  549. if err != nil {
  550. return err
  551. }
  552. return err
  553. }
  554. // GuildMemberDelete removes the given user from the given guild.
  555. // guildID : The ID of a Guild.
  556. // userID : The ID of a User
  557. func (s *Session) GuildMemberDelete(guildID, userID string) (err error) {
  558. return s.GuildMemberDeleteWithReason(guildID, userID, "")
  559. }
  560. // GuildMemberDeleteWithReason removes the given user from the given guild.
  561. // guildID : The ID of a Guild.
  562. // userID : The ID of a User
  563. // reason : The reason for the kick
  564. func (s *Session) GuildMemberDeleteWithReason(guildID, userID, reason string) (err error) {
  565. uri := EndpointGuildMember(guildID, userID)
  566. if reason != "" {
  567. uri += "?reason=" + url.QueryEscape(reason)
  568. }
  569. _, err = s.RequestWithBucketID("DELETE", uri, nil, EndpointGuildMember(guildID, ""))
  570. return
  571. }
  572. // GuildMemberEdit edits the roles of a member.
  573. // guildID : The ID of a Guild.
  574. // userID : The ID of a User.
  575. // roles : A list of role ID's to set on the member.
  576. func (s *Session) GuildMemberEdit(guildID, userID string, roles []string) (err error) {
  577. data := struct {
  578. Roles []string `json:"roles"`
  579. }{roles}
  580. _, err = s.RequestWithBucketID("PATCH", EndpointGuildMember(guildID, userID), data, EndpointGuildMember(guildID, ""))
  581. return
  582. }
  583. // GuildMemberMove moves a guild member from one voice channel to another/none
  584. // guildID : The ID of a Guild.
  585. // userID : The ID of a User.
  586. // channelID : The ID of a channel to move user to or nil to remove from voice channel
  587. // NOTE : I am not entirely set on the name of this function and it may change
  588. // prior to the final 1.0.0 release of Discordgo
  589. func (s *Session) GuildMemberMove(guildID string, userID string, channelID *string) (err error) {
  590. data := struct {
  591. ChannelID *string `json:"channel_id"`
  592. }{channelID}
  593. _, err = s.RequestWithBucketID("PATCH", EndpointGuildMember(guildID, userID), data, EndpointGuildMember(guildID, ""))
  594. return
  595. }
  596. // GuildMemberNickname updates the nickname of a guild member
  597. // guildID : The ID of a guild
  598. // userID : The ID of a user
  599. // userID : The ID of a user or "@me" which is a shortcut of the current user ID
  600. // nickname : The nickname of the member, "" will reset their nickname
  601. func (s *Session) GuildMemberNickname(guildID, userID, nickname string) (err error) {
  602. data := struct {
  603. Nick string `json:"nick"`
  604. }{nickname}
  605. if userID == "@me" {
  606. userID += "/nick"
  607. }
  608. _, err = s.RequestWithBucketID("PATCH", EndpointGuildMember(guildID, userID), data, EndpointGuildMember(guildID, ""))
  609. return
  610. }
  611. // GuildMemberMute server mutes a guild member
  612. // guildID : The ID of a Guild.
  613. // userID : The ID of a User.
  614. // mute : boolean value for if the user should be muted
  615. func (s *Session) GuildMemberMute(guildID string, userID string, mute bool) (err error) {
  616. data := struct {
  617. Mute bool `json:"mute"`
  618. }{mute}
  619. _, err = s.RequestWithBucketID("PATCH", EndpointGuildMember(guildID, userID), data, EndpointGuildMember(guildID, ""))
  620. return
  621. }
  622. // GuildMemberTimeout times out a guild member
  623. // guildID : The ID of a Guild.
  624. // userID : The ID of a User.
  625. // until : The timestamp for how long a member should be timed out.
  626. // Set to nil to remove timeout.
  627. func (s *Session) GuildMemberTimeout(guildID string, userID string, until *time.Time) (err error) {
  628. data := struct {
  629. CommunicationDisabledUntil *time.Time `json:"communication_disabled_until"`
  630. }{until}
  631. _, err = s.RequestWithBucketID("PATCH", EndpointGuildMember(guildID, userID), data, EndpointGuildMember(guildID, ""))
  632. return
  633. }
  634. // GuildMemberDeafen server deafens a guild member
  635. // guildID : The ID of a Guild.
  636. // userID : The ID of a User.
  637. // deaf : boolean value for if the user should be deafened
  638. func (s *Session) GuildMemberDeafen(guildID string, userID string, deaf bool) (err error) {
  639. data := struct {
  640. Deaf bool `json:"deaf"`
  641. }{deaf}
  642. _, err = s.RequestWithBucketID("PATCH", EndpointGuildMember(guildID, userID), data, EndpointGuildMember(guildID, ""))
  643. return
  644. }
  645. // GuildMemberRoleAdd adds the specified role to a given member
  646. // guildID : The ID of a Guild.
  647. // userID : The ID of a User.
  648. // roleID : The ID of a Role to be assigned to the user.
  649. func (s *Session) GuildMemberRoleAdd(guildID, userID, roleID string) (err error) {
  650. _, err = s.RequestWithBucketID("PUT", EndpointGuildMemberRole(guildID, userID, roleID), nil, EndpointGuildMemberRole(guildID, "", ""))
  651. return
  652. }
  653. // GuildMemberRoleRemove removes the specified role to a given member
  654. // guildID : The ID of a Guild.
  655. // userID : The ID of a User.
  656. // roleID : The ID of a Role to be removed from the user.
  657. func (s *Session) GuildMemberRoleRemove(guildID, userID, roleID string) (err error) {
  658. _, err = s.RequestWithBucketID("DELETE", EndpointGuildMemberRole(guildID, userID, roleID), nil, EndpointGuildMemberRole(guildID, "", ""))
  659. return
  660. }
  661. // GuildChannels returns an array of Channel structures for all channels of a
  662. // given guild.
  663. // guildID : The ID of a Guild.
  664. func (s *Session) GuildChannels(guildID string) (st []*Channel, err error) {
  665. body, err := s.request("GET", EndpointGuildChannels(guildID), "", nil, EndpointGuildChannels(guildID), 0)
  666. if err != nil {
  667. return
  668. }
  669. err = unmarshal(body, &st)
  670. return
  671. }
  672. // GuildChannelCreateData is provided to GuildChannelCreateComplex
  673. type GuildChannelCreateData struct {
  674. Name string `json:"name"`
  675. Type ChannelType `json:"type"`
  676. Topic string `json:"topic,omitempty"`
  677. Bitrate int `json:"bitrate,omitempty"`
  678. UserLimit int `json:"user_limit,omitempty"`
  679. RateLimitPerUser int `json:"rate_limit_per_user,omitempty"`
  680. Position int `json:"position,omitempty"`
  681. PermissionOverwrites []*PermissionOverwrite `json:"permission_overwrites,omitempty"`
  682. ParentID string `json:"parent_id,omitempty"`
  683. NSFW bool `json:"nsfw,omitempty"`
  684. }
  685. // GuildChannelCreateComplex creates a new channel in the given guild
  686. // guildID : The ID of a Guild
  687. // data : A data struct describing the new Channel, Name and Type are mandatory, other fields depending on the type
  688. func (s *Session) GuildChannelCreateComplex(guildID string, data GuildChannelCreateData) (st *Channel, err error) {
  689. body, err := s.RequestWithBucketID("POST", EndpointGuildChannels(guildID), data, EndpointGuildChannels(guildID))
  690. if err != nil {
  691. return
  692. }
  693. err = unmarshal(body, &st)
  694. return
  695. }
  696. // GuildChannelCreate creates a new channel in the given guild
  697. // guildID : The ID of a Guild.
  698. // name : Name of the channel (2-100 chars length)
  699. // ctype : Type of the channel
  700. func (s *Session) GuildChannelCreate(guildID, name string, ctype ChannelType) (st *Channel, err error) {
  701. return s.GuildChannelCreateComplex(guildID, GuildChannelCreateData{
  702. Name: name,
  703. Type: ctype,
  704. })
  705. }
  706. // GuildChannelsReorder updates the order of channels in a guild
  707. // guildID : The ID of a Guild.
  708. // channels : Updated channels.
  709. func (s *Session) GuildChannelsReorder(guildID string, channels []*Channel) (err error) {
  710. data := make([]struct {
  711. ID string `json:"id"`
  712. Position int `json:"position"`
  713. }, len(channels))
  714. for i, c := range channels {
  715. data[i].ID = c.ID
  716. data[i].Position = c.Position
  717. }
  718. _, err = s.RequestWithBucketID("PATCH", EndpointGuildChannels(guildID), data, EndpointGuildChannels(guildID))
  719. return
  720. }
  721. // GuildInvites returns an array of Invite structures for the given guild
  722. // guildID : The ID of a Guild.
  723. func (s *Session) GuildInvites(guildID string) (st []*Invite, err error) {
  724. body, err := s.RequestWithBucketID("GET", EndpointGuildInvites(guildID), nil, EndpointGuildInvites(guildID))
  725. if err != nil {
  726. return
  727. }
  728. err = unmarshal(body, &st)
  729. return
  730. }
  731. // GuildRoles returns all roles for a given guild.
  732. // guildID : The ID of a Guild.
  733. func (s *Session) GuildRoles(guildID string) (st []*Role, err error) {
  734. body, err := s.RequestWithBucketID("GET", EndpointGuildRoles(guildID), nil, EndpointGuildRoles(guildID))
  735. if err != nil {
  736. return
  737. }
  738. err = unmarshal(body, &st)
  739. return // TODO return pointer
  740. }
  741. // GuildRoleCreate returns a new Guild Role.
  742. // guildID: The ID of a Guild.
  743. func (s *Session) GuildRoleCreate(guildID string) (st *Role, err error) {
  744. body, err := s.RequestWithBucketID("POST", EndpointGuildRoles(guildID), nil, EndpointGuildRoles(guildID))
  745. if err != nil {
  746. return
  747. }
  748. err = unmarshal(body, &st)
  749. return
  750. }
  751. // GuildRoleEdit updates an existing Guild Role with new values
  752. // guildID : The ID of a Guild.
  753. // roleID : The ID of a Role.
  754. // name : The name of the Role.
  755. // color : The color of the role (decimal, not hex).
  756. // hoist : Whether to display the role's users separately.
  757. // perm : The permissions for the role.
  758. // mention : Whether this role is mentionable
  759. func (s *Session) GuildRoleEdit(guildID, roleID, name string, color int, hoist bool, perm int64, mention bool) (st *Role, err error) {
  760. // Prevent sending a color int that is too big.
  761. if color > 0xFFFFFF {
  762. err = fmt.Errorf("color value cannot be larger than 0xFFFFFF")
  763. return nil, err
  764. }
  765. data := struct {
  766. Name string `json:"name"` // The role's name (overwrites existing)
  767. Color int `json:"color"` // The color the role should have (as a decimal, not hex)
  768. Hoist bool `json:"hoist"` // Whether to display the role's users separately
  769. Permissions int64 `json:"permissions,string"` // The overall permissions number of the role (overwrites existing)
  770. Mentionable bool `json:"mentionable"` // Whether this role is mentionable
  771. }{name, color, hoist, perm, mention}
  772. body, err := s.RequestWithBucketID("PATCH", EndpointGuildRole(guildID, roleID), data, EndpointGuildRole(guildID, ""))
  773. if err != nil {
  774. return
  775. }
  776. err = unmarshal(body, &st)
  777. return
  778. }
  779. // GuildRoleReorder reoders guild roles
  780. // guildID : The ID of a Guild.
  781. // roles : A list of ordered roles.
  782. func (s *Session) GuildRoleReorder(guildID string, roles []*Role) (st []*Role, err error) {
  783. body, err := s.RequestWithBucketID("PATCH", EndpointGuildRoles(guildID), roles, EndpointGuildRoles(guildID))
  784. if err != nil {
  785. return
  786. }
  787. err = unmarshal(body, &st)
  788. return
  789. }
  790. // GuildRoleDelete deletes an existing role.
  791. // guildID : The ID of a Guild.
  792. // roleID : The ID of a Role.
  793. func (s *Session) GuildRoleDelete(guildID, roleID string) (err error) {
  794. _, err = s.RequestWithBucketID("DELETE", EndpointGuildRole(guildID, roleID), nil, EndpointGuildRole(guildID, ""))
  795. return
  796. }
  797. // GuildPruneCount Returns the number of members that would be removed in a prune operation.
  798. // Requires 'KICK_MEMBER' permission.
  799. // guildID : The ID of a Guild.
  800. // days : The number of days to count prune for (1 or more).
  801. func (s *Session) GuildPruneCount(guildID string, days uint32) (count uint32, err error) {
  802. count = 0
  803. if days <= 0 {
  804. err = ErrPruneDaysBounds
  805. return
  806. }
  807. p := struct {
  808. Pruned uint32 `json:"pruned"`
  809. }{}
  810. uri := EndpointGuildPrune(guildID) + "?days=" + strconv.FormatUint(uint64(days), 10)
  811. body, err := s.RequestWithBucketID("GET", uri, nil, EndpointGuildPrune(guildID))
  812. if err != nil {
  813. return
  814. }
  815. err = unmarshal(body, &p)
  816. if err != nil {
  817. return
  818. }
  819. count = p.Pruned
  820. return
  821. }
  822. // GuildPrune Begin as prune operation. Requires the 'KICK_MEMBERS' permission.
  823. // Returns an object with one 'pruned' key indicating the number of members that were removed in the prune operation.
  824. // guildID : The ID of a Guild.
  825. // days : The number of days to count prune for (1 or more).
  826. func (s *Session) GuildPrune(guildID string, days uint32) (count uint32, err error) {
  827. count = 0
  828. if days <= 0 {
  829. err = ErrPruneDaysBounds
  830. return
  831. }
  832. data := struct {
  833. days uint32
  834. }{days}
  835. p := struct {
  836. Pruned uint32 `json:"pruned"`
  837. }{}
  838. body, err := s.RequestWithBucketID("POST", EndpointGuildPrune(guildID), data, EndpointGuildPrune(guildID))
  839. if err != nil {
  840. return
  841. }
  842. err = unmarshal(body, &p)
  843. if err != nil {
  844. return
  845. }
  846. count = p.Pruned
  847. return
  848. }
  849. // GuildIntegrations returns an array of Integrations for a guild.
  850. // guildID : The ID of a Guild.
  851. func (s *Session) GuildIntegrations(guildID string) (st []*Integration, err error) {
  852. body, err := s.RequestWithBucketID("GET", EndpointGuildIntegrations(guildID), nil, EndpointGuildIntegrations(guildID))
  853. if err != nil {
  854. return
  855. }
  856. err = unmarshal(body, &st)
  857. return
  858. }
  859. // GuildIntegrationCreate creates a Guild Integration.
  860. // guildID : The ID of a Guild.
  861. // integrationType : The Integration type.
  862. // integrationID : The ID of an integration.
  863. func (s *Session) GuildIntegrationCreate(guildID, integrationType, integrationID string) (err error) {
  864. data := struct {
  865. Type string `json:"type"`
  866. ID string `json:"id"`
  867. }{integrationType, integrationID}
  868. _, err = s.RequestWithBucketID("POST", EndpointGuildIntegrations(guildID), data, EndpointGuildIntegrations(guildID))
  869. return
  870. }
  871. // GuildIntegrationEdit edits a Guild Integration.
  872. // guildID : The ID of a Guild.
  873. // integrationType : The Integration type.
  874. // integrationID : The ID of an integration.
  875. // expireBehavior : The behavior when an integration subscription lapses (see the integration object documentation).
  876. // expireGracePeriod : Period (in seconds) where the integration will ignore lapsed subscriptions.
  877. // enableEmoticons : Whether emoticons should be synced for this integration (twitch only currently).
  878. func (s *Session) GuildIntegrationEdit(guildID, integrationID string, expireBehavior, expireGracePeriod int, enableEmoticons bool) (err error) {
  879. data := struct {
  880. ExpireBehavior int `json:"expire_behavior"`
  881. ExpireGracePeriod int `json:"expire_grace_period"`
  882. EnableEmoticons bool `json:"enable_emoticons"`
  883. }{expireBehavior, expireGracePeriod, enableEmoticons}
  884. _, err = s.RequestWithBucketID("PATCH", EndpointGuildIntegration(guildID, integrationID), data, EndpointGuildIntegration(guildID, ""))
  885. return
  886. }
  887. // GuildIntegrationDelete removes the given integration from the Guild.
  888. // guildID : The ID of a Guild.
  889. // integrationID : The ID of an integration.
  890. func (s *Session) GuildIntegrationDelete(guildID, integrationID string) (err error) {
  891. _, err = s.RequestWithBucketID("DELETE", EndpointGuildIntegration(guildID, integrationID), nil, EndpointGuildIntegration(guildID, ""))
  892. return
  893. }
  894. // GuildIntegrationSync syncs an integration.
  895. // guildID : The ID of a Guild.
  896. // integrationID : The ID of an integration.
  897. func (s *Session) GuildIntegrationSync(guildID, integrationID string) (err error) {
  898. _, err = s.RequestWithBucketID("POST", EndpointGuildIntegrationSync(guildID, integrationID), nil, EndpointGuildIntegration(guildID, ""))
  899. return
  900. }
  901. // GuildIcon returns an image.Image of a guild icon.
  902. // guildID : The ID of a Guild.
  903. func (s *Session) GuildIcon(guildID string) (img image.Image, err error) {
  904. g, err := s.Guild(guildID)
  905. if err != nil {
  906. return
  907. }
  908. if g.Icon == "" {
  909. err = ErrGuildNoIcon
  910. return
  911. }
  912. body, err := s.RequestWithBucketID("GET", EndpointGuildIcon(guildID, g.Icon), nil, EndpointGuildIcon(guildID, ""))
  913. if err != nil {
  914. return
  915. }
  916. img, _, err = image.Decode(bytes.NewReader(body))
  917. return
  918. }
  919. // GuildSplash returns an image.Image of a guild splash image.
  920. // guildID : The ID of a Guild.
  921. func (s *Session) GuildSplash(guildID string) (img image.Image, err error) {
  922. g, err := s.Guild(guildID)
  923. if err != nil {
  924. return
  925. }
  926. if g.Splash == "" {
  927. err = ErrGuildNoSplash
  928. return
  929. }
  930. body, err := s.RequestWithBucketID("GET", EndpointGuildSplash(guildID, g.Splash), nil, EndpointGuildSplash(guildID, ""))
  931. if err != nil {
  932. return
  933. }
  934. img, _, err = image.Decode(bytes.NewReader(body))
  935. return
  936. }
  937. // GuildEmbed returns the embed for a Guild.
  938. // guildID : The ID of a Guild.
  939. func (s *Session) GuildEmbed(guildID string) (st *GuildEmbed, err error) {
  940. body, err := s.RequestWithBucketID("GET", EndpointGuildEmbed(guildID), nil, EndpointGuildEmbed(guildID))
  941. if err != nil {
  942. return
  943. }
  944. err = unmarshal(body, &st)
  945. return
  946. }
  947. // GuildEmbedEdit returns the embed for a Guild.
  948. // guildID : The ID of a Guild.
  949. func (s *Session) GuildEmbedEdit(guildID string, enabled bool, channelID string) (err error) {
  950. data := GuildEmbed{enabled, channelID}
  951. _, err = s.RequestWithBucketID("PATCH", EndpointGuildEmbed(guildID), data, EndpointGuildEmbed(guildID))
  952. return
  953. }
  954. // GuildAuditLog returns the audit log for a Guild.
  955. // guildID : The ID of a Guild.
  956. // userID : If provided the log will be filtered for the given ID.
  957. // beforeID : If provided all log entries returned will be before the given ID.
  958. // actionType : If provided the log will be filtered for the given Action Type.
  959. // limit : The number messages that can be returned. (default 50, min 1, max 100)
  960. func (s *Session) GuildAuditLog(guildID, userID, beforeID string, actionType, limit int) (st *GuildAuditLog, err error) {
  961. uri := EndpointGuildAuditLogs(guildID)
  962. v := url.Values{}
  963. if userID != "" {
  964. v.Set("user_id", userID)
  965. }
  966. if beforeID != "" {
  967. v.Set("before", beforeID)
  968. }
  969. if actionType > 0 {
  970. v.Set("action_type", strconv.Itoa(actionType))
  971. }
  972. if limit > 0 {
  973. v.Set("limit", strconv.Itoa(limit))
  974. }
  975. if len(v) > 0 {
  976. uri = fmt.Sprintf("%s?%s", uri, v.Encode())
  977. }
  978. body, err := s.RequestWithBucketID("GET", uri, nil, EndpointGuildAuditLogs(guildID))
  979. if err != nil {
  980. return
  981. }
  982. err = unmarshal(body, &st)
  983. return
  984. }
  985. // GuildEmojis returns all emoji
  986. // guildID : The ID of a Guild.
  987. func (s *Session) GuildEmojis(guildID string) (emoji []*Emoji, err error) {
  988. body, err := s.RequestWithBucketID("GET", EndpointGuildEmojis(guildID), nil, EndpointGuildEmojis(guildID))
  989. if err != nil {
  990. return
  991. }
  992. err = unmarshal(body, &emoji)
  993. return
  994. }
  995. // GuildEmojiCreate creates a new emoji
  996. // guildID : The ID of a Guild.
  997. // name : The Name of the Emoji.
  998. // image : The base64 encoded emoji image, has to be smaller than 256KB.
  999. // roles : The roles for which this emoji will be whitelisted, can be nil.
  1000. func (s *Session) GuildEmojiCreate(guildID, name, image string, roles []string) (emoji *Emoji, err error) {
  1001. data := struct {
  1002. Name string `json:"name"`
  1003. Image string `json:"image"`
  1004. Roles []string `json:"roles,omitempty"`
  1005. }{name, image, roles}
  1006. body, err := s.RequestWithBucketID("POST", EndpointGuildEmojis(guildID), data, EndpointGuildEmojis(guildID))
  1007. if err != nil {
  1008. return
  1009. }
  1010. err = unmarshal(body, &emoji)
  1011. return
  1012. }
  1013. // GuildEmojiEdit modifies an emoji
  1014. // guildID : The ID of a Guild.
  1015. // emojiID : The ID of an Emoji.
  1016. // name : The Name of the Emoji.
  1017. // roles : The roles for which this emoji will be whitelisted, can be nil.
  1018. func (s *Session) GuildEmojiEdit(guildID, emojiID, name string, roles []string) (emoji *Emoji, err error) {
  1019. data := struct {
  1020. Name string `json:"name"`
  1021. Roles []string `json:"roles,omitempty"`
  1022. }{name, roles}
  1023. body, err := s.RequestWithBucketID("PATCH", EndpointGuildEmoji(guildID, emojiID), data, EndpointGuildEmojis(guildID))
  1024. if err != nil {
  1025. return
  1026. }
  1027. err = unmarshal(body, &emoji)
  1028. return
  1029. }
  1030. // GuildEmojiDelete deletes an Emoji.
  1031. // guildID : The ID of a Guild.
  1032. // emojiID : The ID of an Emoji.
  1033. func (s *Session) GuildEmojiDelete(guildID, emojiID string) (err error) {
  1034. _, err = s.RequestWithBucketID("DELETE", EndpointGuildEmoji(guildID, emojiID), nil, EndpointGuildEmojis(guildID))
  1035. return
  1036. }
  1037. // ------------------------------------------------------------------------------------------------
  1038. // Functions specific to Discord Channels
  1039. // ------------------------------------------------------------------------------------------------
  1040. // Channel returns a Channel structure of a specific Channel.
  1041. // channelID : The ID of the Channel you want returned.
  1042. func (s *Session) Channel(channelID string) (st *Channel, err error) {
  1043. body, err := s.RequestWithBucketID("GET", EndpointChannel(channelID), nil, EndpointChannel(channelID))
  1044. if err != nil {
  1045. return
  1046. }
  1047. err = unmarshal(body, &st)
  1048. return
  1049. }
  1050. // ChannelEdit edits the given channel
  1051. // channelID : The ID of a Channel
  1052. // name : The new name to assign the channel.
  1053. func (s *Session) ChannelEdit(channelID, name string) (*Channel, error) {
  1054. return s.ChannelEditComplex(channelID, &ChannelEdit{
  1055. Name: name,
  1056. })
  1057. }
  1058. // ChannelEditComplex edits an existing channel, replacing the parameters entirely with ChannelEdit struct
  1059. // channelID : The ID of a Channel
  1060. // data : The channel struct to send
  1061. func (s *Session) ChannelEditComplex(channelID string, data *ChannelEdit) (st *Channel, err error) {
  1062. body, err := s.RequestWithBucketID("PATCH", EndpointChannel(channelID), data, EndpointChannel(channelID))
  1063. if err != nil {
  1064. return
  1065. }
  1066. err = unmarshal(body, &st)
  1067. return
  1068. }
  1069. // ChannelDelete deletes the given channel
  1070. // channelID : The ID of a Channel
  1071. func (s *Session) ChannelDelete(channelID string) (st *Channel, err error) {
  1072. body, err := s.RequestWithBucketID("DELETE", EndpointChannel(channelID), nil, EndpointChannel(channelID))
  1073. if err != nil {
  1074. return
  1075. }
  1076. err = unmarshal(body, &st)
  1077. return
  1078. }
  1079. // ChannelTyping broadcasts to all members that authenticated user is typing in
  1080. // the given channel.
  1081. // channelID : The ID of a Channel
  1082. func (s *Session) ChannelTyping(channelID string) (err error) {
  1083. _, err = s.RequestWithBucketID("POST", EndpointChannelTyping(channelID), nil, EndpointChannelTyping(channelID))
  1084. return
  1085. }
  1086. // ChannelMessages returns an array of Message structures for messages within
  1087. // a given channel.
  1088. // channelID : The ID of a Channel.
  1089. // limit : The number messages that can be returned. (max 100)
  1090. // beforeID : If provided all messages returned will be before given ID.
  1091. // afterID : If provided all messages returned will be after given ID.
  1092. // aroundID : If provided all messages returned will be around given ID.
  1093. func (s *Session) ChannelMessages(channelID string, limit int, beforeID, afterID, aroundID string) (st []*Message, err error) {
  1094. uri := EndpointChannelMessages(channelID)
  1095. v := url.Values{}
  1096. if limit > 0 {
  1097. v.Set("limit", strconv.Itoa(limit))
  1098. }
  1099. if afterID != "" {
  1100. v.Set("after", afterID)
  1101. }
  1102. if beforeID != "" {
  1103. v.Set("before", beforeID)
  1104. }
  1105. if aroundID != "" {
  1106. v.Set("around", aroundID)
  1107. }
  1108. if len(v) > 0 {
  1109. uri += "?" + v.Encode()
  1110. }
  1111. body, err := s.RequestWithBucketID("GET", uri, nil, EndpointChannelMessages(channelID))
  1112. if err != nil {
  1113. return
  1114. }
  1115. err = unmarshal(body, &st)
  1116. return
  1117. }
  1118. // ChannelMessage gets a single message by ID from a given channel.
  1119. // channeld : The ID of a Channel
  1120. // messageID : the ID of a Message
  1121. func (s *Session) ChannelMessage(channelID, messageID string) (st *Message, err error) {
  1122. response, err := s.RequestWithBucketID("GET", EndpointChannelMessage(channelID, messageID), nil, EndpointChannelMessage(channelID, ""))
  1123. if err != nil {
  1124. return
  1125. }
  1126. err = unmarshal(response, &st)
  1127. return
  1128. }
  1129. // ChannelMessageAck acknowledges and marks the given message as read
  1130. // channeld : The ID of a Channel
  1131. // messageID : the ID of a Message
  1132. // lastToken : token returned by last ack
  1133. func (s *Session) ChannelMessageAck(channelID, messageID, lastToken string) (st *Ack, err error) {
  1134. body, err := s.RequestWithBucketID("POST", EndpointChannelMessageAck(channelID, messageID), &Ack{Token: lastToken}, EndpointChannelMessageAck(channelID, ""))
  1135. if err != nil {
  1136. return
  1137. }
  1138. err = unmarshal(body, &st)
  1139. return
  1140. }
  1141. // ChannelMessageSend sends a message to the given channel.
  1142. // channelID : The ID of a Channel.
  1143. // content : The message to send.
  1144. func (s *Session) ChannelMessageSend(channelID string, content string) (*Message, error) {
  1145. return s.ChannelMessageSendComplex(channelID, &MessageSend{
  1146. Content: content,
  1147. })
  1148. }
  1149. var quoteEscaper = strings.NewReplacer("\\", "\\\\", `"`, "\\\"")
  1150. // ChannelMessageSendComplex sends a message to the given channel.
  1151. // channelID : The ID of a Channel.
  1152. // data : The message struct to send.
  1153. func (s *Session) ChannelMessageSendComplex(channelID string, data *MessageSend) (st *Message, err error) {
  1154. // TODO: Remove this when compatibility is not required.
  1155. if data.Embed != nil {
  1156. if data.Embeds == nil {
  1157. data.Embeds = []*MessageEmbed{data.Embed}
  1158. } else {
  1159. err = fmt.Errorf("cannot specify both Embed and Embeds")
  1160. return
  1161. }
  1162. }
  1163. for _, embed := range data.Embeds {
  1164. if embed.Type == "" {
  1165. embed.Type = "rich"
  1166. }
  1167. }
  1168. endpoint := EndpointChannelMessages(channelID)
  1169. // TODO: Remove this when compatibility is not required.
  1170. files := data.Files
  1171. if data.File != nil {
  1172. if files == nil {
  1173. files = []*File{data.File}
  1174. } else {
  1175. err = fmt.Errorf("cannot specify both File and Files")
  1176. return
  1177. }
  1178. }
  1179. var response []byte
  1180. if len(files) > 0 {
  1181. contentType, body, encodeErr := MultipartBodyWithJSON(data, files)
  1182. if encodeErr != nil {
  1183. return st, encodeErr
  1184. }
  1185. response, err = s.request("POST", endpoint, contentType, body, endpoint, 0)
  1186. } else {
  1187. response, err = s.RequestWithBucketID("POST", endpoint, data, endpoint)
  1188. }
  1189. if err != nil {
  1190. return
  1191. }
  1192. err = unmarshal(response, &st)
  1193. return
  1194. }
  1195. // ChannelMessageSendTTS sends a message to the given channel with Text to Speech.
  1196. // channelID : The ID of a Channel.
  1197. // content : The message to send.
  1198. func (s *Session) ChannelMessageSendTTS(channelID string, content string) (*Message, error) {
  1199. return s.ChannelMessageSendComplex(channelID, &MessageSend{
  1200. Content: content,
  1201. TTS: true,
  1202. })
  1203. }
  1204. // ChannelMessageSendEmbed sends a message to the given channel with embedded data.
  1205. // channelID : The ID of a Channel.
  1206. // embed : The embed data to send.
  1207. func (s *Session) ChannelMessageSendEmbed(channelID string, embed *MessageEmbed) (*Message, error) {
  1208. return s.ChannelMessageSendEmbeds(channelID, []*MessageEmbed{embed})
  1209. }
  1210. // ChannelMessageSendEmbeds sends a message to the given channel with multiple embedded data.
  1211. // channelID : The ID of a Channel.
  1212. // embeds : The embeds data to send.
  1213. func (s *Session) ChannelMessageSendEmbeds(channelID string, embeds []*MessageEmbed) (*Message, error) {
  1214. return s.ChannelMessageSendComplex(channelID, &MessageSend{
  1215. Embeds: embeds,
  1216. })
  1217. }
  1218. // ChannelMessageSendReply sends a message to the given channel with reference data.
  1219. // channelID : The ID of a Channel.
  1220. // content : The message to send.
  1221. // reference : The message reference to send.
  1222. func (s *Session) ChannelMessageSendReply(channelID string, content string, reference *MessageReference) (*Message, error) {
  1223. if reference == nil {
  1224. return nil, fmt.Errorf("reply attempted with nil message reference")
  1225. }
  1226. return s.ChannelMessageSendComplex(channelID, &MessageSend{
  1227. Content: content,
  1228. Reference: reference,
  1229. })
  1230. }
  1231. // ChannelMessageEdit edits an existing message, replacing it entirely with
  1232. // the given content.
  1233. // channelID : The ID of a Channel
  1234. // messageID : The ID of a Message
  1235. // content : The contents of the message
  1236. func (s *Session) ChannelMessageEdit(channelID, messageID, content string) (*Message, error) {
  1237. return s.ChannelMessageEditComplex(NewMessageEdit(channelID, messageID).SetContent(content))
  1238. }
  1239. // ChannelMessageEditComplex edits an existing message, replacing it entirely with
  1240. // the given MessageEdit struct
  1241. func (s *Session) ChannelMessageEditComplex(m *MessageEdit) (st *Message, err error) {
  1242. // TODO: Remove this when compatibility is not required.
  1243. if m.Embed != nil {
  1244. if m.Embeds == nil {
  1245. m.Embeds = []*MessageEmbed{m.Embed}
  1246. } else {
  1247. err = fmt.Errorf("cannot specify both Embed and Embeds")
  1248. return
  1249. }
  1250. }
  1251. for _, embed := range m.Embeds {
  1252. if embed.Type == "" {
  1253. embed.Type = "rich"
  1254. }
  1255. }
  1256. response, err := s.RequestWithBucketID("PATCH", EndpointChannelMessage(m.Channel, m.ID), m, EndpointChannelMessage(m.Channel, ""))
  1257. if err != nil {
  1258. return
  1259. }
  1260. err = unmarshal(response, &st)
  1261. return
  1262. }
  1263. // ChannelMessageEditEmbed edits an existing message with embedded data.
  1264. // channelID : The ID of a Channel
  1265. // messageID : The ID of a Message
  1266. // embed : The embed data to send
  1267. func (s *Session) ChannelMessageEditEmbed(channelID, messageID string, embed *MessageEmbed) (*Message, error) {
  1268. return s.ChannelMessageEditEmbeds(channelID, messageID, []*MessageEmbed{embed})
  1269. }
  1270. // ChannelMessageEditEmbeds edits an existing message with multiple embedded data.
  1271. // channelID : The ID of a Channel
  1272. // messageID : The ID of a Message
  1273. // embeds : The embeds data to send
  1274. func (s *Session) ChannelMessageEditEmbeds(channelID, messageID string, embeds []*MessageEmbed) (*Message, error) {
  1275. return s.ChannelMessageEditComplex(NewMessageEdit(channelID, messageID).SetEmbeds(embeds))
  1276. }
  1277. // ChannelMessageDelete deletes a message from the Channel.
  1278. func (s *Session) ChannelMessageDelete(channelID, messageID string) (err error) {
  1279. _, err = s.RequestWithBucketID("DELETE", EndpointChannelMessage(channelID, messageID), nil, EndpointChannelMessage(channelID, ""))
  1280. return
  1281. }
  1282. // ChannelMessagesBulkDelete bulk deletes the messages from the channel for the provided messageIDs.
  1283. // If only one messageID is in the slice call channelMessageDelete function.
  1284. // If the slice is empty do nothing.
  1285. // channelID : The ID of the channel for the messages to delete.
  1286. // messages : The IDs of the messages to be deleted. A slice of string IDs. A maximum of 100 messages.
  1287. func (s *Session) ChannelMessagesBulkDelete(channelID string, messages []string) (err error) {
  1288. if len(messages) == 0 {
  1289. return
  1290. }
  1291. if len(messages) == 1 {
  1292. err = s.ChannelMessageDelete(channelID, messages[0])
  1293. return
  1294. }
  1295. if len(messages) > 100 {
  1296. messages = messages[:100]
  1297. }
  1298. data := struct {
  1299. Messages []string `json:"messages"`
  1300. }{messages}
  1301. _, err = s.RequestWithBucketID("POST", EndpointChannelMessagesBulkDelete(channelID), data, EndpointChannelMessagesBulkDelete(channelID))
  1302. return
  1303. }
  1304. // ChannelMessagePin pins a message within a given channel.
  1305. // channelID: The ID of a channel.
  1306. // messageID: The ID of a message.
  1307. func (s *Session) ChannelMessagePin(channelID, messageID string) (err error) {
  1308. _, err = s.RequestWithBucketID("PUT", EndpointChannelMessagePin(channelID, messageID), nil, EndpointChannelMessagePin(channelID, ""))
  1309. return
  1310. }
  1311. // ChannelMessageUnpin unpins a message within a given channel.
  1312. // channelID: The ID of a channel.
  1313. // messageID: The ID of a message.
  1314. func (s *Session) ChannelMessageUnpin(channelID, messageID string) (err error) {
  1315. _, err = s.RequestWithBucketID("DELETE", EndpointChannelMessagePin(channelID, messageID), nil, EndpointChannelMessagePin(channelID, ""))
  1316. return
  1317. }
  1318. // ChannelMessagesPinned returns an array of Message structures for pinned messages
  1319. // within a given channel
  1320. // channelID : The ID of a Channel.
  1321. func (s *Session) ChannelMessagesPinned(channelID string) (st []*Message, err error) {
  1322. body, err := s.RequestWithBucketID("GET", EndpointChannelMessagesPins(channelID), nil, EndpointChannelMessagesPins(channelID))
  1323. if err != nil {
  1324. return
  1325. }
  1326. err = unmarshal(body, &st)
  1327. return
  1328. }
  1329. // ChannelFileSend sends a file to the given channel.
  1330. // channelID : The ID of a Channel.
  1331. // name: The name of the file.
  1332. // io.Reader : A reader for the file contents.
  1333. func (s *Session) ChannelFileSend(channelID, name string, r io.Reader) (*Message, error) {
  1334. return s.ChannelMessageSendComplex(channelID, &MessageSend{File: &File{Name: name, Reader: r}})
  1335. }
  1336. // ChannelFileSendWithMessage sends a file to the given channel with an message.
  1337. // DEPRECATED. Use ChannelMessageSendComplex instead.
  1338. // channelID : The ID of a Channel.
  1339. // content: Optional Message content.
  1340. // name: The name of the file.
  1341. // io.Reader : A reader for the file contents.
  1342. func (s *Session) ChannelFileSendWithMessage(channelID, content string, name string, r io.Reader) (*Message, error) {
  1343. return s.ChannelMessageSendComplex(channelID, &MessageSend{File: &File{Name: name, Reader: r}, Content: content})
  1344. }
  1345. // ChannelInvites returns an array of Invite structures for the given channel
  1346. // channelID : The ID of a Channel
  1347. func (s *Session) ChannelInvites(channelID string) (st []*Invite, err error) {
  1348. body, err := s.RequestWithBucketID("GET", EndpointChannelInvites(channelID), nil, EndpointChannelInvites(channelID))
  1349. if err != nil {
  1350. return
  1351. }
  1352. err = unmarshal(body, &st)
  1353. return
  1354. }
  1355. // ChannelInviteCreate creates a new invite for the given channel.
  1356. // channelID : The ID of a Channel
  1357. // i : An Invite struct with the values MaxAge, MaxUses and Temporary defined.
  1358. func (s *Session) ChannelInviteCreate(channelID string, i Invite) (st *Invite, err error) {
  1359. data := struct {
  1360. MaxAge int `json:"max_age"`
  1361. MaxUses int `json:"max_uses"`
  1362. Temporary bool `json:"temporary"`
  1363. Unique bool `json:"unique"`
  1364. }{i.MaxAge, i.MaxUses, i.Temporary, i.Unique}
  1365. body, err := s.RequestWithBucketID("POST", EndpointChannelInvites(channelID), data, EndpointChannelInvites(channelID))
  1366. if err != nil {
  1367. return
  1368. }
  1369. err = unmarshal(body, &st)
  1370. return
  1371. }
  1372. // ChannelPermissionSet creates a Permission Override for the given channel.
  1373. // NOTE: This func name may changed. Using Set instead of Create because
  1374. // you can both create a new override or update an override with this function.
  1375. func (s *Session) ChannelPermissionSet(channelID, targetID string, targetType PermissionOverwriteType, allow, deny int64) (err error) {
  1376. data := struct {
  1377. ID string `json:"id"`
  1378. Type PermissionOverwriteType `json:"type"`
  1379. Allow int64 `json:"allow,string"`
  1380. Deny int64 `json:"deny,string"`
  1381. }{targetID, targetType, allow, deny}
  1382. _, err = s.RequestWithBucketID("PUT", EndpointChannelPermission(channelID, targetID), data, EndpointChannelPermission(channelID, ""))
  1383. return
  1384. }
  1385. // ChannelPermissionDelete deletes a specific permission override for the given channel.
  1386. // NOTE: Name of this func may change.
  1387. func (s *Session) ChannelPermissionDelete(channelID, targetID string) (err error) {
  1388. _, err = s.RequestWithBucketID("DELETE", EndpointChannelPermission(channelID, targetID), nil, EndpointChannelPermission(channelID, ""))
  1389. return
  1390. }
  1391. // ChannelMessageCrosspost cross posts a message in a news channel to followers
  1392. // of the channel
  1393. // channelID : The ID of a Channel
  1394. // messageID : The ID of a Message
  1395. func (s *Session) ChannelMessageCrosspost(channelID, messageID string) (st *Message, err error) {
  1396. endpoint := EndpointChannelMessageCrosspost(channelID, messageID)
  1397. body, err := s.RequestWithBucketID("POST", endpoint, nil, endpoint)
  1398. if err != nil {
  1399. return
  1400. }
  1401. err = unmarshal(body, &st)
  1402. return
  1403. }
  1404. // ChannelNewsFollow follows a news channel in the targetID
  1405. // channelID : The ID of a News Channel
  1406. // targetID : The ID of a Channel where the News Channel should post to
  1407. func (s *Session) ChannelNewsFollow(channelID, targetID string) (st *ChannelFollow, err error) {
  1408. endpoint := EndpointChannelFollow(channelID)
  1409. data := struct {
  1410. WebhookChannelID string `json:"webhook_channel_id"`
  1411. }{targetID}
  1412. body, err := s.RequestWithBucketID("POST", endpoint, data, endpoint)
  1413. if err != nil {
  1414. return
  1415. }
  1416. err = unmarshal(body, &st)
  1417. return
  1418. }
  1419. // ------------------------------------------------------------------------------------------------
  1420. // Functions specific to Discord Invites
  1421. // ------------------------------------------------------------------------------------------------
  1422. // Invite returns an Invite structure of the given invite
  1423. // inviteID : The invite code
  1424. func (s *Session) Invite(inviteID string) (st *Invite, err error) {
  1425. body, err := s.RequestWithBucketID("GET", EndpointInvite(inviteID), nil, EndpointInvite(""))
  1426. if err != nil {
  1427. return
  1428. }
  1429. err = unmarshal(body, &st)
  1430. return
  1431. }
  1432. // InviteWithCounts returns an Invite structure of the given invite including approximate member counts
  1433. // inviteID : The invite code
  1434. func (s *Session) InviteWithCounts(inviteID string) (st *Invite, err error) {
  1435. body, err := s.RequestWithBucketID("GET", EndpointInvite(inviteID)+"?with_counts=true", nil, EndpointInvite(""))
  1436. if err != nil {
  1437. return
  1438. }
  1439. err = unmarshal(body, &st)
  1440. return
  1441. }
  1442. // InviteDelete deletes an existing invite
  1443. // inviteID : the code of an invite
  1444. func (s *Session) InviteDelete(inviteID string) (st *Invite, err error) {
  1445. body, err := s.RequestWithBucketID("DELETE", EndpointInvite(inviteID), nil, EndpointInvite(""))
  1446. if err != nil {
  1447. return
  1448. }
  1449. err = unmarshal(body, &st)
  1450. return
  1451. }
  1452. // InviteAccept accepts an Invite to a Guild or Channel
  1453. // inviteID : The invite code
  1454. func (s *Session) InviteAccept(inviteID string) (st *Invite, err error) {
  1455. body, err := s.RequestWithBucketID("POST", EndpointInvite(inviteID), nil, EndpointInvite(""))
  1456. if err != nil {
  1457. return
  1458. }
  1459. err = unmarshal(body, &st)
  1460. return
  1461. }
  1462. // ------------------------------------------------------------------------------------------------
  1463. // Functions specific to Discord Voice
  1464. // ------------------------------------------------------------------------------------------------
  1465. // VoiceRegions returns the voice server regions
  1466. func (s *Session) VoiceRegions() (st []*VoiceRegion, err error) {
  1467. body, err := s.RequestWithBucketID("GET", EndpointVoiceRegions, nil, EndpointVoiceRegions)
  1468. if err != nil {
  1469. return
  1470. }
  1471. err = unmarshal(body, &st)
  1472. return
  1473. }
  1474. // ------------------------------------------------------------------------------------------------
  1475. // Functions specific to Discord Websockets
  1476. // ------------------------------------------------------------------------------------------------
  1477. // Gateway returns the websocket Gateway address
  1478. func (s *Session) Gateway() (gateway string, err error) {
  1479. response, err := s.RequestWithBucketID("GET", EndpointGateway, nil, EndpointGateway)
  1480. if err != nil {
  1481. return
  1482. }
  1483. temp := struct {
  1484. URL string `json:"url"`
  1485. }{}
  1486. err = unmarshal(response, &temp)
  1487. if err != nil {
  1488. return
  1489. }
  1490. gateway = temp.URL
  1491. // Ensure the gateway always has a trailing slash.
  1492. // MacOS will fail to connect if we add query params without a trailing slash on the base domain.
  1493. if !strings.HasSuffix(gateway, "/") {
  1494. gateway += "/"
  1495. }
  1496. return
  1497. }
  1498. // GatewayBot returns the websocket Gateway address and the recommended number of shards
  1499. func (s *Session) GatewayBot() (st *GatewayBotResponse, err error) {
  1500. response, err := s.RequestWithBucketID("GET", EndpointGatewayBot, nil, EndpointGatewayBot)
  1501. if err != nil {
  1502. return
  1503. }
  1504. err = unmarshal(response, &st)
  1505. if err != nil {
  1506. return
  1507. }
  1508. // Ensure the gateway always has a trailing slash.
  1509. // MacOS will fail to connect if we add query params without a trailing slash on the base domain.
  1510. if !strings.HasSuffix(st.URL, "/") {
  1511. st.URL += "/"
  1512. }
  1513. return
  1514. }
  1515. // Functions specific to Webhooks
  1516. // WebhookCreate returns a new Webhook.
  1517. // channelID: The ID of a Channel.
  1518. // name : The name of the webhook.
  1519. // avatar : The avatar of the webhook.
  1520. func (s *Session) WebhookCreate(channelID, name, avatar string) (st *Webhook, err error) {
  1521. data := struct {
  1522. Name string `json:"name"`
  1523. Avatar string `json:"avatar,omitempty"`
  1524. }{name, avatar}
  1525. body, err := s.RequestWithBucketID("POST", EndpointChannelWebhooks(channelID), data, EndpointChannelWebhooks(channelID))
  1526. if err != nil {
  1527. return
  1528. }
  1529. err = unmarshal(body, &st)
  1530. return
  1531. }
  1532. // ChannelWebhooks returns all webhooks for a given channel.
  1533. // channelID: The ID of a channel.
  1534. func (s *Session) ChannelWebhooks(channelID string) (st []*Webhook, err error) {
  1535. body, err := s.RequestWithBucketID("GET", EndpointChannelWebhooks(channelID), nil, EndpointChannelWebhooks(channelID))
  1536. if err != nil {
  1537. return
  1538. }
  1539. err = unmarshal(body, &st)
  1540. return
  1541. }
  1542. // GuildWebhooks returns all webhooks for a given guild.
  1543. // guildID: The ID of a Guild.
  1544. func (s *Session) GuildWebhooks(guildID string) (st []*Webhook, err error) {
  1545. body, err := s.RequestWithBucketID("GET", EndpointGuildWebhooks(guildID), nil, EndpointGuildWebhooks(guildID))
  1546. if err != nil {
  1547. return
  1548. }
  1549. err = unmarshal(body, &st)
  1550. return
  1551. }
  1552. // Webhook returns a webhook for a given ID
  1553. // webhookID: The ID of a webhook.
  1554. func (s *Session) Webhook(webhookID string) (st *Webhook, err error) {
  1555. body, err := s.RequestWithBucketID("GET", EndpointWebhook(webhookID), nil, EndpointWebhooks)
  1556. if err != nil {
  1557. return
  1558. }
  1559. err = unmarshal(body, &st)
  1560. return
  1561. }
  1562. // WebhookWithToken returns a webhook for a given ID
  1563. // webhookID: The ID of a webhook.
  1564. // token : The auth token for the webhook.
  1565. func (s *Session) WebhookWithToken(webhookID, token string) (st *Webhook, err error) {
  1566. body, err := s.RequestWithBucketID("GET", EndpointWebhookToken(webhookID, token), nil, EndpointWebhookToken("", ""))
  1567. if err != nil {
  1568. return
  1569. }
  1570. err = unmarshal(body, &st)
  1571. return
  1572. }
  1573. // WebhookEdit updates an existing Webhook.
  1574. // webhookID: The ID of a webhook.
  1575. // name : The name of the webhook.
  1576. // avatar : The avatar of the webhook.
  1577. func (s *Session) WebhookEdit(webhookID, name, avatar, channelID string) (st *Role, err error) {
  1578. data := struct {
  1579. Name string `json:"name,omitempty"`
  1580. Avatar string `json:"avatar,omitempty"`
  1581. ChannelID string `json:"channel_id,omitempty"`
  1582. }{name, avatar, channelID}
  1583. body, err := s.RequestWithBucketID("PATCH", EndpointWebhook(webhookID), data, EndpointWebhooks)
  1584. if err != nil {
  1585. return
  1586. }
  1587. err = unmarshal(body, &st)
  1588. return
  1589. }
  1590. // WebhookEditWithToken updates an existing Webhook with an auth token.
  1591. // webhookID: The ID of a webhook.
  1592. // token : The auth token for the webhook.
  1593. // name : The name of the webhook.
  1594. // avatar : The avatar of the webhook.
  1595. func (s *Session) WebhookEditWithToken(webhookID, token, name, avatar string) (st *Role, err error) {
  1596. data := struct {
  1597. Name string `json:"name,omitempty"`
  1598. Avatar string `json:"avatar,omitempty"`
  1599. }{name, avatar}
  1600. body, err := s.RequestWithBucketID("PATCH", EndpointWebhookToken(webhookID, token), data, EndpointWebhookToken("", ""))
  1601. if err != nil {
  1602. return
  1603. }
  1604. err = unmarshal(body, &st)
  1605. return
  1606. }
  1607. // WebhookDelete deletes a webhook for a given ID
  1608. // webhookID: The ID of a webhook.
  1609. func (s *Session) WebhookDelete(webhookID string) (err error) {
  1610. _, err = s.RequestWithBucketID("DELETE", EndpointWebhook(webhookID), nil, EndpointWebhooks)
  1611. return
  1612. }
  1613. // WebhookDeleteWithToken deletes a webhook for a given ID with an auth token.
  1614. // webhookID: The ID of a webhook.
  1615. // token : The auth token for the webhook.
  1616. func (s *Session) WebhookDeleteWithToken(webhookID, token string) (st *Webhook, err error) {
  1617. body, err := s.RequestWithBucketID("DELETE", EndpointWebhookToken(webhookID, token), nil, EndpointWebhookToken("", ""))
  1618. if err != nil {
  1619. return
  1620. }
  1621. err = unmarshal(body, &st)
  1622. return
  1623. }
  1624. // WebhookExecute executes a webhook.
  1625. // webhookID: The ID of a webhook.
  1626. // token : The auth token for the webhook
  1627. // wait : Waits for server confirmation of message send and ensures that the return struct is populated (it is nil otherwise)
  1628. func (s *Session) WebhookExecute(webhookID, token string, wait bool, data *WebhookParams) (st *Message, err error) {
  1629. uri := EndpointWebhookToken(webhookID, token)
  1630. if wait {
  1631. uri += "?wait=true"
  1632. }
  1633. var response []byte
  1634. if len(data.Files) > 0 {
  1635. contentType, body, encodeErr := MultipartBodyWithJSON(data, data.Files)
  1636. if encodeErr != nil {
  1637. return st, encodeErr
  1638. }
  1639. response, err = s.request("POST", uri, contentType, body, uri, 0)
  1640. } else {
  1641. response, err = s.RequestWithBucketID("POST", uri, data, uri)
  1642. }
  1643. if !wait || err != nil {
  1644. return
  1645. }
  1646. err = unmarshal(response, &st)
  1647. return
  1648. }
  1649. // WebhookMessage gets a webhook message.
  1650. // webhookID : The ID of a webhook
  1651. // token : The auth token for the webhook
  1652. // messageID : The ID of message to get
  1653. func (s *Session) WebhookMessage(webhookID, token, messageID string) (message *Message, err error) {
  1654. uri := EndpointWebhookMessage(webhookID, token, messageID)
  1655. body, err := s.RequestWithBucketID("GET", uri, nil, EndpointWebhookToken("", ""))
  1656. if err != nil {
  1657. return
  1658. }
  1659. err = json.Unmarshal(body, &message)
  1660. return
  1661. }
  1662. // WebhookMessageEdit edits a webhook message and returns a new one.
  1663. // webhookID : The ID of a webhook
  1664. // token : The auth token for the webhook
  1665. // messageID : The ID of message to edit
  1666. func (s *Session) WebhookMessageEdit(webhookID, token, messageID string, data *WebhookEdit) (st *Message, err error) {
  1667. uri := EndpointWebhookMessage(webhookID, token, messageID)
  1668. var response []byte
  1669. if len(data.Files) > 0 {
  1670. contentType, body, err := MultipartBodyWithJSON(data, data.Files)
  1671. if err != nil {
  1672. return nil, err
  1673. }
  1674. response, err = s.request("PATCH", uri, contentType, body, uri, 0)
  1675. if err != nil {
  1676. return nil, err
  1677. }
  1678. } else {
  1679. response, err = s.RequestWithBucketID("PATCH", uri, data, EndpointWebhookToken("", ""))
  1680. if err != nil {
  1681. return nil, err
  1682. }
  1683. }
  1684. err = unmarshal(response, &st)
  1685. return
  1686. }
  1687. // WebhookMessageDelete deletes a webhook message.
  1688. // webhookID : The ID of a webhook
  1689. // token : The auth token for the webhook
  1690. // messageID : The ID of a message to edit
  1691. func (s *Session) WebhookMessageDelete(webhookID, token, messageID string) (err error) {
  1692. uri := EndpointWebhookMessage(webhookID, token, messageID)
  1693. _, err = s.RequestWithBucketID("DELETE", uri, nil, EndpointWebhookToken("", ""))
  1694. return
  1695. }
  1696. // MessageReactionAdd creates an emoji reaction to a message.
  1697. // channelID : The channel ID.
  1698. // messageID : The message ID.
  1699. // emojiID : Either the unicode emoji for the reaction, or a guild emoji identifier.
  1700. func (s *Session) MessageReactionAdd(channelID, messageID, emojiID string) error {
  1701. // emoji such as #⃣ need to have # escaped
  1702. emojiID = strings.Replace(emojiID, "#", "%23", -1)
  1703. _, err := s.RequestWithBucketID("PUT", EndpointMessageReaction(channelID, messageID, emojiID, "@me"), nil, EndpointMessageReaction(channelID, "", "", ""))
  1704. return err
  1705. }
  1706. // MessageReactionRemove deletes an emoji reaction to a message.
  1707. // channelID : The channel ID.
  1708. // messageID : The message ID.
  1709. // emojiID : Either the unicode emoji for the reaction, or a guild emoji identifier.
  1710. // userID : @me or ID of the user to delete the reaction for.
  1711. func (s *Session) MessageReactionRemove(channelID, messageID, emojiID, userID string) error {
  1712. // emoji such as #⃣ need to have # escaped
  1713. emojiID = strings.Replace(emojiID, "#", "%23", -1)
  1714. _, err := s.RequestWithBucketID("DELETE", EndpointMessageReaction(channelID, messageID, emojiID, userID), nil, EndpointMessageReaction(channelID, "", "", ""))
  1715. return err
  1716. }
  1717. // MessageReactionsRemoveAll deletes all reactions from a message
  1718. // channelID : The channel ID
  1719. // messageID : The message ID.
  1720. func (s *Session) MessageReactionsRemoveAll(channelID, messageID string) error {
  1721. _, err := s.RequestWithBucketID("DELETE", EndpointMessageReactionsAll(channelID, messageID), nil, EndpointMessageReactionsAll(channelID, messageID))
  1722. return err
  1723. }
  1724. // MessageReactionsRemoveEmoji deletes all reactions of a certain emoji from a message
  1725. // channelID : The channel ID
  1726. // messageID : The message ID
  1727. // emojiID : The emoji ID
  1728. func (s *Session) MessageReactionsRemoveEmoji(channelID, messageID, emojiID string) error {
  1729. // emoji such as #⃣ need to have # escaped
  1730. emojiID = strings.Replace(emojiID, "#", "%23", -1)
  1731. _, err := s.RequestWithBucketID("DELETE", EndpointMessageReactions(channelID, messageID, emojiID), nil, EndpointMessageReactions(channelID, messageID, emojiID))
  1732. return err
  1733. }
  1734. // MessageReactions gets all the users reactions for a specific emoji.
  1735. // channelID : The channel ID.
  1736. // messageID : The message ID.
  1737. // emojiID : Either the unicode emoji for the reaction, or a guild emoji identifier.
  1738. // limit : max number of users to return (max 100)
  1739. // beforeID : If provided all reactions returned will be before given ID.
  1740. // afterID : If provided all reactions returned will be after given ID.
  1741. func (s *Session) MessageReactions(channelID, messageID, emojiID string, limit int, beforeID, afterID string) (st []*User, err error) {
  1742. // emoji such as #⃣ need to have # escaped
  1743. emojiID = strings.Replace(emojiID, "#", "%23", -1)
  1744. uri := EndpointMessageReactions(channelID, messageID, emojiID)
  1745. v := url.Values{}
  1746. if limit > 0 {
  1747. v.Set("limit", strconv.Itoa(limit))
  1748. }
  1749. if afterID != "" {
  1750. v.Set("after", afterID)
  1751. }
  1752. if beforeID != "" {
  1753. v.Set("before", beforeID)
  1754. }
  1755. if len(v) > 0 {
  1756. uri += "?" + v.Encode()
  1757. }
  1758. body, err := s.RequestWithBucketID("GET", uri, nil, EndpointMessageReaction(channelID, "", "", ""))
  1759. if err != nil {
  1760. return
  1761. }
  1762. err = unmarshal(body, &st)
  1763. return
  1764. }
  1765. // ------------------------------------------------------------------------------------------------
  1766. // Functions specific to application (slash) commands
  1767. // ------------------------------------------------------------------------------------------------
  1768. // ApplicationCommandCreate creates a global application command and returns it.
  1769. // appID : The application ID.
  1770. // guildID : Guild ID to create guild-specific application command. If empty - creates global application command.
  1771. // cmd : New application command data.
  1772. func (s *Session) ApplicationCommandCreate(appID string, guildID string, cmd *ApplicationCommand) (ccmd *ApplicationCommand, err error) {
  1773. endpoint := EndpointApplicationGlobalCommands(appID)
  1774. if guildID != "" {
  1775. endpoint = EndpointApplicationGuildCommands(appID, guildID)
  1776. }
  1777. body, err := s.RequestWithBucketID("POST", endpoint, *cmd, endpoint)
  1778. if err != nil {
  1779. return
  1780. }
  1781. err = unmarshal(body, &ccmd)
  1782. return
  1783. }
  1784. // ApplicationCommandEdit edits application command and returns new command data.
  1785. // appID : The application ID.
  1786. // cmdID : Application command ID to edit.
  1787. // guildID : Guild ID to edit guild-specific application command. If empty - edits global application command.
  1788. // cmd : Updated application command data.
  1789. func (s *Session) ApplicationCommandEdit(appID, guildID, cmdID string, cmd *ApplicationCommand) (updated *ApplicationCommand, err error) {
  1790. endpoint := EndpointApplicationGlobalCommand(appID, cmdID)
  1791. if guildID != "" {
  1792. endpoint = EndpointApplicationGuildCommand(appID, guildID, cmdID)
  1793. }
  1794. body, err := s.RequestWithBucketID("PATCH", endpoint, *cmd, endpoint)
  1795. if err != nil {
  1796. return
  1797. }
  1798. err = unmarshal(body, &updated)
  1799. return
  1800. }
  1801. // ApplicationCommandBulkOverwrite Creates commands overwriting existing commands. Returns a list of commands.
  1802. // appID : The application ID.
  1803. // commands : The commands to create.
  1804. func (s *Session) ApplicationCommandBulkOverwrite(appID string, guildID string, commands []*ApplicationCommand) (createdCommands []*ApplicationCommand, err error) {
  1805. endpoint := EndpointApplicationGlobalCommands(appID)
  1806. if guildID != "" {
  1807. endpoint = EndpointApplicationGuildCommands(appID, guildID)
  1808. }
  1809. body, err := s.RequestWithBucketID("PUT", endpoint, commands, endpoint)
  1810. if err != nil {
  1811. return
  1812. }
  1813. err = unmarshal(body, &createdCommands)
  1814. return
  1815. }
  1816. // ApplicationCommandDelete deletes application command by ID.
  1817. // appID : The application ID.
  1818. // cmdID : Application command ID to delete.
  1819. // guildID : Guild ID to delete guild-specific application command. If empty - deletes global application command.
  1820. func (s *Session) ApplicationCommandDelete(appID, guildID, cmdID string) error {
  1821. endpoint := EndpointApplicationGlobalCommand(appID, cmdID)
  1822. if guildID != "" {
  1823. endpoint = EndpointApplicationGuildCommand(appID, guildID, cmdID)
  1824. }
  1825. _, err := s.RequestWithBucketID("DELETE", endpoint, nil, endpoint)
  1826. return err
  1827. }
  1828. // ApplicationCommand retrieves an application command by given ID.
  1829. // appID : The application ID.
  1830. // cmdID : Application command ID.
  1831. // guildID : Guild ID to retrieve guild-specific application command. If empty - retrieves global application command.
  1832. func (s *Session) ApplicationCommand(appID, guildID, cmdID string) (cmd *ApplicationCommand, err error) {
  1833. endpoint := EndpointApplicationGlobalCommand(appID, cmdID)
  1834. if guildID != "" {
  1835. endpoint = EndpointApplicationGuildCommand(appID, guildID, cmdID)
  1836. }
  1837. body, err := s.RequestWithBucketID("GET", endpoint, nil, endpoint)
  1838. if err != nil {
  1839. return
  1840. }
  1841. err = unmarshal(body, &cmd)
  1842. return
  1843. }
  1844. // ApplicationCommands retrieves all commands in application.
  1845. // appID : The application ID.
  1846. // guildID : Guild ID to retrieve all guild-specific application commands. If empty - retrieves global application commands.
  1847. func (s *Session) ApplicationCommands(appID, guildID string) (cmd []*ApplicationCommand, err error) {
  1848. endpoint := EndpointApplicationGlobalCommands(appID)
  1849. if guildID != "" {
  1850. endpoint = EndpointApplicationGuildCommands(appID, guildID)
  1851. }
  1852. body, err := s.RequestWithBucketID("GET", endpoint, nil, endpoint)
  1853. if err != nil {
  1854. return
  1855. }
  1856. err = unmarshal(body, &cmd)
  1857. return
  1858. }
  1859. // InteractionRespond creates the response to an interaction.
  1860. // appID : The application ID.
  1861. // interaction : Interaction instance.
  1862. // resp : Response message data.
  1863. func (s *Session) InteractionRespond(interaction *Interaction, resp *InteractionResponse) (err error) {
  1864. endpoint := EndpointInteractionResponse(interaction.ID, interaction.Token)
  1865. if resp.Data != nil && len(resp.Data.Files) > 0 {
  1866. contentType, body, err := MultipartBodyWithJSON(resp, resp.Data.Files)
  1867. if err != nil {
  1868. return err
  1869. }
  1870. _, err = s.request("POST", endpoint, contentType, body, endpoint, 0)
  1871. } else {
  1872. _, err = s.RequestWithBucketID("POST", endpoint, *resp, endpoint)
  1873. }
  1874. return err
  1875. }
  1876. // InteractionResponse gets the response to an interaction.
  1877. // appID : The application ID.
  1878. // interaction : Interaction instance.
  1879. func (s *Session) InteractionResponse(appID string, interaction *Interaction) (*Message, error) {
  1880. return s.WebhookMessage(appID, interaction.Token, "@original")
  1881. }
  1882. // InteractionResponseEdit edits the response to an interaction.
  1883. // appID : The application ID.
  1884. // interaction : Interaction instance.
  1885. // newresp : Updated response message data.
  1886. func (s *Session) InteractionResponseEdit(appID string, interaction *Interaction, newresp *WebhookEdit) (*Message, error) {
  1887. return s.WebhookMessageEdit(appID, interaction.Token, "@original", newresp)
  1888. }
  1889. // InteractionResponseDelete deletes the response to an interaction.
  1890. // appID : The application ID.
  1891. // interaction : Interaction instance.
  1892. func (s *Session) InteractionResponseDelete(appID string, interaction *Interaction) error {
  1893. endpoint := EndpointInteractionResponseActions(appID, interaction.Token)
  1894. _, err := s.RequestWithBucketID("DELETE", endpoint, nil, endpoint)
  1895. return err
  1896. }
  1897. // FollowupMessageCreate creates the followup message for an interaction.
  1898. // appID : The application ID.
  1899. // interaction : Interaction instance.
  1900. // wait : Waits for server confirmation of message send and ensures that the return struct is populated (it is nil otherwise)
  1901. // data : Data of the message to send.
  1902. func (s *Session) FollowupMessageCreate(appID string, interaction *Interaction, wait bool, data *WebhookParams) (*Message, error) {
  1903. return s.WebhookExecute(appID, interaction.Token, wait, data)
  1904. }
  1905. // FollowupMessageEdit edits a followup message of an interaction.
  1906. // appID : The application ID.
  1907. // interaction : Interaction instance.
  1908. // messageID : The followup message ID.
  1909. // data : Data to update the message
  1910. func (s *Session) FollowupMessageEdit(appID string, interaction *Interaction, messageID string, data *WebhookEdit) (*Message, error) {
  1911. return s.WebhookMessageEdit(appID, interaction.Token, messageID, data)
  1912. }
  1913. // FollowupMessageDelete deletes a followup message of an interaction.
  1914. // appID : The application ID.
  1915. // interaction : Interaction instance.
  1916. // messageID : The followup message ID.
  1917. func (s *Session) FollowupMessageDelete(appID string, interaction *Interaction, messageID string) error {
  1918. return s.WebhookMessageDelete(appID, interaction.Token, messageID)
  1919. }