restapi.go 55 KB

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