restapi.go 69 KB

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