restapi.go 55 KB

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