restapi.go 62 KB

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