restapi.go 66 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240
  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. "mime/multipart"
  21. "net/http"
  22. "net/textproto"
  23. "net/url"
  24. "strconv"
  25. "strings"
  26. "time"
  27. )
  28. // All error constants
  29. var (
  30. ErrJSONUnmarshal = errors.New("json unmarshal")
  31. ErrStatusOffline = errors.New("You can't set your Status to offline")
  32. ErrVerificationLevelBounds = errors.New("VerificationLevel out of bounds, should be between 0 and 3")
  33. ErrPruneDaysBounds = errors.New("the number of days should be more than or equal to 1")
  34. ErrGuildNoIcon = errors.New("guild does not have an icon set")
  35. ErrGuildNoSplash = errors.New("guild does not have a splash set")
  36. 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")
  37. )
  38. // Request is the same as RequestWithBucketID but the bucket id is the same as the urlStr
  39. func (s *Session) Request(method, urlStr string, data interface{}) (response []byte, err error) {
  40. return s.RequestWithBucketID(method, urlStr, data, strings.SplitN(urlStr, "?", 2)[0])
  41. }
  42. // RequestWithBucketID makes a (GET/POST/...) Requests to Discord REST API with JSON data.
  43. func (s *Session) RequestWithBucketID(method, urlStr string, data interface{}, bucketID string) (response []byte, err error) {
  44. var body []byte
  45. if data != nil {
  46. body, err = json.Marshal(data)
  47. if err != nil {
  48. return
  49. }
  50. }
  51. return s.request(method, urlStr, "application/json", body, bucketID, 0)
  52. }
  53. // request makes a (GET/POST/...) Requests to Discord REST API.
  54. // Sequence is the sequence number, if it fails with a 502 it will
  55. // retry with sequence+1 until it either succeeds or sequence >= session.MaxRestRetries
  56. func (s *Session) request(method, urlStr, contentType string, b []byte, bucketID string, sequence int) (response []byte, err error) {
  57. if bucketID == "" {
  58. bucketID = strings.SplitN(urlStr, "?", 2)[0]
  59. }
  60. return s.RequestWithLockedBucket(method, urlStr, contentType, b, s.Ratelimiter.LockBucket(bucketID), sequence)
  61. }
  62. // RequestWithLockedBucket makes a request using a bucket that's already been locked
  63. func (s *Session) RequestWithLockedBucket(method, urlStr, contentType string, b []byte, bucket *Bucket, sequence int) (response []byte, err error) {
  64. if s.Debug {
  65. log.Printf("API REQUEST %8s :: %s\n", method, urlStr)
  66. log.Printf("API REQUEST PAYLOAD :: [%s]\n", string(b))
  67. }
  68. req, err := http.NewRequest(method, urlStr, bytes.NewBuffer(b))
  69. if err != nil {
  70. bucket.Release(nil)
  71. return
  72. }
  73. // Not used on initial login..
  74. // TODO: Verify if a login, otherwise complain about no-token
  75. if s.Token != "" {
  76. req.Header.Set("authorization", s.Token)
  77. }
  78. // Discord's API returns a 400 Bad Request is Content-Type is set, but the
  79. // request body is empty.
  80. if b != nil {
  81. req.Header.Set("Content-Type", contentType)
  82. }
  83. // TODO: Make a configurable static variable.
  84. req.Header.Set("User-Agent", s.UserAgent)
  85. if s.Debug {
  86. for k, v := range req.Header {
  87. log.Printf("API REQUEST HEADER :: [%s] = %+v\n", k, v)
  88. }
  89. }
  90. resp, err := s.Client.Do(req)
  91. if err != nil {
  92. bucket.Release(nil)
  93. return
  94. }
  95. defer func() {
  96. err2 := resp.Body.Close()
  97. if err2 != nil {
  98. log.Println("error closing resp body")
  99. }
  100. }()
  101. err = bucket.Release(resp.Header)
  102. if err != nil {
  103. return
  104. }
  105. response, err = ioutil.ReadAll(resp.Body)
  106. if err != nil {
  107. return
  108. }
  109. if s.Debug {
  110. log.Printf("API RESPONSE STATUS :: %s\n", resp.Status)
  111. for k, v := range resp.Header {
  112. log.Printf("API RESPONSE HEADER :: [%s] = %+v\n", k, v)
  113. }
  114. log.Printf("API RESPONSE BODY :: [%s]\n\n\n", response)
  115. }
  116. switch resp.StatusCode {
  117. case http.StatusOK:
  118. case http.StatusCreated:
  119. case http.StatusNoContent:
  120. case http.StatusBadGateway:
  121. // Retry sending request if possible
  122. if sequence < s.MaxRestRetries {
  123. s.log(LogInformational, "%s Failed (%s), Retrying...", urlStr, resp.Status)
  124. response, err = s.RequestWithLockedBucket(method, urlStr, contentType, b, s.Ratelimiter.LockBucketObject(bucket), sequence+1)
  125. } else {
  126. err = fmt.Errorf("Exceeded Max retries HTTP %s, %s", resp.Status, response)
  127. }
  128. case 429: // TOO MANY REQUESTS - Rate limiting
  129. rl := TooManyRequests{}
  130. err = json.Unmarshal(response, &rl)
  131. if err != nil {
  132. s.log(LogError, "rate limit unmarshal error, %s", err)
  133. return
  134. }
  135. s.log(LogInformational, "Rate Limiting %s, retry in %d", urlStr, rl.RetryAfter)
  136. s.handleEvent(rateLimitEventType, RateLimit{TooManyRequests: &rl, URL: urlStr})
  137. time.Sleep(rl.RetryAfter * time.Millisecond)
  138. // we can make the above smarter
  139. // this method can cause longer delays than required
  140. response, err = s.RequestWithLockedBucket(method, urlStr, contentType, b, s.Ratelimiter.LockBucketObject(bucket), sequence)
  141. case http.StatusUnauthorized:
  142. if strings.Index(s.Token, "Bot ") != 0 {
  143. s.log(LogInformational, ErrUnauthorized.Error())
  144. err = ErrUnauthorized
  145. }
  146. fallthrough
  147. default: // Error condition
  148. err = newRestError(req, resp, response)
  149. }
  150. return
  151. }
  152. func unmarshal(data []byte, v interface{}) error {
  153. err := json.Unmarshal(data, v)
  154. if err != nil {
  155. return ErrJSONUnmarshal
  156. }
  157. return nil
  158. }
  159. // ------------------------------------------------------------------------------------------------
  160. // Functions specific to Discord Sessions
  161. // ------------------------------------------------------------------------------------------------
  162. // Login asks the Discord server for an authentication token.
  163. //
  164. // NOTE: While email/pass authentication is supported by DiscordGo it is
  165. // HIGHLY DISCOURAGED by Discord. Please only use email/pass to obtain a token
  166. // and then use that authentication token for all future connections.
  167. // Also, doing any form of automation with a user (non Bot) account may result
  168. // in that account being permanently banned from Discord.
  169. func (s *Session) Login(email, password string) (err error) {
  170. data := struct {
  171. Email string `json:"email"`
  172. Password string `json:"password"`
  173. }{email, password}
  174. response, err := s.RequestWithBucketID("POST", EndpointLogin, data, EndpointLogin)
  175. if err != nil {
  176. return
  177. }
  178. temp := struct {
  179. Token string `json:"token"`
  180. MFA bool `json:"mfa"`
  181. }{}
  182. err = unmarshal(response, &temp)
  183. if err != nil {
  184. return
  185. }
  186. s.Token = temp.Token
  187. s.MFA = temp.MFA
  188. return
  189. }
  190. // Register sends a Register request to Discord, and returns the authentication token
  191. // Note that this account is temporary and should be verified for future use.
  192. // Another option is to save the authentication token external, but this isn't recommended.
  193. func (s *Session) Register(username string) (token string, err error) {
  194. data := struct {
  195. Username string `json:"username"`
  196. }{username}
  197. response, err := s.RequestWithBucketID("POST", EndpointRegister, data, EndpointRegister)
  198. if err != nil {
  199. return
  200. }
  201. temp := struct {
  202. Token string `json:"token"`
  203. }{}
  204. err = unmarshal(response, &temp)
  205. if err != nil {
  206. return
  207. }
  208. token = temp.Token
  209. return
  210. }
  211. // Logout sends a logout request to Discord.
  212. // This does not seem to actually invalidate the token. So you can still
  213. // make API calls even after a Logout. So, it seems almost pointless to
  214. // even use.
  215. func (s *Session) Logout() (err error) {
  216. // _, err = s.Request("POST", LOGOUT, `{"token": "` + s.Token + `"}`)
  217. if s.Token == "" {
  218. return
  219. }
  220. data := struct {
  221. Token string `json:"token"`
  222. }{s.Token}
  223. _, err = s.RequestWithBucketID("POST", EndpointLogout, data, EndpointLogout)
  224. return
  225. }
  226. // ------------------------------------------------------------------------------------------------
  227. // Functions specific to Discord Users
  228. // ------------------------------------------------------------------------------------------------
  229. // User returns the user details of the given userID
  230. // userID : A user ID or "@me" which is a shortcut of current user ID
  231. func (s *Session) User(userID string) (st *User, err error) {
  232. body, err := s.RequestWithBucketID("GET", EndpointUser(userID), nil, EndpointUsers)
  233. if err != nil {
  234. return
  235. }
  236. err = unmarshal(body, &st)
  237. return
  238. }
  239. // UserAvatar is deprecated. Please use UserAvatarDecode
  240. // userID : A user ID or "@me" which is a shortcut of current user ID
  241. func (s *Session) UserAvatar(userID string) (img image.Image, err error) {
  242. u, err := s.User(userID)
  243. if err != nil {
  244. return
  245. }
  246. img, err = s.UserAvatarDecode(u)
  247. return
  248. }
  249. // UserAvatarDecode returns an image.Image of a user's Avatar
  250. // user : The user which avatar should be retrieved
  251. func (s *Session) UserAvatarDecode(u *User) (img image.Image, err error) {
  252. body, err := s.RequestWithBucketID("GET", EndpointUserAvatar(u.ID, u.Avatar), nil, EndpointUserAvatar("", ""))
  253. if err != nil {
  254. return
  255. }
  256. img, _, err = image.Decode(bytes.NewReader(body))
  257. return
  258. }
  259. // UserUpdate updates a users settings.
  260. func (s *Session) UserUpdate(email, password, username, avatar, newPassword string) (st *User, err error) {
  261. // NOTE: Avatar must be either the hash/id of existing Avatar or
  262. // data:image/png;base64,BASE64_STRING_OF_NEW_AVATAR_PNG
  263. // to set a new avatar.
  264. // If left blank, avatar will be set to null/blank
  265. data := struct {
  266. Email string `json:"email,omitempty"`
  267. Password string `json:"password,omitempty"`
  268. Username string `json:"username,omitempty"`
  269. Avatar string `json:"avatar,omitempty"`
  270. NewPassword string `json:"new_password,omitempty"`
  271. }{email, password, username, avatar, newPassword}
  272. body, err := s.RequestWithBucketID("PATCH", EndpointUser("@me"), data, EndpointUsers)
  273. if err != nil {
  274. return
  275. }
  276. err = unmarshal(body, &st)
  277. return
  278. }
  279. // UserSettings returns the settings for a given user
  280. func (s *Session) UserSettings() (st *Settings, err error) {
  281. body, err := s.RequestWithBucketID("GET", EndpointUserSettings("@me"), nil, EndpointUserSettings(""))
  282. if err != nil {
  283. return
  284. }
  285. err = unmarshal(body, &st)
  286. return
  287. }
  288. // UserUpdateStatus update the user status
  289. // status : The new status (Actual valid status are 'online','idle','dnd','invisible')
  290. func (s *Session) UserUpdateStatus(status Status) (st *Settings, err error) {
  291. if status == StatusOffline {
  292. err = ErrStatusOffline
  293. return
  294. }
  295. data := struct {
  296. Status Status `json:"status"`
  297. }{status}
  298. body, err := s.RequestWithBucketID("PATCH", EndpointUserSettings("@me"), data, EndpointUserSettings(""))
  299. if err != nil {
  300. return
  301. }
  302. err = unmarshal(body, &st)
  303. return
  304. }
  305. // UserConnections returns the user's connections
  306. func (s *Session) UserConnections() (conn []*UserConnection, err error) {
  307. response, err := s.RequestWithBucketID("GET", EndpointUserConnections("@me"), nil, EndpointUserConnections("@me"))
  308. if err != nil {
  309. return nil, err
  310. }
  311. err = unmarshal(response, &conn)
  312. if err != nil {
  313. return
  314. }
  315. return
  316. }
  317. // UserChannels returns an array of Channel structures for all private
  318. // channels.
  319. func (s *Session) UserChannels() (st []*Channel, err error) {
  320. body, err := s.RequestWithBucketID("GET", EndpointUserChannels("@me"), nil, EndpointUserChannels(""))
  321. if err != nil {
  322. return
  323. }
  324. err = unmarshal(body, &st)
  325. return
  326. }
  327. // UserChannelCreate creates a new User (Private) Channel with another User
  328. // recipientID : A user ID for the user to which this channel is opened with.
  329. func (s *Session) UserChannelCreate(recipientID string) (st *Channel, err error) {
  330. data := struct {
  331. RecipientID string `json:"recipient_id"`
  332. }{recipientID}
  333. body, err := s.RequestWithBucketID("POST", EndpointUserChannels("@me"), data, EndpointUserChannels(""))
  334. if err != nil {
  335. return
  336. }
  337. err = unmarshal(body, &st)
  338. return
  339. }
  340. // UserGuilds returns an array of UserGuild structures for all guilds.
  341. // limit : The number guilds that can be returned. (max 100)
  342. // beforeID : If provided all guilds returned will be before given ID.
  343. // afterID : If provided all guilds returned will be after given ID.
  344. func (s *Session) UserGuilds(limit int, beforeID, afterID string) (st []*UserGuild, err error) {
  345. v := url.Values{}
  346. if limit > 0 {
  347. v.Set("limit", strconv.Itoa(limit))
  348. }
  349. if afterID != "" {
  350. v.Set("after", afterID)
  351. }
  352. if beforeID != "" {
  353. v.Set("before", beforeID)
  354. }
  355. uri := EndpointUserGuilds("@me")
  356. if len(v) > 0 {
  357. uri += "?" + v.Encode()
  358. }
  359. body, err := s.RequestWithBucketID("GET", uri, nil, EndpointUserGuilds(""))
  360. if err != nil {
  361. return
  362. }
  363. err = unmarshal(body, &st)
  364. return
  365. }
  366. // UserGuildSettingsEdit Edits the users notification settings for a guild
  367. // guildID : The ID of the guild to edit the settings on
  368. // settings : The settings to update
  369. func (s *Session) UserGuildSettingsEdit(guildID string, settings *UserGuildSettingsEdit) (st *UserGuildSettings, err error) {
  370. body, err := s.RequestWithBucketID("PATCH", EndpointUserGuildSettings("@me", guildID), settings, EndpointUserGuildSettings("", guildID))
  371. if err != nil {
  372. return
  373. }
  374. err = unmarshal(body, &st)
  375. return
  376. }
  377. // UserChannelPermissions returns the permission of a user in a channel.
  378. // userID : The ID of the user to calculate permissions for.
  379. // channelID : The ID of the channel to calculate permission for.
  380. //
  381. // NOTE: This function is now deprecated and will be removed in the future.
  382. // Please see the same function inside state.go
  383. func (s *Session) UserChannelPermissions(userID, channelID string) (apermissions int, err error) {
  384. // Try to just get permissions from state.
  385. apermissions, err = s.State.UserChannelPermissions(userID, channelID)
  386. if err == nil {
  387. return
  388. }
  389. // Otherwise try get as much data from state as possible, falling back to the network.
  390. channel, err := s.State.Channel(channelID)
  391. if err != nil || channel == nil {
  392. channel, err = s.Channel(channelID)
  393. if err != nil {
  394. return
  395. }
  396. }
  397. guild, err := s.State.Guild(channel.GuildID)
  398. if err != nil || guild == nil {
  399. guild, err = s.Guild(channel.GuildID)
  400. if err != nil {
  401. return
  402. }
  403. }
  404. if userID == guild.OwnerID {
  405. apermissions = PermissionAll
  406. return
  407. }
  408. member, err := s.State.Member(guild.ID, userID)
  409. if err != nil || member == nil {
  410. member, err = s.GuildMember(guild.ID, userID)
  411. if err != nil {
  412. return
  413. }
  414. }
  415. return memberPermissions(guild, channel, member), nil
  416. }
  417. // Calculates the permissions for a member.
  418. // https://support.discord.com/hc/en-us/articles/206141927-How-is-the-permission-hierarchy-structured-
  419. func memberPermissions(guild *Guild, channel *Channel, member *Member) (apermissions int) {
  420. userID := member.User.ID
  421. if userID == guild.OwnerID {
  422. apermissions = PermissionAll
  423. return
  424. }
  425. for _, role := range guild.Roles {
  426. if role.ID == guild.ID {
  427. apermissions |= role.Permissions
  428. break
  429. }
  430. }
  431. for _, role := range guild.Roles {
  432. for _, roleID := range member.Roles {
  433. if role.ID == roleID {
  434. apermissions |= role.Permissions
  435. break
  436. }
  437. }
  438. }
  439. if apermissions&PermissionAdministrator == PermissionAdministrator {
  440. apermissions |= PermissionAll
  441. }
  442. // Apply @everyone overrides from the channel.
  443. for _, overwrite := range channel.PermissionOverwrites {
  444. if guild.ID == overwrite.ID {
  445. apermissions &= ^overwrite.Deny
  446. apermissions |= overwrite.Allow
  447. break
  448. }
  449. }
  450. denies := 0
  451. allows := 0
  452. // Member overwrites can override role overrides, so do two passes
  453. for _, overwrite := range channel.PermissionOverwrites {
  454. for _, roleID := range member.Roles {
  455. if overwrite.Type == "role" && roleID == overwrite.ID {
  456. denies |= overwrite.Deny
  457. allows |= overwrite.Allow
  458. break
  459. }
  460. }
  461. }
  462. apermissions &= ^denies
  463. apermissions |= allows
  464. for _, overwrite := range channel.PermissionOverwrites {
  465. if overwrite.Type == "member" && overwrite.ID == userID {
  466. apermissions &= ^overwrite.Deny
  467. apermissions |= overwrite.Allow
  468. break
  469. }
  470. }
  471. if apermissions&PermissionAdministrator == PermissionAdministrator {
  472. apermissions |= PermissionAllChannel
  473. }
  474. return apermissions
  475. }
  476. // ------------------------------------------------------------------------------------------------
  477. // Functions specific to Discord Guilds
  478. // ------------------------------------------------------------------------------------------------
  479. // Guild returns a Guild structure of a specific Guild.
  480. // guildID : The ID of a Guild
  481. func (s *Session) Guild(guildID string) (st *Guild, err error) {
  482. body, err := s.RequestWithBucketID("GET", EndpointGuild(guildID), nil, EndpointGuild(guildID))
  483. if err != nil {
  484. return
  485. }
  486. err = unmarshal(body, &st)
  487. return
  488. }
  489. // GuildCreate creates a new Guild
  490. // name : A name for the Guild (2-100 characters)
  491. func (s *Session) GuildCreate(name string) (st *Guild, err error) {
  492. data := struct {
  493. Name string `json:"name"`
  494. }{name}
  495. body, err := s.RequestWithBucketID("POST", EndpointGuildCreate, data, EndpointGuildCreate)
  496. if err != nil {
  497. return
  498. }
  499. err = unmarshal(body, &st)
  500. return
  501. }
  502. // GuildEdit edits a new Guild
  503. // guildID : The ID of a Guild
  504. // g : A GuildParams struct with the values Name, Region and VerificationLevel defined.
  505. func (s *Session) GuildEdit(guildID string, g GuildParams) (st *Guild, err error) {
  506. // Bounds checking for VerificationLevel, interval: [0, 4]
  507. if g.VerificationLevel != nil {
  508. val := *g.VerificationLevel
  509. if val < 0 || val > 4 {
  510. err = ErrVerificationLevelBounds
  511. return
  512. }
  513. }
  514. //Bounds checking for regions
  515. if g.Region != "" {
  516. isValid := false
  517. regions, _ := s.VoiceRegions()
  518. for _, r := range regions {
  519. if g.Region == r.ID {
  520. isValid = true
  521. }
  522. }
  523. if !isValid {
  524. var valid []string
  525. for _, r := range regions {
  526. valid = append(valid, r.ID)
  527. }
  528. err = fmt.Errorf("Region not a valid region (%q)", valid)
  529. return
  530. }
  531. }
  532. body, err := s.RequestWithBucketID("PATCH", EndpointGuild(guildID), g, EndpointGuild(guildID))
  533. if err != nil {
  534. return
  535. }
  536. err = unmarshal(body, &st)
  537. return
  538. }
  539. // GuildDelete deletes a Guild.
  540. // guildID : The ID of a Guild
  541. func (s *Session) GuildDelete(guildID string) (st *Guild, err error) {
  542. body, err := s.RequestWithBucketID("DELETE", EndpointGuild(guildID), nil, EndpointGuild(guildID))
  543. if err != nil {
  544. return
  545. }
  546. err = unmarshal(body, &st)
  547. return
  548. }
  549. // GuildLeave leaves a Guild.
  550. // guildID : The ID of a Guild
  551. func (s *Session) GuildLeave(guildID string) (err error) {
  552. _, err = s.RequestWithBucketID("DELETE", EndpointUserGuild("@me", guildID), nil, EndpointUserGuild("", guildID))
  553. return
  554. }
  555. // GuildBans returns an array of GuildBan structures for all bans of a
  556. // given guild.
  557. // guildID : The ID of a Guild.
  558. func (s *Session) GuildBans(guildID string) (st []*GuildBan, err error) {
  559. body, err := s.RequestWithBucketID("GET", EndpointGuildBans(guildID), nil, EndpointGuildBans(guildID))
  560. if err != nil {
  561. return
  562. }
  563. err = unmarshal(body, &st)
  564. return
  565. }
  566. // GuildBanCreate bans the given user from the given guild.
  567. // guildID : The ID of a Guild.
  568. // userID : The ID of a User
  569. // days : The number of days of previous comments to delete.
  570. func (s *Session) GuildBanCreate(guildID, userID string, days int) (err error) {
  571. return s.GuildBanCreateWithReason(guildID, userID, "", days)
  572. }
  573. // GuildBanCreateWithReason bans the given user from the given guild also providing a reaso.
  574. // guildID : The ID of a Guild.
  575. // userID : The ID of a User
  576. // reason : The reason for this ban
  577. // days : The number of days of previous comments to delete.
  578. func (s *Session) GuildBanCreateWithReason(guildID, userID, reason string, days int) (err error) {
  579. uri := EndpointGuildBan(guildID, userID)
  580. queryParams := url.Values{}
  581. if days > 0 {
  582. queryParams.Set("delete-message-days", strconv.Itoa(days))
  583. }
  584. if reason != "" {
  585. queryParams.Set("reason", reason)
  586. }
  587. if len(queryParams) > 0 {
  588. uri += "?" + queryParams.Encode()
  589. }
  590. _, err = s.RequestWithBucketID("PUT", uri, nil, EndpointGuildBan(guildID, ""))
  591. return
  592. }
  593. // GuildBanDelete removes the given user from the guild bans
  594. // guildID : The ID of a Guild.
  595. // userID : The ID of a User
  596. func (s *Session) GuildBanDelete(guildID, userID string) (err error) {
  597. _, err = s.RequestWithBucketID("DELETE", EndpointGuildBan(guildID, userID), nil, EndpointGuildBan(guildID, ""))
  598. return
  599. }
  600. // GuildMembers returns a list of members for a guild.
  601. // guildID : The ID of a Guild.
  602. // after : The id of the member to return members after
  603. // limit : max number of members to return (max 1000)
  604. func (s *Session) GuildMembers(guildID string, after string, limit int) (st []*Member, err error) {
  605. uri := EndpointGuildMembers(guildID)
  606. v := url.Values{}
  607. if after != "" {
  608. v.Set("after", after)
  609. }
  610. if limit > 0 {
  611. v.Set("limit", strconv.Itoa(limit))
  612. }
  613. if len(v) > 0 {
  614. uri += "?" + v.Encode()
  615. }
  616. body, err := s.RequestWithBucketID("GET", uri, nil, EndpointGuildMembers(guildID))
  617. if err != nil {
  618. return
  619. }
  620. err = unmarshal(body, &st)
  621. return
  622. }
  623. // GuildMember returns a member of a guild.
  624. // guildID : The ID of a Guild.
  625. // userID : The ID of a User
  626. func (s *Session) GuildMember(guildID, userID string) (st *Member, err error) {
  627. body, err := s.RequestWithBucketID("GET", EndpointGuildMember(guildID, userID), nil, EndpointGuildMember(guildID, ""))
  628. if err != nil {
  629. return
  630. }
  631. err = unmarshal(body, &st)
  632. return
  633. }
  634. // GuildMemberAdd force joins a user to the guild.
  635. // accessToken : Valid access_token for the user.
  636. // guildID : The ID of a Guild.
  637. // userID : The ID of a User.
  638. // nick : Value to set users nickname to
  639. // roles : A list of role ID's to set on the member.
  640. // mute : If the user is muted.
  641. // deaf : If the user is deafened.
  642. func (s *Session) GuildMemberAdd(accessToken, guildID, userID, nick string, roles []string, mute, deaf bool) (err error) {
  643. data := struct {
  644. AccessToken string `json:"access_token"`
  645. Nick string `json:"nick,omitempty"`
  646. Roles []string `json:"roles,omitempty"`
  647. Mute bool `json:"mute,omitempty"`
  648. Deaf bool `json:"deaf,omitempty"`
  649. }{accessToken, nick, roles, mute, deaf}
  650. _, err = s.RequestWithBucketID("PUT", EndpointGuildMember(guildID, userID), data, EndpointGuildMember(guildID, ""))
  651. if err != nil {
  652. return err
  653. }
  654. return err
  655. }
  656. // GuildMemberDelete removes the given user from the given guild.
  657. // guildID : The ID of a Guild.
  658. // userID : The ID of a User
  659. func (s *Session) GuildMemberDelete(guildID, userID string) (err error) {
  660. return s.GuildMemberDeleteWithReason(guildID, userID, "")
  661. }
  662. // GuildMemberDeleteWithReason removes the given user from the given guild.
  663. // guildID : The ID of a Guild.
  664. // userID : The ID of a User
  665. // reason : The reason for the kick
  666. func (s *Session) GuildMemberDeleteWithReason(guildID, userID, reason string) (err error) {
  667. uri := EndpointGuildMember(guildID, userID)
  668. if reason != "" {
  669. uri += "?reason=" + url.QueryEscape(reason)
  670. }
  671. _, err = s.RequestWithBucketID("DELETE", uri, nil, EndpointGuildMember(guildID, ""))
  672. return
  673. }
  674. // GuildMemberEdit edits the roles of a member.
  675. // guildID : The ID of a Guild.
  676. // userID : The ID of a User.
  677. // roles : A list of role ID's to set on the member.
  678. func (s *Session) GuildMemberEdit(guildID, userID string, roles []string) (err error) {
  679. data := struct {
  680. Roles []string `json:"roles"`
  681. }{roles}
  682. _, err = s.RequestWithBucketID("PATCH", EndpointGuildMember(guildID, userID), data, EndpointGuildMember(guildID, ""))
  683. if err != nil {
  684. return
  685. }
  686. return
  687. }
  688. // GuildMemberMove moves a guild member from one voice channel to another/none
  689. // guildID : The ID of a Guild.
  690. // userID : The ID of a User.
  691. // channelID : The ID of a channel to move user to, or null?
  692. // NOTE : I am not entirely set on the name of this function and it may change
  693. // prior to the final 1.0.0 release of Discordgo
  694. func (s *Session) GuildMemberMove(guildID, userID, channelID string) (err error) {
  695. data := struct {
  696. ChannelID string `json:"channel_id"`
  697. }{channelID}
  698. _, err = s.RequestWithBucketID("PATCH", EndpointGuildMember(guildID, userID), data, EndpointGuildMember(guildID, ""))
  699. if err != nil {
  700. return
  701. }
  702. return
  703. }
  704. // GuildMemberNickname updates the nickname of a guild member
  705. // guildID : The ID of a guild
  706. // userID : The ID of a user
  707. // userID : The ID of a user or "@me" which is a shortcut of the current user ID
  708. func (s *Session) GuildMemberNickname(guildID, userID, nickname string) (err error) {
  709. data := struct {
  710. Nick string `json:"nick"`
  711. }{nickname}
  712. if userID == "@me" {
  713. userID += "/nick"
  714. }
  715. _, err = s.RequestWithBucketID("PATCH", EndpointGuildMember(guildID, userID), data, EndpointGuildMember(guildID, ""))
  716. return
  717. }
  718. // GuildMemberRoleAdd adds the specified role to a given member
  719. // guildID : The ID of a Guild.
  720. // userID : The ID of a User.
  721. // roleID : The ID of a Role to be assigned to the user.
  722. func (s *Session) GuildMemberRoleAdd(guildID, userID, roleID string) (err error) {
  723. _, err = s.RequestWithBucketID("PUT", EndpointGuildMemberRole(guildID, userID, roleID), nil, EndpointGuildMemberRole(guildID, "", ""))
  724. return
  725. }
  726. // GuildMemberRoleRemove removes the specified role to a given member
  727. // guildID : The ID of a Guild.
  728. // userID : The ID of a User.
  729. // roleID : The ID of a Role to be removed from the user.
  730. func (s *Session) GuildMemberRoleRemove(guildID, userID, roleID string) (err error) {
  731. _, err = s.RequestWithBucketID("DELETE", EndpointGuildMemberRole(guildID, userID, roleID), nil, EndpointGuildMemberRole(guildID, "", ""))
  732. return
  733. }
  734. // GuildChannels returns an array of Channel structures for all channels of a
  735. // given guild.
  736. // guildID : The ID of a Guild.
  737. func (s *Session) GuildChannels(guildID string) (st []*Channel, err error) {
  738. body, err := s.request("GET", EndpointGuildChannels(guildID), "", nil, EndpointGuildChannels(guildID), 0)
  739. if err != nil {
  740. return
  741. }
  742. err = unmarshal(body, &st)
  743. return
  744. }
  745. // GuildChannelCreateData is provided to GuildChannelCreateComplex
  746. type GuildChannelCreateData struct {
  747. Name string `json:"name"`
  748. Type ChannelType `json:"type"`
  749. Topic string `json:"topic,omitempty"`
  750. Bitrate int `json:"bitrate,omitempty"`
  751. UserLimit int `json:"user_limit,omitempty"`
  752. RateLimitPerUser int `json:"rate_limit_per_user,omitempty"`
  753. Position int `json:"position,omitempty"`
  754. PermissionOverwrites []*PermissionOverwrite `json:"permission_overwrites,omitempty"`
  755. ParentID string `json:"parent_id,omitempty"`
  756. NSFW bool `json:"nsfw,omitempty"`
  757. }
  758. // GuildChannelCreateComplex creates a new channel in the given guild
  759. // guildID : The ID of a Guild
  760. // data : A data struct describing the new Channel, Name and Type are mandatory, other fields depending on the type
  761. func (s *Session) GuildChannelCreateComplex(guildID string, data GuildChannelCreateData) (st *Channel, err error) {
  762. body, err := s.RequestWithBucketID("POST", EndpointGuildChannels(guildID), data, EndpointGuildChannels(guildID))
  763. if err != nil {
  764. return
  765. }
  766. err = unmarshal(body, &st)
  767. return
  768. }
  769. // GuildChannelCreate creates a new channel in the given guild
  770. // guildID : The ID of a Guild.
  771. // name : Name of the channel (2-100 chars length)
  772. // ctype : Type of the channel
  773. func (s *Session) GuildChannelCreate(guildID, name string, ctype ChannelType) (st *Channel, err error) {
  774. return s.GuildChannelCreateComplex(guildID, GuildChannelCreateData{
  775. Name: name,
  776. Type: ctype,
  777. })
  778. }
  779. // GuildChannelsReorder updates the order of channels in a guild
  780. // guildID : The ID of a Guild.
  781. // channels : Updated channels.
  782. func (s *Session) GuildChannelsReorder(guildID string, channels []*Channel) (err error) {
  783. data := make([]struct {
  784. ID string `json:"id"`
  785. Position int `json:"position"`
  786. }, len(channels))
  787. for i, c := range channels {
  788. data[i].ID = c.ID
  789. data[i].Position = c.Position
  790. }
  791. _, err = s.RequestWithBucketID("PATCH", EndpointGuildChannels(guildID), data, EndpointGuildChannels(guildID))
  792. return
  793. }
  794. // GuildInvites returns an array of Invite structures for the given guild
  795. // guildID : The ID of a Guild.
  796. func (s *Session) GuildInvites(guildID string) (st []*Invite, err error) {
  797. body, err := s.RequestWithBucketID("GET", EndpointGuildInvites(guildID), nil, EndpointGuildInvites(guildID))
  798. if err != nil {
  799. return
  800. }
  801. err = unmarshal(body, &st)
  802. return
  803. }
  804. // GuildRoles returns all roles for a given guild.
  805. // guildID : The ID of a Guild.
  806. func (s *Session) GuildRoles(guildID string) (st []*Role, err error) {
  807. body, err := s.RequestWithBucketID("GET", EndpointGuildRoles(guildID), nil, EndpointGuildRoles(guildID))
  808. if err != nil {
  809. return
  810. }
  811. err = unmarshal(body, &st)
  812. return // TODO return pointer
  813. }
  814. // GuildRoleCreate returns a new Guild Role.
  815. // guildID: The ID of a Guild.
  816. func (s *Session) GuildRoleCreate(guildID string) (st *Role, err error) {
  817. body, err := s.RequestWithBucketID("POST", EndpointGuildRoles(guildID), nil, EndpointGuildRoles(guildID))
  818. if err != nil {
  819. return
  820. }
  821. err = unmarshal(body, &st)
  822. return
  823. }
  824. // GuildRoleEdit updates an existing Guild Role with new values
  825. // guildID : The ID of a Guild.
  826. // roleID : The ID of a Role.
  827. // name : The name of the Role.
  828. // color : The color of the role (decimal, not hex).
  829. // hoist : Whether to display the role's users separately.
  830. // perm : The permissions for the role.
  831. // mention : Whether this role is mentionable
  832. func (s *Session) GuildRoleEdit(guildID, roleID, name string, color int, hoist bool, perm int, mention bool) (st *Role, err error) {
  833. // Prevent sending a color int that is too big.
  834. if color > 0xFFFFFF {
  835. err = fmt.Errorf("color value cannot be larger than 0xFFFFFF")
  836. return nil, err
  837. }
  838. data := struct {
  839. Name string `json:"name"` // The role's name (overwrites existing)
  840. Color int `json:"color"` // The color the role should have (as a decimal, not hex)
  841. Hoist bool `json:"hoist"` // Whether to display the role's users separately
  842. Permissions int `json:"permissions"` // The overall permissions number of the role (overwrites existing)
  843. Mentionable bool `json:"mentionable"` // Whether this role is mentionable
  844. }{name, color, hoist, perm, mention}
  845. body, err := s.RequestWithBucketID("PATCH", EndpointGuildRole(guildID, roleID), data, EndpointGuildRole(guildID, ""))
  846. if err != nil {
  847. return
  848. }
  849. err = unmarshal(body, &st)
  850. return
  851. }
  852. // GuildRoleReorder reoders guild roles
  853. // guildID : The ID of a Guild.
  854. // roles : A list of ordered roles.
  855. func (s *Session) GuildRoleReorder(guildID string, roles []*Role) (st []*Role, err error) {
  856. body, err := s.RequestWithBucketID("PATCH", EndpointGuildRoles(guildID), roles, EndpointGuildRoles(guildID))
  857. if err != nil {
  858. return
  859. }
  860. err = unmarshal(body, &st)
  861. return
  862. }
  863. // GuildRoleDelete deletes an existing role.
  864. // guildID : The ID of a Guild.
  865. // roleID : The ID of a Role.
  866. func (s *Session) GuildRoleDelete(guildID, roleID string) (err error) {
  867. _, err = s.RequestWithBucketID("DELETE", EndpointGuildRole(guildID, roleID), nil, EndpointGuildRole(guildID, ""))
  868. return
  869. }
  870. // GuildPruneCount Returns the number of members that would be removed in a prune operation.
  871. // Requires 'KICK_MEMBER' permission.
  872. // guildID : The ID of a Guild.
  873. // days : The number of days to count prune for (1 or more).
  874. func (s *Session) GuildPruneCount(guildID string, days uint32) (count uint32, err error) {
  875. count = 0
  876. if days <= 0 {
  877. err = ErrPruneDaysBounds
  878. return
  879. }
  880. p := struct {
  881. Pruned uint32 `json:"pruned"`
  882. }{}
  883. uri := EndpointGuildPrune(guildID) + "?days=" + strconv.FormatUint(uint64(days), 10)
  884. body, err := s.RequestWithBucketID("GET", uri, nil, EndpointGuildPrune(guildID))
  885. if err != nil {
  886. return
  887. }
  888. err = unmarshal(body, &p)
  889. if err != nil {
  890. return
  891. }
  892. count = p.Pruned
  893. return
  894. }
  895. // GuildPrune Begin as prune operation. Requires the 'KICK_MEMBERS' permission.
  896. // Returns an object with one 'pruned' key indicating the number of members that were removed in the prune operation.
  897. // guildID : The ID of a Guild.
  898. // days : The number of days to count prune for (1 or more).
  899. func (s *Session) GuildPrune(guildID string, days uint32) (count uint32, err error) {
  900. count = 0
  901. if days <= 0 {
  902. err = ErrPruneDaysBounds
  903. return
  904. }
  905. data := struct {
  906. days uint32
  907. }{days}
  908. p := struct {
  909. Pruned uint32 `json:"pruned"`
  910. }{}
  911. body, err := s.RequestWithBucketID("POST", EndpointGuildPrune(guildID), data, EndpointGuildPrune(guildID))
  912. if err != nil {
  913. return
  914. }
  915. err = unmarshal(body, &p)
  916. if err != nil {
  917. return
  918. }
  919. count = p.Pruned
  920. return
  921. }
  922. // GuildIntegrations returns an array of Integrations for a guild.
  923. // guildID : The ID of a Guild.
  924. func (s *Session) GuildIntegrations(guildID string) (st []*Integration, err error) {
  925. body, err := s.RequestWithBucketID("GET", EndpointGuildIntegrations(guildID), nil, EndpointGuildIntegrations(guildID))
  926. if err != nil {
  927. return
  928. }
  929. err = unmarshal(body, &st)
  930. return
  931. }
  932. // GuildIntegrationCreate creates a Guild Integration.
  933. // guildID : The ID of a Guild.
  934. // integrationType : The Integration type.
  935. // integrationID : The ID of an integration.
  936. func (s *Session) GuildIntegrationCreate(guildID, integrationType, integrationID string) (err error) {
  937. data := struct {
  938. Type string `json:"type"`
  939. ID string `json:"id"`
  940. }{integrationType, integrationID}
  941. _, err = s.RequestWithBucketID("POST", EndpointGuildIntegrations(guildID), data, EndpointGuildIntegrations(guildID))
  942. return
  943. }
  944. // GuildIntegrationEdit edits a Guild Integration.
  945. // guildID : The ID of a Guild.
  946. // integrationType : The Integration type.
  947. // integrationID : The ID of an integration.
  948. // expireBehavior : The behavior when an integration subscription lapses (see the integration object documentation).
  949. // expireGracePeriod : Period (in seconds) where the integration will ignore lapsed subscriptions.
  950. // enableEmoticons : Whether emoticons should be synced for this integration (twitch only currently).
  951. func (s *Session) GuildIntegrationEdit(guildID, integrationID string, expireBehavior, expireGracePeriod int, enableEmoticons bool) (err error) {
  952. data := struct {
  953. ExpireBehavior int `json:"expire_behavior"`
  954. ExpireGracePeriod int `json:"expire_grace_period"`
  955. EnableEmoticons bool `json:"enable_emoticons"`
  956. }{expireBehavior, expireGracePeriod, enableEmoticons}
  957. _, err = s.RequestWithBucketID("PATCH", EndpointGuildIntegration(guildID, integrationID), data, EndpointGuildIntegration(guildID, ""))
  958. return
  959. }
  960. // GuildIntegrationDelete removes the given integration from the Guild.
  961. // guildID : The ID of a Guild.
  962. // integrationID : The ID of an integration.
  963. func (s *Session) GuildIntegrationDelete(guildID, integrationID string) (err error) {
  964. _, err = s.RequestWithBucketID("DELETE", EndpointGuildIntegration(guildID, integrationID), nil, EndpointGuildIntegration(guildID, ""))
  965. return
  966. }
  967. // GuildIntegrationSync syncs an integration.
  968. // guildID : The ID of a Guild.
  969. // integrationID : The ID of an integration.
  970. func (s *Session) GuildIntegrationSync(guildID, integrationID string) (err error) {
  971. _, err = s.RequestWithBucketID("POST", EndpointGuildIntegrationSync(guildID, integrationID), nil, EndpointGuildIntegration(guildID, ""))
  972. return
  973. }
  974. // GuildIcon returns an image.Image of a guild icon.
  975. // guildID : The ID of a Guild.
  976. func (s *Session) GuildIcon(guildID string) (img image.Image, err error) {
  977. g, err := s.Guild(guildID)
  978. if err != nil {
  979. return
  980. }
  981. if g.Icon == "" {
  982. err = ErrGuildNoIcon
  983. return
  984. }
  985. body, err := s.RequestWithBucketID("GET", EndpointGuildIcon(guildID, g.Icon), nil, EndpointGuildIcon(guildID, ""))
  986. if err != nil {
  987. return
  988. }
  989. img, _, err = image.Decode(bytes.NewReader(body))
  990. return
  991. }
  992. // GuildSplash returns an image.Image of a guild splash image.
  993. // guildID : The ID of a Guild.
  994. func (s *Session) GuildSplash(guildID string) (img image.Image, err error) {
  995. g, err := s.Guild(guildID)
  996. if err != nil {
  997. return
  998. }
  999. if g.Splash == "" {
  1000. err = ErrGuildNoSplash
  1001. return
  1002. }
  1003. body, err := s.RequestWithBucketID("GET", EndpointGuildSplash(guildID, g.Splash), nil, EndpointGuildSplash(guildID, ""))
  1004. if err != nil {
  1005. return
  1006. }
  1007. img, _, err = image.Decode(bytes.NewReader(body))
  1008. return
  1009. }
  1010. // GuildEmbed returns the embed for a Guild.
  1011. // guildID : The ID of a Guild.
  1012. func (s *Session) GuildEmbed(guildID string) (st *GuildEmbed, err error) {
  1013. body, err := s.RequestWithBucketID("GET", EndpointGuildEmbed(guildID), nil, EndpointGuildEmbed(guildID))
  1014. if err != nil {
  1015. return
  1016. }
  1017. err = unmarshal(body, &st)
  1018. return
  1019. }
  1020. // GuildEmbedEdit returns the embed for a Guild.
  1021. // guildID : The ID of a Guild.
  1022. func (s *Session) GuildEmbedEdit(guildID string, enabled bool, channelID string) (err error) {
  1023. data := GuildEmbed{enabled, channelID}
  1024. _, err = s.RequestWithBucketID("PATCH", EndpointGuildEmbed(guildID), data, EndpointGuildEmbed(guildID))
  1025. return
  1026. }
  1027. // GuildAuditLog returns the audit log for a Guild.
  1028. // guildID : The ID of a Guild.
  1029. // userID : If provided the log will be filtered for the given ID.
  1030. // beforeID : If provided all log entries returned will be before the given ID.
  1031. // actionType : If provided the log will be filtered for the given Action Type.
  1032. // limit : The number messages that can be returned. (default 50, min 1, max 100)
  1033. func (s *Session) GuildAuditLog(guildID, userID, beforeID string, actionType, limit int) (st *GuildAuditLog, err error) {
  1034. uri := EndpointGuildAuditLogs(guildID)
  1035. v := url.Values{}
  1036. if userID != "" {
  1037. v.Set("user_id", userID)
  1038. }
  1039. if beforeID != "" {
  1040. v.Set("before", beforeID)
  1041. }
  1042. if actionType > 0 {
  1043. v.Set("action_type", strconv.Itoa(actionType))
  1044. }
  1045. if limit > 0 {
  1046. v.Set("limit", strconv.Itoa(limit))
  1047. }
  1048. if len(v) > 0 {
  1049. uri = fmt.Sprintf("%s?%s", uri, v.Encode())
  1050. }
  1051. body, err := s.RequestWithBucketID("GET", uri, nil, EndpointGuildAuditLogs(guildID))
  1052. if err != nil {
  1053. return
  1054. }
  1055. err = unmarshal(body, &st)
  1056. return
  1057. }
  1058. // GuildEmojiCreate creates a new emoji
  1059. // guildID : The ID of a Guild.
  1060. // name : The Name of the Emoji.
  1061. // image : The base64 encoded emoji image, has to be smaller than 256KB.
  1062. // roles : The roles for which this emoji will be whitelisted, can be nil.
  1063. func (s *Session) GuildEmojiCreate(guildID, name, image string, roles []string) (emoji *Emoji, err error) {
  1064. data := struct {
  1065. Name string `json:"name"`
  1066. Image string `json:"image"`
  1067. Roles []string `json:"roles,omitempty"`
  1068. }{name, image, roles}
  1069. body, err := s.RequestWithBucketID("POST", EndpointGuildEmojis(guildID), data, EndpointGuildEmojis(guildID))
  1070. if err != nil {
  1071. return
  1072. }
  1073. err = unmarshal(body, &emoji)
  1074. return
  1075. }
  1076. // GuildEmojiEdit modifies an emoji
  1077. // guildID : The ID of a Guild.
  1078. // emojiID : The ID of an Emoji.
  1079. // name : The Name of the Emoji.
  1080. // roles : The roles for which this emoji will be whitelisted, can be nil.
  1081. func (s *Session) GuildEmojiEdit(guildID, emojiID, name string, roles []string) (emoji *Emoji, err error) {
  1082. data := struct {
  1083. Name string `json:"name"`
  1084. Roles []string `json:"roles,omitempty"`
  1085. }{name, roles}
  1086. body, err := s.RequestWithBucketID("PATCH", EndpointGuildEmoji(guildID, emojiID), data, EndpointGuildEmojis(guildID))
  1087. if err != nil {
  1088. return
  1089. }
  1090. err = unmarshal(body, &emoji)
  1091. return
  1092. }
  1093. // GuildEmojiDelete deletes an Emoji.
  1094. // guildID : The ID of a Guild.
  1095. // emojiID : The ID of an Emoji.
  1096. func (s *Session) GuildEmojiDelete(guildID, emojiID string) (err error) {
  1097. _, err = s.RequestWithBucketID("DELETE", EndpointGuildEmoji(guildID, emojiID), nil, EndpointGuildEmojis(guildID))
  1098. return
  1099. }
  1100. // ------------------------------------------------------------------------------------------------
  1101. // Functions specific to Discord Channels
  1102. // ------------------------------------------------------------------------------------------------
  1103. // Channel returns a Channel structure of a specific Channel.
  1104. // channelID : The ID of the Channel you want returned.
  1105. func (s *Session) Channel(channelID string) (st *Channel, err error) {
  1106. body, err := s.RequestWithBucketID("GET", EndpointChannel(channelID), nil, EndpointChannel(channelID))
  1107. if err != nil {
  1108. return
  1109. }
  1110. err = unmarshal(body, &st)
  1111. return
  1112. }
  1113. // ChannelEdit edits the given channel
  1114. // channelID : The ID of a Channel
  1115. // name : The new name to assign the channel.
  1116. func (s *Session) ChannelEdit(channelID, name string) (*Channel, error) {
  1117. return s.ChannelEditComplex(channelID, &ChannelEdit{
  1118. Name: name,
  1119. })
  1120. }
  1121. // ChannelEditComplex edits an existing channel, replacing the parameters entirely with ChannelEdit struct
  1122. // channelID : The ID of a Channel
  1123. // data : The channel struct to send
  1124. func (s *Session) ChannelEditComplex(channelID string, data *ChannelEdit) (st *Channel, err error) {
  1125. body, err := s.RequestWithBucketID("PATCH", EndpointChannel(channelID), data, EndpointChannel(channelID))
  1126. if err != nil {
  1127. return
  1128. }
  1129. err = unmarshal(body, &st)
  1130. return
  1131. }
  1132. // ChannelDelete deletes the given channel
  1133. // channelID : The ID of a Channel
  1134. func (s *Session) ChannelDelete(channelID string) (st *Channel, err error) {
  1135. body, err := s.RequestWithBucketID("DELETE", EndpointChannel(channelID), nil, EndpointChannel(channelID))
  1136. if err != nil {
  1137. return
  1138. }
  1139. err = unmarshal(body, &st)
  1140. return
  1141. }
  1142. // ChannelTyping broadcasts to all members that authenticated user is typing in
  1143. // the given channel.
  1144. // channelID : The ID of a Channel
  1145. func (s *Session) ChannelTyping(channelID string) (err error) {
  1146. _, err = s.RequestWithBucketID("POST", EndpointChannelTyping(channelID), nil, EndpointChannelTyping(channelID))
  1147. return
  1148. }
  1149. // ChannelMessages returns an array of Message structures for messages within
  1150. // a given channel.
  1151. // channelID : The ID of a Channel.
  1152. // limit : The number messages that can be returned. (max 100)
  1153. // beforeID : If provided all messages returned will be before given ID.
  1154. // afterID : If provided all messages returned will be after given ID.
  1155. // aroundID : If provided all messages returned will be around given ID.
  1156. func (s *Session) ChannelMessages(channelID string, limit int, beforeID, afterID, aroundID string) (st []*Message, err error) {
  1157. uri := EndpointChannelMessages(channelID)
  1158. v := url.Values{}
  1159. if limit > 0 {
  1160. v.Set("limit", strconv.Itoa(limit))
  1161. }
  1162. if afterID != "" {
  1163. v.Set("after", afterID)
  1164. }
  1165. if beforeID != "" {
  1166. v.Set("before", beforeID)
  1167. }
  1168. if aroundID != "" {
  1169. v.Set("around", aroundID)
  1170. }
  1171. if len(v) > 0 {
  1172. uri += "?" + v.Encode()
  1173. }
  1174. body, err := s.RequestWithBucketID("GET", uri, nil, EndpointChannelMessages(channelID))
  1175. if err != nil {
  1176. return
  1177. }
  1178. err = unmarshal(body, &st)
  1179. return
  1180. }
  1181. // ChannelMessage gets a single message by ID from a given channel.
  1182. // channeld : The ID of a Channel
  1183. // messageID : the ID of a Message
  1184. func (s *Session) ChannelMessage(channelID, messageID string) (st *Message, err error) {
  1185. response, err := s.RequestWithBucketID("GET", EndpointChannelMessage(channelID, messageID), nil, EndpointChannelMessage(channelID, ""))
  1186. if err != nil {
  1187. return
  1188. }
  1189. err = unmarshal(response, &st)
  1190. return
  1191. }
  1192. // ChannelMessageAck acknowledges and marks the given message as read
  1193. // channeld : The ID of a Channel
  1194. // messageID : the ID of a Message
  1195. // lastToken : token returned by last ack
  1196. func (s *Session) ChannelMessageAck(channelID, messageID, lastToken string) (st *Ack, err error) {
  1197. body, err := s.RequestWithBucketID("POST", EndpointChannelMessageAck(channelID, messageID), &Ack{Token: lastToken}, EndpointChannelMessageAck(channelID, ""))
  1198. if err != nil {
  1199. return
  1200. }
  1201. err = unmarshal(body, &st)
  1202. return
  1203. }
  1204. // ChannelMessageSend sends a message to the given channel.
  1205. // channelID : The ID of a Channel.
  1206. // content : The message to send.
  1207. func (s *Session) ChannelMessageSend(channelID string, content string) (*Message, error) {
  1208. return s.ChannelMessageSendComplex(channelID, &MessageSend{
  1209. Content: content,
  1210. })
  1211. }
  1212. var quoteEscaper = strings.NewReplacer("\\", "\\\\", `"`, "\\\"")
  1213. // ChannelMessageSendComplex sends a message to the given channel.
  1214. // channelID : The ID of a Channel.
  1215. // data : The message struct to send.
  1216. func (s *Session) ChannelMessageSendComplex(channelID string, data *MessageSend) (st *Message, err error) {
  1217. if data.Embed != nil && data.Embed.Type == "" {
  1218. data.Embed.Type = "rich"
  1219. }
  1220. endpoint := EndpointChannelMessages(channelID)
  1221. // TODO: Remove this when compatibility is not required.
  1222. files := data.Files
  1223. if data.File != nil {
  1224. if files == nil {
  1225. files = []*File{data.File}
  1226. } else {
  1227. err = fmt.Errorf("cannot specify both File and Files")
  1228. return
  1229. }
  1230. }
  1231. var response []byte
  1232. if len(files) > 0 {
  1233. body := &bytes.Buffer{}
  1234. bodywriter := multipart.NewWriter(body)
  1235. var payload []byte
  1236. payload, err = json.Marshal(data)
  1237. if err != nil {
  1238. return
  1239. }
  1240. var p io.Writer
  1241. h := make(textproto.MIMEHeader)
  1242. h.Set("Content-Disposition", `form-data; name="payload_json"`)
  1243. h.Set("Content-Type", "application/json")
  1244. p, err = bodywriter.CreatePart(h)
  1245. if err != nil {
  1246. return
  1247. }
  1248. if _, err = p.Write(payload); err != nil {
  1249. return
  1250. }
  1251. for i, file := range files {
  1252. h := make(textproto.MIMEHeader)
  1253. h.Set("Content-Disposition", fmt.Sprintf(`form-data; name="file%d"; filename="%s"`, i, quoteEscaper.Replace(file.Name)))
  1254. contentType := file.ContentType
  1255. if contentType == "" {
  1256. contentType = "application/octet-stream"
  1257. }
  1258. h.Set("Content-Type", contentType)
  1259. p, err = bodywriter.CreatePart(h)
  1260. if err != nil {
  1261. return
  1262. }
  1263. if _, err = io.Copy(p, file.Reader); err != nil {
  1264. return
  1265. }
  1266. }
  1267. err = bodywriter.Close()
  1268. if err != nil {
  1269. return
  1270. }
  1271. response, err = s.request("POST", endpoint, bodywriter.FormDataContentType(), body.Bytes(), endpoint, 0)
  1272. } else {
  1273. response, err = s.RequestWithBucketID("POST", endpoint, data, endpoint)
  1274. }
  1275. if err != nil {
  1276. return
  1277. }
  1278. err = unmarshal(response, &st)
  1279. return
  1280. }
  1281. // ChannelMessageSendTTS sends a message to the given channel with Text to Speech.
  1282. // channelID : The ID of a Channel.
  1283. // content : The message to send.
  1284. func (s *Session) ChannelMessageSendTTS(channelID string, content string) (*Message, error) {
  1285. return s.ChannelMessageSendComplex(channelID, &MessageSend{
  1286. Content: content,
  1287. TTS: true,
  1288. })
  1289. }
  1290. // ChannelMessageSendEmbed sends a message to the given channel with embedded data.
  1291. // channelID : The ID of a Channel.
  1292. // embed : The embed data to send.
  1293. func (s *Session) ChannelMessageSendEmbed(channelID string, embed *MessageEmbed) (*Message, error) {
  1294. return s.ChannelMessageSendComplex(channelID, &MessageSend{
  1295. Embed: embed,
  1296. })
  1297. }
  1298. // ChannelMessageEdit edits an existing message, replacing it entirely with
  1299. // the given content.
  1300. // channelID : The ID of a Channel
  1301. // messageID : The ID of a Message
  1302. // content : The contents of the message
  1303. func (s *Session) ChannelMessageEdit(channelID, messageID, content string) (*Message, error) {
  1304. return s.ChannelMessageEditComplex(NewMessageEdit(channelID, messageID).SetContent(content))
  1305. }
  1306. // ChannelMessageEditComplex edits an existing message, replacing it entirely with
  1307. // the given MessageEdit struct
  1308. func (s *Session) ChannelMessageEditComplex(m *MessageEdit) (st *Message, err error) {
  1309. if m.Embed != nil && m.Embed.Type == "" {
  1310. m.Embed.Type = "rich"
  1311. }
  1312. response, err := s.RequestWithBucketID("PATCH", EndpointChannelMessage(m.Channel, m.ID), m, EndpointChannelMessage(m.Channel, ""))
  1313. if err != nil {
  1314. return
  1315. }
  1316. err = unmarshal(response, &st)
  1317. return
  1318. }
  1319. // ChannelMessageEditEmbed edits an existing message with embedded data.
  1320. // channelID : The ID of a Channel
  1321. // messageID : The ID of a Message
  1322. // embed : The embed data to send
  1323. func (s *Session) ChannelMessageEditEmbed(channelID, messageID string, embed *MessageEmbed) (*Message, error) {
  1324. return s.ChannelMessageEditComplex(NewMessageEdit(channelID, messageID).SetEmbed(embed))
  1325. }
  1326. // ChannelMessageDelete deletes a message from the Channel.
  1327. func (s *Session) ChannelMessageDelete(channelID, messageID string) (err error) {
  1328. _, err = s.RequestWithBucketID("DELETE", EndpointChannelMessage(channelID, messageID), nil, EndpointChannelMessage(channelID, ""))
  1329. return
  1330. }
  1331. // ChannelMessagesBulkDelete bulk deletes the messages from the channel for the provided messageIDs.
  1332. // If only one messageID is in the slice call channelMessageDelete function.
  1333. // If the slice is empty do nothing.
  1334. // channelID : The ID of the channel for the messages to delete.
  1335. // messages : The IDs of the messages to be deleted. A slice of string IDs. A maximum of 100 messages.
  1336. func (s *Session) ChannelMessagesBulkDelete(channelID string, messages []string) (err error) {
  1337. if len(messages) == 0 {
  1338. return
  1339. }
  1340. if len(messages) == 1 {
  1341. err = s.ChannelMessageDelete(channelID, messages[0])
  1342. return
  1343. }
  1344. if len(messages) > 100 {
  1345. messages = messages[:100]
  1346. }
  1347. data := struct {
  1348. Messages []string `json:"messages"`
  1349. }{messages}
  1350. _, err = s.RequestWithBucketID("POST", EndpointChannelMessagesBulkDelete(channelID), data, EndpointChannelMessagesBulkDelete(channelID))
  1351. return
  1352. }
  1353. // ChannelMessagePin pins a message within a given channel.
  1354. // channelID: The ID of a channel.
  1355. // messageID: The ID of a message.
  1356. func (s *Session) ChannelMessagePin(channelID, messageID string) (err error) {
  1357. _, err = s.RequestWithBucketID("PUT", EndpointChannelMessagePin(channelID, messageID), nil, EndpointChannelMessagePin(channelID, ""))
  1358. return
  1359. }
  1360. // ChannelMessageUnpin unpins a message within a given channel.
  1361. // channelID: The ID of a channel.
  1362. // messageID: The ID of a message.
  1363. func (s *Session) ChannelMessageUnpin(channelID, messageID string) (err error) {
  1364. _, err = s.RequestWithBucketID("DELETE", EndpointChannelMessagePin(channelID, messageID), nil, EndpointChannelMessagePin(channelID, ""))
  1365. return
  1366. }
  1367. // ChannelMessagesPinned returns an array of Message structures for pinned messages
  1368. // within a given channel
  1369. // channelID : The ID of a Channel.
  1370. func (s *Session) ChannelMessagesPinned(channelID string) (st []*Message, err error) {
  1371. body, err := s.RequestWithBucketID("GET", EndpointChannelMessagesPins(channelID), nil, EndpointChannelMessagesPins(channelID))
  1372. if err != nil {
  1373. return
  1374. }
  1375. err = unmarshal(body, &st)
  1376. return
  1377. }
  1378. // ChannelFileSend sends a file to the given channel.
  1379. // channelID : The ID of a Channel.
  1380. // name: The name of the file.
  1381. // io.Reader : A reader for the file contents.
  1382. func (s *Session) ChannelFileSend(channelID, name string, r io.Reader) (*Message, error) {
  1383. return s.ChannelMessageSendComplex(channelID, &MessageSend{File: &File{Name: name, Reader: r}})
  1384. }
  1385. // ChannelFileSendWithMessage sends a file to the given channel with an message.
  1386. // DEPRECATED. Use ChannelMessageSendComplex instead.
  1387. // channelID : The ID of a Channel.
  1388. // content: Optional Message content.
  1389. // name: The name of the file.
  1390. // io.Reader : A reader for the file contents.
  1391. func (s *Session) ChannelFileSendWithMessage(channelID, content string, name string, r io.Reader) (*Message, error) {
  1392. return s.ChannelMessageSendComplex(channelID, &MessageSend{File: &File{Name: name, Reader: r}, Content: content})
  1393. }
  1394. // ChannelInvites returns an array of Invite structures for the given channel
  1395. // channelID : The ID of a Channel
  1396. func (s *Session) ChannelInvites(channelID string) (st []*Invite, err error) {
  1397. body, err := s.RequestWithBucketID("GET", EndpointChannelInvites(channelID), nil, EndpointChannelInvites(channelID))
  1398. if err != nil {
  1399. return
  1400. }
  1401. err = unmarshal(body, &st)
  1402. return
  1403. }
  1404. // ChannelInviteCreate creates a new invite for the given channel.
  1405. // channelID : The ID of a Channel
  1406. // i : An Invite struct with the values MaxAge, MaxUses and Temporary defined.
  1407. func (s *Session) ChannelInviteCreate(channelID string, i Invite) (st *Invite, err error) {
  1408. data := struct {
  1409. MaxAge int `json:"max_age"`
  1410. MaxUses int `json:"max_uses"`
  1411. Temporary bool `json:"temporary"`
  1412. Unique bool `json:"unique"`
  1413. }{i.MaxAge, i.MaxUses, i.Temporary, i.Unique}
  1414. body, err := s.RequestWithBucketID("POST", EndpointChannelInvites(channelID), data, EndpointChannelInvites(channelID))
  1415. if err != nil {
  1416. return
  1417. }
  1418. err = unmarshal(body, &st)
  1419. return
  1420. }
  1421. // ChannelPermissionSet creates a Permission Override for the given channel.
  1422. // NOTE: This func name may changed. Using Set instead of Create because
  1423. // you can both create a new override or update an override with this function.
  1424. func (s *Session) ChannelPermissionSet(channelID, targetID, targetType string, allow, deny int) (err error) {
  1425. data := struct {
  1426. ID string `json:"id"`
  1427. Type string `json:"type"`
  1428. Allow int `json:"allow"`
  1429. Deny int `json:"deny"`
  1430. }{targetID, targetType, allow, deny}
  1431. _, err = s.RequestWithBucketID("PUT", EndpointChannelPermission(channelID, targetID), data, EndpointChannelPermission(channelID, ""))
  1432. return
  1433. }
  1434. // ChannelPermissionDelete deletes a specific permission override for the given channel.
  1435. // NOTE: Name of this func may change.
  1436. func (s *Session) ChannelPermissionDelete(channelID, targetID string) (err error) {
  1437. _, err = s.RequestWithBucketID("DELETE", EndpointChannelPermission(channelID, targetID), nil, EndpointChannelPermission(channelID, ""))
  1438. return
  1439. }
  1440. // ------------------------------------------------------------------------------------------------
  1441. // Functions specific to Discord Invites
  1442. // ------------------------------------------------------------------------------------------------
  1443. // Invite returns an Invite structure of the given invite
  1444. // inviteID : The invite code
  1445. func (s *Session) Invite(inviteID string) (st *Invite, err error) {
  1446. body, err := s.RequestWithBucketID("GET", EndpointInvite(inviteID), nil, EndpointInvite(""))
  1447. if err != nil {
  1448. return
  1449. }
  1450. err = unmarshal(body, &st)
  1451. return
  1452. }
  1453. // InviteWithCounts returns an Invite structure of the given invite including approximate member counts
  1454. // inviteID : The invite code
  1455. func (s *Session) InviteWithCounts(inviteID string) (st *Invite, err error) {
  1456. body, err := s.RequestWithBucketID("GET", EndpointInvite(inviteID)+"?with_counts=true", nil, EndpointInvite(""))
  1457. if err != nil {
  1458. return
  1459. }
  1460. err = unmarshal(body, &st)
  1461. return
  1462. }
  1463. // InviteDelete deletes an existing invite
  1464. // inviteID : the code of an invite
  1465. func (s *Session) InviteDelete(inviteID string) (st *Invite, err error) {
  1466. body, err := s.RequestWithBucketID("DELETE", EndpointInvite(inviteID), nil, EndpointInvite(""))
  1467. if err != nil {
  1468. return
  1469. }
  1470. err = unmarshal(body, &st)
  1471. return
  1472. }
  1473. // InviteAccept accepts an Invite to a Guild or Channel
  1474. // inviteID : The invite code
  1475. func (s *Session) InviteAccept(inviteID string) (st *Invite, err error) {
  1476. body, err := s.RequestWithBucketID("POST", EndpointInvite(inviteID), nil, EndpointInvite(""))
  1477. if err != nil {
  1478. return
  1479. }
  1480. err = unmarshal(body, &st)
  1481. return
  1482. }
  1483. // ------------------------------------------------------------------------------------------------
  1484. // Functions specific to Discord Voice
  1485. // ------------------------------------------------------------------------------------------------
  1486. // VoiceRegions returns the voice server regions
  1487. func (s *Session) VoiceRegions() (st []*VoiceRegion, err error) {
  1488. body, err := s.RequestWithBucketID("GET", EndpointVoiceRegions, nil, EndpointVoiceRegions)
  1489. if err != nil {
  1490. return
  1491. }
  1492. err = unmarshal(body, &st)
  1493. return
  1494. }
  1495. // VoiceICE returns the voice server ICE information
  1496. func (s *Session) VoiceICE() (st *VoiceICE, err error) {
  1497. body, err := s.RequestWithBucketID("GET", EndpointVoiceIce, nil, EndpointVoiceIce)
  1498. if err != nil {
  1499. return
  1500. }
  1501. err = unmarshal(body, &st)
  1502. return
  1503. }
  1504. // ------------------------------------------------------------------------------------------------
  1505. // Functions specific to Discord Websockets
  1506. // ------------------------------------------------------------------------------------------------
  1507. // Gateway returns the websocket Gateway address
  1508. func (s *Session) Gateway() (gateway string, err error) {
  1509. response, err := s.RequestWithBucketID("GET", EndpointGateway, nil, EndpointGateway)
  1510. if err != nil {
  1511. return
  1512. }
  1513. temp := struct {
  1514. URL string `json:"url"`
  1515. }{}
  1516. err = unmarshal(response, &temp)
  1517. if err != nil {
  1518. return
  1519. }
  1520. gateway = temp.URL
  1521. // Ensure the gateway always has a trailing slash.
  1522. // MacOS will fail to connect if we add query params without a trailing slash on the base domain.
  1523. if !strings.HasSuffix(gateway, "/") {
  1524. gateway += "/"
  1525. }
  1526. return
  1527. }
  1528. // GatewayBot returns the websocket Gateway address and the recommended number of shards
  1529. func (s *Session) GatewayBot() (st *GatewayBotResponse, err error) {
  1530. response, err := s.RequestWithBucketID("GET", EndpointGatewayBot, nil, EndpointGatewayBot)
  1531. if err != nil {
  1532. return
  1533. }
  1534. err = unmarshal(response, &st)
  1535. if err != nil {
  1536. return
  1537. }
  1538. // Ensure the gateway always has a trailing slash.
  1539. // MacOS will fail to connect if we add query params without a trailing slash on the base domain.
  1540. if !strings.HasSuffix(st.URL, "/") {
  1541. st.URL += "/"
  1542. }
  1543. return
  1544. }
  1545. // Functions specific to Webhooks
  1546. // WebhookCreate returns a new Webhook.
  1547. // channelID: The ID of a Channel.
  1548. // name : The name of the webhook.
  1549. // avatar : The avatar of the webhook.
  1550. func (s *Session) WebhookCreate(channelID, name, avatar string) (st *Webhook, err error) {
  1551. data := struct {
  1552. Name string `json:"name"`
  1553. Avatar string `json:"avatar,omitempty"`
  1554. }{name, avatar}
  1555. body, err := s.RequestWithBucketID("POST", EndpointChannelWebhooks(channelID), data, EndpointChannelWebhooks(channelID))
  1556. if err != nil {
  1557. return
  1558. }
  1559. err = unmarshal(body, &st)
  1560. return
  1561. }
  1562. // ChannelWebhooks returns all webhooks for a given channel.
  1563. // channelID: The ID of a channel.
  1564. func (s *Session) ChannelWebhooks(channelID string) (st []*Webhook, err error) {
  1565. body, err := s.RequestWithBucketID("GET", EndpointChannelWebhooks(channelID), nil, EndpointChannelWebhooks(channelID))
  1566. if err != nil {
  1567. return
  1568. }
  1569. err = unmarshal(body, &st)
  1570. return
  1571. }
  1572. // GuildWebhooks returns all webhooks for a given guild.
  1573. // guildID: The ID of a Guild.
  1574. func (s *Session) GuildWebhooks(guildID string) (st []*Webhook, err error) {
  1575. body, err := s.RequestWithBucketID("GET", EndpointGuildWebhooks(guildID), nil, EndpointGuildWebhooks(guildID))
  1576. if err != nil {
  1577. return
  1578. }
  1579. err = unmarshal(body, &st)
  1580. return
  1581. }
  1582. // Webhook returns a webhook for a given ID
  1583. // webhookID: The ID of a webhook.
  1584. func (s *Session) Webhook(webhookID string) (st *Webhook, err error) {
  1585. body, err := s.RequestWithBucketID("GET", EndpointWebhook(webhookID), nil, EndpointWebhooks)
  1586. if err != nil {
  1587. return
  1588. }
  1589. err = unmarshal(body, &st)
  1590. return
  1591. }
  1592. // WebhookWithToken returns a webhook for a given ID
  1593. // webhookID: The ID of a webhook.
  1594. // token : The auth token for the webhook.
  1595. func (s *Session) WebhookWithToken(webhookID, token string) (st *Webhook, err error) {
  1596. body, err := s.RequestWithBucketID("GET", EndpointWebhookToken(webhookID, token), nil, EndpointWebhookToken("", ""))
  1597. if err != nil {
  1598. return
  1599. }
  1600. err = unmarshal(body, &st)
  1601. return
  1602. }
  1603. // WebhookEdit updates an existing Webhook.
  1604. // webhookID: The ID of a webhook.
  1605. // name : The name of the webhook.
  1606. // avatar : The avatar of the webhook.
  1607. func (s *Session) WebhookEdit(webhookID, name, avatar, channelID string) (st *Role, err error) {
  1608. data := struct {
  1609. Name string `json:"name,omitempty"`
  1610. Avatar string `json:"avatar,omitempty"`
  1611. ChannelID string `json:"channel_id,omitempty"`
  1612. }{name, avatar, channelID}
  1613. body, err := s.RequestWithBucketID("PATCH", EndpointWebhook(webhookID), data, EndpointWebhooks)
  1614. if err != nil {
  1615. return
  1616. }
  1617. err = unmarshal(body, &st)
  1618. return
  1619. }
  1620. // WebhookEditWithToken updates an existing Webhook with an auth token.
  1621. // webhookID: The ID of a webhook.
  1622. // token : The auth token for the webhook.
  1623. // name : The name of the webhook.
  1624. // avatar : The avatar of the webhook.
  1625. func (s *Session) WebhookEditWithToken(webhookID, token, name, avatar string) (st *Role, err error) {
  1626. data := struct {
  1627. Name string `json:"name,omitempty"`
  1628. Avatar string `json:"avatar,omitempty"`
  1629. }{name, avatar}
  1630. body, err := s.RequestWithBucketID("PATCH", EndpointWebhookToken(webhookID, token), data, EndpointWebhookToken("", ""))
  1631. if err != nil {
  1632. return
  1633. }
  1634. err = unmarshal(body, &st)
  1635. return
  1636. }
  1637. // WebhookDelete deletes a webhook for a given ID
  1638. // webhookID: The ID of a webhook.
  1639. func (s *Session) WebhookDelete(webhookID string) (err error) {
  1640. _, err = s.RequestWithBucketID("DELETE", EndpointWebhook(webhookID), nil, EndpointWebhooks)
  1641. return
  1642. }
  1643. // WebhookDeleteWithToken deletes a webhook for a given ID with an auth token.
  1644. // webhookID: The ID of a webhook.
  1645. // token : The auth token for the webhook.
  1646. func (s *Session) WebhookDeleteWithToken(webhookID, token string) (st *Webhook, err error) {
  1647. body, err := s.RequestWithBucketID("DELETE", EndpointWebhookToken(webhookID, token), nil, EndpointWebhookToken("", ""))
  1648. if err != nil {
  1649. return
  1650. }
  1651. err = unmarshal(body, &st)
  1652. return
  1653. }
  1654. // WebhookExecute executes a webhook.
  1655. // webhookID: The ID of a webhook.
  1656. // token : The auth token for the webhook
  1657. // wait : Waits for server confirmation of message send and ensures that the return struct is populated (it is nil otherwise)
  1658. func (s *Session) WebhookExecute(webhookID, token string, wait bool, data *WebhookParams) (st *Message, err error) {
  1659. uri := EndpointWebhookToken(webhookID, token)
  1660. if wait {
  1661. uri += "?wait=true"
  1662. }
  1663. response, err := s.RequestWithBucketID("POST", uri, data, EndpointWebhookToken("", ""))
  1664. if !wait || err != nil {
  1665. return
  1666. }
  1667. err = unmarshal(response, &st)
  1668. return
  1669. }
  1670. // MessageReactionAdd creates an emoji reaction to a message.
  1671. // channelID : The channel ID.
  1672. // messageID : The message ID.
  1673. // emojiID : Either the unicode emoji for the reaction, or a guild emoji identifier.
  1674. func (s *Session) MessageReactionAdd(channelID, messageID, emojiID string) error {
  1675. // emoji such as #⃣ need to have # escaped
  1676. emojiID = strings.Replace(emojiID, "#", "%23", -1)
  1677. _, err := s.RequestWithBucketID("PUT", EndpointMessageReaction(channelID, messageID, emojiID, "@me"), nil, EndpointMessageReaction(channelID, "", "", ""))
  1678. return err
  1679. }
  1680. // MessageReactionRemove deletes an emoji reaction to a message.
  1681. // channelID : The channel ID.
  1682. // messageID : The message ID.
  1683. // emojiID : Either the unicode emoji for the reaction, or a guild emoji identifier.
  1684. // userID : @me or ID of the user to delete the reaction for.
  1685. func (s *Session) MessageReactionRemove(channelID, messageID, emojiID, userID string) error {
  1686. // emoji such as #⃣ need to have # escaped
  1687. emojiID = strings.Replace(emojiID, "#", "%23", -1)
  1688. _, err := s.RequestWithBucketID("DELETE", EndpointMessageReaction(channelID, messageID, emojiID, userID), nil, EndpointMessageReaction(channelID, "", "", ""))
  1689. return err
  1690. }
  1691. // MessageReactionsRemoveAll deletes all reactions from a message
  1692. // channelID : The channel ID
  1693. // messageID : The message ID.
  1694. func (s *Session) MessageReactionsRemoveAll(channelID, messageID string) error {
  1695. _, err := s.RequestWithBucketID("DELETE", EndpointMessageReactionsAll(channelID, messageID), nil, EndpointMessageReactionsAll(channelID, messageID))
  1696. return err
  1697. }
  1698. // MessageReactions gets all the users reactions for a specific emoji.
  1699. // channelID : The channel ID.
  1700. // messageID : The message ID.
  1701. // emojiID : Either the unicode emoji for the reaction, or a guild emoji identifier.
  1702. // limit : max number of users to return (max 100)
  1703. // beforeID : If provided all reactions returned will be before given ID.
  1704. // afterID : If provided all reactions returned will be after given ID.
  1705. func (s *Session) MessageReactions(channelID, messageID, emojiID string, limit int, beforeID, afterID string) (st []*User, err error) {
  1706. // emoji such as #⃣ need to have # escaped
  1707. emojiID = strings.Replace(emojiID, "#", "%23", -1)
  1708. uri := EndpointMessageReactions(channelID, messageID, emojiID)
  1709. v := url.Values{}
  1710. if limit > 0 {
  1711. v.Set("limit", strconv.Itoa(limit))
  1712. }
  1713. if afterID != "" {
  1714. v.Set("after", afterID)
  1715. }
  1716. if beforeID != "" {
  1717. v.Set("before", beforeID)
  1718. }
  1719. if len(v) > 0 {
  1720. uri += "?" + v.Encode()
  1721. }
  1722. body, err := s.RequestWithBucketID("GET", uri, nil, EndpointMessageReaction(channelID, "", "", ""))
  1723. if err != nil {
  1724. return
  1725. }
  1726. err = unmarshal(body, &st)
  1727. return
  1728. }
  1729. // ------------------------------------------------------------------------------------------------
  1730. // Functions specific to user notes
  1731. // ------------------------------------------------------------------------------------------------
  1732. // UserNoteSet sets the note for a specific user.
  1733. func (s *Session) UserNoteSet(userID string, message string) (err error) {
  1734. data := struct {
  1735. Note string `json:"note"`
  1736. }{message}
  1737. _, err = s.RequestWithBucketID("PUT", EndpointUserNotes(userID), data, EndpointUserNotes(""))
  1738. return
  1739. }
  1740. // ------------------------------------------------------------------------------------------------
  1741. // Functions specific to Discord Relationships (Friends list)
  1742. // ------------------------------------------------------------------------------------------------
  1743. // RelationshipsGet returns an array of all the relationships of the user.
  1744. func (s *Session) RelationshipsGet() (r []*Relationship, err error) {
  1745. body, err := s.RequestWithBucketID("GET", EndpointRelationships(), nil, EndpointRelationships())
  1746. if err != nil {
  1747. return
  1748. }
  1749. err = unmarshal(body, &r)
  1750. return
  1751. }
  1752. // relationshipCreate creates a new relationship. (I.e. send or accept a friend request, block a user.)
  1753. // relationshipType : 1 = friend, 2 = blocked, 3 = incoming friend req, 4 = sent friend req
  1754. func (s *Session) relationshipCreate(userID string, relationshipType int) (err error) {
  1755. data := struct {
  1756. Type int `json:"type"`
  1757. }{relationshipType}
  1758. _, err = s.RequestWithBucketID("PUT", EndpointRelationship(userID), data, EndpointRelationships())
  1759. return
  1760. }
  1761. // RelationshipFriendRequestSend sends a friend request to a user.
  1762. // userID: ID of the user.
  1763. func (s *Session) RelationshipFriendRequestSend(userID string) (err error) {
  1764. err = s.relationshipCreate(userID, 4)
  1765. return
  1766. }
  1767. // RelationshipFriendRequestAccept accepts a friend request from a user.
  1768. // userID: ID of the user.
  1769. func (s *Session) RelationshipFriendRequestAccept(userID string) (err error) {
  1770. err = s.relationshipCreate(userID, 1)
  1771. return
  1772. }
  1773. // RelationshipUserBlock blocks a user.
  1774. // userID: ID of the user.
  1775. func (s *Session) RelationshipUserBlock(userID string) (err error) {
  1776. err = s.relationshipCreate(userID, 2)
  1777. return
  1778. }
  1779. // RelationshipDelete removes the relationship with a user.
  1780. // userID: ID of the user.
  1781. func (s *Session) RelationshipDelete(userID string) (err error) {
  1782. _, err = s.RequestWithBucketID("DELETE", EndpointRelationship(userID), nil, EndpointRelationships())
  1783. return
  1784. }
  1785. // RelationshipsMutualGet returns an array of all the users both @me and the given user is friends with.
  1786. // userID: ID of the user.
  1787. func (s *Session) RelationshipsMutualGet(userID string) (mf []*User, err error) {
  1788. body, err := s.RequestWithBucketID("GET", EndpointRelationshipsMutual(userID), nil, EndpointRelationshipsMutual(userID))
  1789. if err != nil {
  1790. return
  1791. }
  1792. err = unmarshal(body, &mf)
  1793. return
  1794. }