restapi.go 37 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403
  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. "sync"
  26. "time"
  27. )
  28. // ErrJSONUnmarshal is returned for JSON Unmarshall errors.
  29. var ErrJSONUnmarshal = errors.New("json unmarshal")
  30. // Request makes a (GET/POST/...) Requests to Discord REST API with JSON data.
  31. // All the other Discord REST Calls in this file use this function.
  32. func (s *Session) Request(method, urlStr string, data interface{}) (response []byte, err error) {
  33. var body []byte
  34. if data != nil {
  35. body, err = json.Marshal(data)
  36. if err != nil {
  37. return
  38. }
  39. }
  40. return s.request(method, urlStr, "application/json", body)
  41. }
  42. // request makes a (GET/POST/...) Requests to Discord REST API.
  43. func (s *Session) request(method, urlStr, contentType string, b []byte) (response []byte, err error) {
  44. // rate limit mutex for this url
  45. // TODO: review for performance improvements
  46. // ideally we just ignore endpoints that we've never
  47. // received a 429 on. But this simple method works and
  48. // is a lot less complex :) It also might even be more
  49. // performat due to less checks and maps.
  50. var mu *sync.Mutex
  51. s.rateLimit.Lock()
  52. if s.rateLimit.url == nil {
  53. s.rateLimit.url = make(map[string]*sync.Mutex)
  54. }
  55. bu := strings.Split(urlStr, "?")
  56. mu, _ = s.rateLimit.url[bu[0]]
  57. if mu == nil {
  58. mu = new(sync.Mutex)
  59. s.rateLimit.url[bu[0]] = mu
  60. }
  61. s.rateLimit.Unlock()
  62. mu.Lock() // lock this URL for ratelimiting
  63. if s.Debug {
  64. log.Printf("API REQUEST %8s :: %s\n", method, urlStr)
  65. log.Printf("API REQUEST PAYLOAD :: [%s]\n", string(b))
  66. }
  67. req, err := http.NewRequest(method, urlStr, bytes.NewBuffer(b))
  68. if err != nil {
  69. return
  70. }
  71. // Not used on initial login..
  72. // TODO: Verify if a login, otherwise complain about no-token
  73. if s.Token != "" {
  74. req.Header.Set("authorization", s.Token)
  75. }
  76. req.Header.Set("Content-Type", contentType)
  77. // TODO: Make a configurable static variable.
  78. req.Header.Set("User-Agent", fmt.Sprintf("DiscordBot (https://github.com/bwmarrin/discordgo, v%s)", VERSION))
  79. if s.Debug {
  80. for k, v := range req.Header {
  81. log.Printf("API REQUEST HEADER :: [%s] = %+v\n", k, v)
  82. }
  83. }
  84. client := &http.Client{Timeout: (20 * time.Second)}
  85. resp, err := client.Do(req)
  86. mu.Unlock() // unlock ratelimit mutex
  87. if err != nil {
  88. return
  89. }
  90. defer func() {
  91. err2 := resp.Body.Close()
  92. if err2 != nil {
  93. log.Println("error closing resp body")
  94. }
  95. }()
  96. response, err = ioutil.ReadAll(resp.Body)
  97. if err != nil {
  98. return
  99. }
  100. if s.Debug {
  101. log.Printf("API RESPONSE STATUS :: %s\n", resp.Status)
  102. for k, v := range resp.Header {
  103. log.Printf("API RESPONSE HEADER :: [%s] = %+v\n", k, v)
  104. }
  105. log.Printf("API RESPONSE BODY :: [%s]\n\n\n", response)
  106. }
  107. switch resp.StatusCode {
  108. case http.StatusOK:
  109. case http.StatusCreated:
  110. case http.StatusNoContent:
  111. // TODO check for 401 response, invalidate token if we get one.
  112. case 429: // TOO MANY REQUESTS - Rate limiting
  113. mu.Lock() // lock URL ratelimit mutex
  114. rl := TooManyRequests{}
  115. err = json.Unmarshal(response, &rl)
  116. if err != nil {
  117. s.log(LogError, "rate limit unmarshal error, %s", err)
  118. mu.Unlock()
  119. return
  120. }
  121. s.log(LogInformational, "Rate Limiting %s, retry in %d", urlStr, rl.RetryAfter)
  122. s.handle(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 then required
  126. mu.Unlock() // we have to unlock here
  127. response, err = s.request(method, urlStr, contentType, b)
  128. default: // Error condition
  129. err = fmt.Errorf("HTTP %s, %s", resp.Status, response)
  130. }
  131. return
  132. }
  133. func unmarshal(data []byte, v interface{}) error {
  134. err := json.Unmarshal(data, v)
  135. if err != nil {
  136. return ErrJSONUnmarshal
  137. }
  138. return nil
  139. }
  140. // ------------------------------------------------------------------------------------------------
  141. // Functions specific to Discord Sessions
  142. // ------------------------------------------------------------------------------------------------
  143. // Login asks the Discord server for an authentication token.
  144. func (s *Session) Login(email, password string) (err error) {
  145. data := struct {
  146. Email string `json:"email"`
  147. Password string `json:"password"`
  148. }{email, password}
  149. response, err := s.Request("POST", EndpointLogin, data)
  150. if err != nil {
  151. return
  152. }
  153. temp := struct {
  154. Token string `json:"token"`
  155. }{}
  156. err = unmarshal(response, &temp)
  157. if err != nil {
  158. return
  159. }
  160. s.Token = temp.Token
  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.Request("POST", EndpointRegister, data)
  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.Request("POST", EndpointLogout, data)
  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.Request("GET", EndpointUser(userID), nil)
  206. if err != nil {
  207. return
  208. }
  209. err = unmarshal(body, &st)
  210. return
  211. }
  212. // UserAvatar returns an image.Image of a users Avatar.
  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. body, err := s.Request("GET", EndpointUserAvatar(userID, u.Avatar), nil)
  220. if err != nil {
  221. return
  222. }
  223. img, _, err = image.Decode(bytes.NewReader(body))
  224. return
  225. }
  226. // UserUpdate updates a users settings.
  227. func (s *Session) UserUpdate(email, password, username, avatar, newPassword string) (st *User, err error) {
  228. // NOTE: Avatar must be either the hash/id of existing Avatar or
  229. // data:image/png;base64,BASE64_STRING_OF_NEW_AVATAR_PNG
  230. // to set a new avatar.
  231. // If left blank, avatar will be set to null/blank
  232. data := struct {
  233. Email string `json:"email"`
  234. Password string `json:"password"`
  235. Username string `json:"username"`
  236. Avatar string `json:"avatar,omitempty"`
  237. NewPassword string `json:"new_password,omitempty"`
  238. }{email, password, username, avatar, newPassword}
  239. body, err := s.Request("PATCH", EndpointUser("@me"), data)
  240. if err != nil {
  241. return
  242. }
  243. err = unmarshal(body, &st)
  244. return
  245. }
  246. // UserSettings returns the settings for a given user
  247. func (s *Session) UserSettings() (st *Settings, err error) {
  248. body, err := s.Request("GET", EndpointUserSettings("@me"), nil)
  249. if err != nil {
  250. return
  251. }
  252. err = unmarshal(body, &st)
  253. return
  254. }
  255. // UserChannels returns an array of Channel structures for all private
  256. // channels.
  257. func (s *Session) UserChannels() (st []*Channel, err error) {
  258. body, err := s.Request("GET", EndpointUserChannels("@me"), nil)
  259. if err != nil {
  260. return
  261. }
  262. err = unmarshal(body, &st)
  263. return
  264. }
  265. // UserChannelCreate creates a new User (Private) Channel with another User
  266. // recipientID : A user ID for the user to which this channel is opened with.
  267. func (s *Session) UserChannelCreate(recipientID string) (st *Channel, err error) {
  268. data := struct {
  269. RecipientID string `json:"recipient_id"`
  270. }{recipientID}
  271. body, err := s.Request("POST", EndpointUserChannels("@me"), data)
  272. if err != nil {
  273. return
  274. }
  275. err = unmarshal(body, &st)
  276. return
  277. }
  278. // UserGuilds returns an array of Guild structures for all guilds.
  279. func (s *Session) UserGuilds() (st []*Guild, err error) {
  280. body, err := s.Request("GET", EndpointUserGuilds("@me"), nil)
  281. if err != nil {
  282. return
  283. }
  284. err = unmarshal(body, &st)
  285. return
  286. }
  287. // UserGuildSettingsEdit Edits the users notification settings for a guild
  288. // guildID : The ID of the guild to edit the settings on
  289. // settings : The settings to update
  290. func (s *Session) UserGuildSettingsEdit(guildID string, settings *UserGuildSettingsEdit) (st *UserGuildSettings, err error) {
  291. body, err := s.Request("PATCH", EndpointUserGuildSettings("@me", guildID), settings)
  292. if err != nil {
  293. return
  294. }
  295. err = unmarshal(body, &st)
  296. return
  297. }
  298. // NOTE: This function is now deprecated and will be removed in the future.
  299. // Please see the same function inside state.go
  300. // UserChannelPermissions returns the permission of a user in a channel.
  301. // userID : The ID of the user to calculate permissions for.
  302. // channelID : The ID of the channel to calculate permission for.
  303. func (s *Session) UserChannelPermissions(userID, channelID string) (apermissions int, err error) {
  304. channel, err := s.State.Channel(channelID)
  305. if err != nil || channel == nil {
  306. channel, err = s.Channel(channelID)
  307. if err != nil {
  308. return
  309. }
  310. }
  311. guild, err := s.State.Guild(channel.GuildID)
  312. if err != nil || guild == nil {
  313. guild, err = s.Guild(channel.GuildID)
  314. if err != nil {
  315. return
  316. }
  317. }
  318. if userID == guild.OwnerID {
  319. apermissions = PermissionAll
  320. return
  321. }
  322. member, err := s.State.Member(guild.ID, userID)
  323. if err != nil || member == nil {
  324. member, err = s.GuildMember(guild.ID, userID)
  325. if err != nil {
  326. return
  327. }
  328. }
  329. for _, role := range guild.Roles {
  330. for _, roleID := range member.Roles {
  331. if role.ID == roleID {
  332. apermissions |= role.Permissions
  333. break
  334. }
  335. }
  336. }
  337. if apermissions&PermissionManageRoles > 0 {
  338. apermissions |= PermissionAll
  339. }
  340. // Member overwrites can override role overrides, so do two passes
  341. for _, overwrite := range channel.PermissionOverwrites {
  342. for _, roleID := range member.Roles {
  343. if overwrite.Type == "role" && roleID == overwrite.ID {
  344. apermissions &= ^overwrite.Deny
  345. apermissions |= overwrite.Allow
  346. break
  347. }
  348. }
  349. }
  350. for _, overwrite := range channel.PermissionOverwrites {
  351. if overwrite.Type == "member" && overwrite.ID == userID {
  352. apermissions &= ^overwrite.Deny
  353. apermissions |= overwrite.Allow
  354. break
  355. }
  356. }
  357. if apermissions&PermissionManageRoles > 0 {
  358. apermissions |= PermissionAllChannel
  359. }
  360. return
  361. }
  362. // ------------------------------------------------------------------------------------------------
  363. // Functions specific to Discord Guilds
  364. // ------------------------------------------------------------------------------------------------
  365. // Guild returns a Guild structure of a specific Guild.
  366. // guildID : The ID of a Guild
  367. func (s *Session) Guild(guildID string) (st *Guild, err error) {
  368. if s.StateEnabled {
  369. // Attempt to grab the guild from State first.
  370. st, err = s.State.Guild(guildID)
  371. if err == nil {
  372. return
  373. }
  374. }
  375. body, err := s.Request("GET", EndpointGuild(guildID), nil)
  376. if err != nil {
  377. return
  378. }
  379. err = unmarshal(body, &st)
  380. return
  381. }
  382. // GuildCreate creates a new Guild
  383. // name : A name for the Guild (2-100 characters)
  384. func (s *Session) GuildCreate(name string) (st *Guild, err error) {
  385. data := struct {
  386. Name string `json:"name"`
  387. }{name}
  388. body, err := s.Request("POST", EndpointGuilds, data)
  389. if err != nil {
  390. return
  391. }
  392. err = unmarshal(body, &st)
  393. return
  394. }
  395. // GuildEdit edits a new Guild
  396. // guildID : The ID of a Guild
  397. // g : A GuildParams struct with the values Name, Region and VerificationLevel defined.
  398. func (s *Session) GuildEdit(guildID string, g GuildParams) (st *Guild, err error) {
  399. // Bounds checking for VerificationLevel, interval: [0, 3]
  400. if g.VerificationLevel != nil {
  401. val := *g.VerificationLevel
  402. if val < 0 || val > 3 {
  403. err = errors.New("VerificationLevel out of bounds, should be between 0 and 3")
  404. return
  405. }
  406. }
  407. //Bounds checking for regions
  408. if g.Region != "" {
  409. isValid := false
  410. regions, _ := s.VoiceRegions()
  411. for _, r := range regions {
  412. if g.Region == r.ID {
  413. isValid = true
  414. }
  415. }
  416. if !isValid {
  417. var valid []string
  418. for _, r := range regions {
  419. valid = append(valid, r.ID)
  420. }
  421. err = fmt.Errorf("Region not a valid region (%q)", valid)
  422. return
  423. }
  424. }
  425. data := struct {
  426. Name string `json:"name,omitempty"`
  427. Region string `json:"region,omitempty"`
  428. VerificationLevel *VerificationLevel `json:"verification_level,omitempty"`
  429. }{g.Name, g.Region, g.VerificationLevel}
  430. body, err := s.Request("PATCH", EndpointGuild(guildID), data)
  431. if err != nil {
  432. return
  433. }
  434. err = unmarshal(body, &st)
  435. return
  436. }
  437. // GuildDelete deletes a Guild.
  438. // guildID : The ID of a Guild
  439. func (s *Session) GuildDelete(guildID string) (st *Guild, err error) {
  440. body, err := s.Request("DELETE", EndpointGuild(guildID), nil)
  441. if err != nil {
  442. return
  443. }
  444. err = unmarshal(body, &st)
  445. return
  446. }
  447. // GuildLeave leaves a Guild.
  448. // guildID : The ID of a Guild
  449. func (s *Session) GuildLeave(guildID string) (err error) {
  450. _, err = s.Request("DELETE", EndpointUserGuild("@me", guildID), nil)
  451. return
  452. }
  453. // GuildBans returns an array of User structures for all bans of a
  454. // given guild.
  455. // guildID : The ID of a Guild.
  456. func (s *Session) GuildBans(guildID string) (st []*User, err error) {
  457. body, err := s.Request("GET", EndpointGuildBans(guildID), nil)
  458. if err != nil {
  459. return
  460. }
  461. err = unmarshal(body, &st)
  462. return
  463. }
  464. // GuildBanCreate bans the given user from the given guild.
  465. // guildID : The ID of a Guild.
  466. // userID : The ID of a User
  467. // days : The number of days of previous comments to delete.
  468. func (s *Session) GuildBanCreate(guildID, userID string, days int) (err error) {
  469. uri := EndpointGuildBan(guildID, userID)
  470. if days > 0 {
  471. uri = fmt.Sprintf("%s?delete-message-days=%d", uri, days)
  472. }
  473. _, err = s.Request("PUT", uri, nil)
  474. return
  475. }
  476. // GuildBanDelete removes the given user from the guild bans
  477. // guildID : The ID of a Guild.
  478. // userID : The ID of a User
  479. func (s *Session) GuildBanDelete(guildID, userID string) (err error) {
  480. _, err = s.Request("DELETE", EndpointGuildBan(guildID, userID), nil)
  481. return
  482. }
  483. // GuildMembers returns a list of members for a guild.
  484. // guildID : The ID of a Guild.
  485. // offset : A number of members to skip
  486. // limit : max number of members to return (max 1000)
  487. func (s *Session) GuildMembers(guildID string, offset, limit int) (st []*Member, err error) {
  488. uri := EndpointGuildMembers(guildID)
  489. v := url.Values{}
  490. if offset > 0 {
  491. v.Set("offset", strconv.Itoa(offset))
  492. }
  493. if limit > 0 {
  494. v.Set("limit", strconv.Itoa(limit))
  495. }
  496. if len(v) > 0 {
  497. uri = fmt.Sprintf("%s?%s", uri, v.Encode())
  498. }
  499. body, err := s.Request("GET", uri, nil)
  500. if err != nil {
  501. return
  502. }
  503. err = unmarshal(body, &st)
  504. return
  505. }
  506. // GuildMember returns a member of a guild.
  507. // guildID : The ID of a Guild.
  508. // userID : The ID of a User
  509. func (s *Session) GuildMember(guildID, userID string) (st *Member, err error) {
  510. body, err := s.Request("GET", EndpointGuildMember(guildID, userID), nil)
  511. if err != nil {
  512. return
  513. }
  514. err = unmarshal(body, &st)
  515. return
  516. }
  517. // GuildMemberDelete removes the given user from the given guild.
  518. // guildID : The ID of a Guild.
  519. // userID : The ID of a User
  520. func (s *Session) GuildMemberDelete(guildID, userID string) (err error) {
  521. _, err = s.Request("DELETE", EndpointGuildMember(guildID, userID), nil)
  522. return
  523. }
  524. // GuildMemberEdit edits the roles of a member.
  525. // guildID : The ID of a Guild.
  526. // userID : The ID of a User.
  527. // roles : A list of role ID's to set on the member.
  528. func (s *Session) GuildMemberEdit(guildID, userID string, roles []string) (err error) {
  529. data := struct {
  530. Roles []string `json:"roles"`
  531. }{roles}
  532. _, err = s.Request("PATCH", EndpointGuildMember(guildID, userID), data)
  533. if err != nil {
  534. return
  535. }
  536. return
  537. }
  538. // GuildMemberMove moves a guild member from one voice channel to another/none
  539. // guildID : The ID of a Guild.
  540. // userID : The ID of a User.
  541. // channelID : The ID of a channel to move user to, or null?
  542. // NOTE : I am not entirely set on the name of this function and it may change
  543. // prior to the final 1.0.0 release of Discordgo
  544. func (s *Session) GuildMemberMove(guildID, userID, channelID string) (err error) {
  545. data := struct {
  546. ChannelID string `json:"channel_id"`
  547. }{channelID}
  548. _, err = s.Request("PATCH", EndpointGuildMember(guildID, userID), data)
  549. if err != nil {
  550. return
  551. }
  552. return
  553. }
  554. // GuildMemberNickname updates the nickname of a guild member
  555. // guildID : The ID of a guild
  556. // userID : The ID of a user
  557. func (s *Session) GuildMemberNickname(guildID, userID, nickname string) (err error) {
  558. data := struct {
  559. Nick string `json:"nick"`
  560. }{nickname}
  561. _, err = s.Request("PATCH", EndpointGuildMember(guildID, userID), data)
  562. return
  563. }
  564. // GuildChannels returns an array of Channel structures for all channels of a
  565. // given guild.
  566. // guildID : The ID of a Guild.
  567. func (s *Session) GuildChannels(guildID string) (st []*Channel, err error) {
  568. body, err := s.request("GET", EndpointGuildChannels(guildID), "", nil)
  569. if err != nil {
  570. return
  571. }
  572. err = unmarshal(body, &st)
  573. return
  574. }
  575. // GuildChannelCreate creates a new channel in the given guild
  576. // guildID : The ID of a Guild.
  577. // name : Name of the channel (2-100 chars length)
  578. // ctype : Tpye of the channel (voice or text)
  579. func (s *Session) GuildChannelCreate(guildID, name, ctype string) (st *Channel, err error) {
  580. data := struct {
  581. Name string `json:"name"`
  582. Type string `json:"type"`
  583. }{name, ctype}
  584. body, err := s.Request("POST", EndpointGuildChannels(guildID), data)
  585. if err != nil {
  586. return
  587. }
  588. err = unmarshal(body, &st)
  589. return
  590. }
  591. // GuildChannelsReorder updates the order of channels in a guild
  592. // guildID : The ID of a Guild.
  593. // channels : Updated channels.
  594. func (s *Session) GuildChannelsReorder(guildID string, channels []*Channel) (err error) {
  595. _, err = s.Request("PATCH", EndpointGuildChannels(guildID), channels)
  596. return
  597. }
  598. // GuildInvites returns an array of Invite structures for the given guild
  599. // guildID : The ID of a Guild.
  600. func (s *Session) GuildInvites(guildID string) (st []*Invite, err error) {
  601. body, err := s.Request("GET", EndpointGuildInvites(guildID), nil)
  602. if err != nil {
  603. return
  604. }
  605. err = unmarshal(body, &st)
  606. return
  607. }
  608. // GuildRoles returns all roles for a given guild.
  609. // guildID : The ID of a Guild.
  610. func (s *Session) GuildRoles(guildID string) (st []*Role, err error) {
  611. body, err := s.Request("GET", EndpointGuildRoles(guildID), nil)
  612. if err != nil {
  613. return
  614. }
  615. err = unmarshal(body, &st)
  616. return // TODO return pointer
  617. }
  618. // GuildRoleCreate returns a new Guild Role.
  619. // guildID: The ID of a Guild.
  620. func (s *Session) GuildRoleCreate(guildID string) (st *Role, err error) {
  621. body, err := s.Request("POST", EndpointGuildRoles(guildID), nil)
  622. if err != nil {
  623. return
  624. }
  625. err = unmarshal(body, &st)
  626. return
  627. }
  628. // GuildRoleEdit updates an existing Guild Role with new values
  629. // guildID : The ID of a Guild.
  630. // roleID : The ID of a Role.
  631. // name : The name of the Role.
  632. // color : The color of the role (decimal, not hex).
  633. // hoist : Whether to display the role's users separately.
  634. // perm : The permissions for the role.
  635. func (s *Session) GuildRoleEdit(guildID, roleID, name string, color int, hoist bool, perm int) (st *Role, err error) {
  636. // Prevent sending a color int that is too big.
  637. if color > 0xFFFFFF {
  638. err = fmt.Errorf("color value cannot be larger than 0xFFFFFF")
  639. }
  640. data := struct {
  641. Name string `json:"name"` // The color the role should have (as a decimal, not hex)
  642. Color int `json:"color"` // Whether to display the role's users separately
  643. Hoist bool `json:"hoist"` // The role's name (overwrites existing)
  644. Permissions int `json:"permissions"` // The overall permissions number of the role (overwrites existing)
  645. }{name, color, hoist, perm}
  646. body, err := s.Request("PATCH", EndpointGuildRole(guildID, roleID), data)
  647. if err != nil {
  648. return
  649. }
  650. err = unmarshal(body, &st)
  651. return
  652. }
  653. // GuildRoleReorder reoders guild roles
  654. // guildID : The ID of a Guild.
  655. // roles : A list of ordered roles.
  656. func (s *Session) GuildRoleReorder(guildID string, roles []*Role) (st []*Role, err error) {
  657. body, err := s.Request("PATCH", EndpointGuildRoles(guildID), roles)
  658. if err != nil {
  659. return
  660. }
  661. err = unmarshal(body, &st)
  662. return
  663. }
  664. // GuildRoleDelete deletes an existing role.
  665. // guildID : The ID of a Guild.
  666. // roleID : The ID of a Role.
  667. func (s *Session) GuildRoleDelete(guildID, roleID string) (err error) {
  668. _, err = s.Request("DELETE", EndpointGuildRole(guildID, roleID), nil)
  669. return
  670. }
  671. // GuildIntegrations returns an array of Integrations for a guild.
  672. // guildID : The ID of a Guild.
  673. func (s *Session) GuildIntegrations(guildID string) (st []*GuildIntegration, err error) {
  674. body, err := s.Request("GET", EndpointGuildIntegrations(guildID), nil)
  675. if err != nil {
  676. return
  677. }
  678. err = unmarshal(body, &st)
  679. return
  680. }
  681. // GuildIntegrationCreate creates a Guild Integration.
  682. // guildID : The ID of a Guild.
  683. // integrationType : The Integration type.
  684. // integrationID : The ID of an integration.
  685. func (s *Session) GuildIntegrationCreate(guildID, integrationType, integrationID string) (err error) {
  686. data := struct {
  687. Type string `json:"type"`
  688. ID string `json:"id"`
  689. }{integrationType, integrationID}
  690. _, err = s.Request("POST", EndpointGuildIntegrations(guildID), data)
  691. return
  692. }
  693. // GuildIntegrationEdit edits a Guild Integration.
  694. // guildID : The ID of a Guild.
  695. // integrationType : The Integration type.
  696. // integrationID : The ID of an integration.
  697. // expireBehavior : The behavior when an integration subscription lapses (see the integration object documentation).
  698. // expireGracePeriod : Period (in seconds) where the integration will ignore lapsed subscriptions.
  699. // enableEmoticons : Whether emoticons should be synced for this integration (twitch only currently).
  700. func (s *Session) GuildIntegrationEdit(guildID, integrationID string, expireBehavior, expireGracePeriod int, enableEmoticons bool) (err error) {
  701. data := struct {
  702. ExpireBehavior int `json:"expire_behavior"`
  703. ExpireGracePeriod int `json:"expire_grace_period"`
  704. EnableEmoticons bool `json:"enable_emoticons"`
  705. }{expireBehavior, expireGracePeriod, enableEmoticons}
  706. _, err = s.Request("PATCH", EndpointGuildIntegration(guildID, integrationID), data)
  707. return
  708. }
  709. // GuildIntegrationDelete removes the given integration from the Guild.
  710. // guildID : The ID of a Guild.
  711. // integrationID : The ID of an integration.
  712. func (s *Session) GuildIntegrationDelete(guildID, integrationID string) (err error) {
  713. _, err = s.Request("DELETE", EndpointGuildIntegration(guildID, integrationID), nil)
  714. return
  715. }
  716. // GuildIntegrationSync syncs an integration.
  717. // guildID : The ID of a Guild.
  718. // integrationID : The ID of an integration.
  719. func (s *Session) GuildIntegrationSync(guildID, integrationID string) (err error) {
  720. _, err = s.Request("POST", EndpointGuildIntegrationSync(guildID, integrationID), nil)
  721. return
  722. }
  723. // GuildIcon returns an image.Image of a guild icon.
  724. // guildID : The ID of a Guild.
  725. func (s *Session) GuildIcon(guildID string) (img image.Image, err error) {
  726. g, err := s.Guild(guildID)
  727. if err != nil {
  728. return
  729. }
  730. if g.Icon == "" {
  731. err = errors.New("Guild does not have an icon set.")
  732. return
  733. }
  734. body, err := s.Request("GET", EndpointGuildIcon(guildID, g.Icon), nil)
  735. if err != nil {
  736. return
  737. }
  738. img, _, err = image.Decode(bytes.NewReader(body))
  739. return
  740. }
  741. // GuildSplash returns an image.Image of a guild splash image.
  742. // guildID : The ID of a Guild.
  743. func (s *Session) GuildSplash(guildID string) (img image.Image, err error) {
  744. g, err := s.Guild(guildID)
  745. if err != nil {
  746. return
  747. }
  748. if g.Splash == "" {
  749. err = errors.New("Guild does not have a splash set.")
  750. return
  751. }
  752. body, err := s.Request("GET", EndpointGuildSplash(guildID, g.Splash), nil)
  753. if err != nil {
  754. return
  755. }
  756. img, _, err = image.Decode(bytes.NewReader(body))
  757. return
  758. }
  759. // GuildEmbed returns the embed for a Guild.
  760. // guildID : The ID of a Guild.
  761. func (s *Session) GuildEmbed(guildID string) (st *GuildEmbed, err error) {
  762. body, err := s.Request("GET", EndpointGuildEmbed(guildID), nil)
  763. if err != nil {
  764. return
  765. }
  766. err = unmarshal(body, &st)
  767. return
  768. }
  769. // GuildEmbedEdit returns the embed for a Guild.
  770. // guildID : The ID of a Guild.
  771. func (s *Session) GuildEmbedEdit(guildID string, enabled bool, channelID string) (err error) {
  772. data := GuildEmbed{enabled, channelID}
  773. _, err = s.Request("PATCH", EndpointGuildEmbed(guildID), data)
  774. return
  775. }
  776. // ------------------------------------------------------------------------------------------------
  777. // Functions specific to Discord Channels
  778. // ------------------------------------------------------------------------------------------------
  779. // Channel returns a Channel strucutre of a specific Channel.
  780. // channelID : The ID of the Channel you want returned.
  781. func (s *Session) Channel(channelID string) (st *Channel, err error) {
  782. body, err := s.Request("GET", EndpointChannel(channelID), nil)
  783. if err != nil {
  784. return
  785. }
  786. err = unmarshal(body, &st)
  787. return
  788. }
  789. // ChannelEdit edits the given channel
  790. // channelID : The ID of a Channel
  791. // name : The new name to assign the channel.
  792. func (s *Session) ChannelEdit(channelID, name string) (st *Channel, err error) {
  793. data := struct {
  794. Name string `json:"name"`
  795. }{name}
  796. body, err := s.Request("PATCH", EndpointChannel(channelID), data)
  797. if err != nil {
  798. return
  799. }
  800. err = unmarshal(body, &st)
  801. return
  802. }
  803. // ChannelDelete deletes the given channel
  804. // channelID : The ID of a Channel
  805. func (s *Session) ChannelDelete(channelID string) (st *Channel, err error) {
  806. body, err := s.Request("DELETE", EndpointChannel(channelID), nil)
  807. if err != nil {
  808. return
  809. }
  810. err = unmarshal(body, &st)
  811. return
  812. }
  813. // ChannelTyping broadcasts to all members that authenticated user is typing in
  814. // the given channel.
  815. // channelID : The ID of a Channel
  816. func (s *Session) ChannelTyping(channelID string) (err error) {
  817. _, err = s.Request("POST", EndpointChannelTyping(channelID), nil)
  818. return
  819. }
  820. // ChannelMessages returns an array of Message structures for messages within
  821. // a given channel.
  822. // channelID : The ID of a Channel.
  823. // limit : The number messages that can be returned. (max 100)
  824. // beforeID : If provided all messages returned will be before given ID.
  825. // afterID : If provided all messages returned will be after given ID.
  826. func (s *Session) ChannelMessages(channelID string, limit int, beforeID, afterID string) (st []*Message, err error) {
  827. uri := EndpointChannelMessages(channelID)
  828. v := url.Values{}
  829. if limit > 0 {
  830. v.Set("limit", strconv.Itoa(limit))
  831. }
  832. if afterID != "" {
  833. v.Set("after", afterID)
  834. }
  835. if beforeID != "" {
  836. v.Set("before", beforeID)
  837. }
  838. if len(v) > 0 {
  839. uri = fmt.Sprintf("%s?%s", uri, v.Encode())
  840. }
  841. body, err := s.Request("GET", uri, nil)
  842. if err != nil {
  843. return
  844. }
  845. err = unmarshal(body, &st)
  846. return
  847. }
  848. // ChannelMessage gets a single message by ID from a given channel.
  849. // channeld : The ID of a Channel
  850. // messageID : the ID of a Message
  851. func (s *Session) ChannelMessage(channelID, messageID string) (st *Message, err error) {
  852. response, err := s.Request("GET", EndpointChannelMessage(channelID, messageID), nil)
  853. if err != nil {
  854. return
  855. }
  856. err = unmarshal(response, &st)
  857. return
  858. }
  859. // ChannelMessageAck acknowledges and marks the given message as read
  860. // channeld : The ID of a Channel
  861. // messageID : the ID of a Message
  862. func (s *Session) ChannelMessageAck(channelID, messageID string) (err error) {
  863. _, err = s.request("POST", EndpointChannelMessageAck(channelID, messageID), "", nil)
  864. return
  865. }
  866. // channelMessageSend sends a message to the given channel.
  867. // channelID : The ID of a Channel.
  868. // content : The message to send.
  869. // tts : Whether to send the message with TTS.
  870. func (s *Session) channelMessageSend(channelID, content string, tts bool) (st *Message, err error) {
  871. // TODO: nonce string ?
  872. data := struct {
  873. Content string `json:"content"`
  874. TTS bool `json:"tts"`
  875. }{content, tts}
  876. // Send the message to the given channel
  877. response, err := s.Request("POST", EndpointChannelMessages(channelID), data)
  878. if err != nil {
  879. return
  880. }
  881. err = unmarshal(response, &st)
  882. return
  883. }
  884. // ChannelMessageSend sends a message to the given channel.
  885. // channelID : The ID of a Channel.
  886. // content : The message to send.
  887. func (s *Session) ChannelMessageSend(channelID string, content string) (st *Message, err error) {
  888. return s.channelMessageSend(channelID, content, false)
  889. }
  890. // ChannelMessageSendTTS sends a message to the given channel with Text to Speech.
  891. // channelID : The ID of a Channel.
  892. // content : The message to send.
  893. func (s *Session) ChannelMessageSendTTS(channelID string, content string) (st *Message, err error) {
  894. return s.channelMessageSend(channelID, content, true)
  895. }
  896. // ChannelMessageEdit edits an existing message, replacing it entirely with
  897. // the given content.
  898. // channeld : The ID of a Channel
  899. // messageID : the ID of a Message
  900. func (s *Session) ChannelMessageEdit(channelID, messageID, content string) (st *Message, err error) {
  901. data := struct {
  902. Content string `json:"content"`
  903. }{content}
  904. response, err := s.Request("PATCH", EndpointChannelMessage(channelID, messageID), data)
  905. if err != nil {
  906. return
  907. }
  908. err = unmarshal(response, &st)
  909. return
  910. }
  911. // ChannelMessageDelete deletes a message from the Channel.
  912. func (s *Session) ChannelMessageDelete(channelID, messageID string) (err error) {
  913. _, err = s.Request("DELETE", EndpointChannelMessage(channelID, messageID), nil)
  914. return
  915. }
  916. // ChannelMessagesBulkDelete bulk deletes the messages from the channel for the provided messageIDs.
  917. // If only one messageID is in the slice call channelMessageDelete funciton.
  918. // If the slice is empty do nothing.
  919. // channelID : The ID of the channel for the messages to delete.
  920. // messages : The IDs of the messages to be deleted. A slice of string IDs. A maximum of 100 messages.
  921. func (s *Session) ChannelMessagesBulkDelete(channelID string, messages []string) (err error) {
  922. if len(messages) == 0 {
  923. return
  924. }
  925. if len(messages) == 1 {
  926. err = s.ChannelMessageDelete(channelID, messages[0])
  927. return
  928. }
  929. if len(messages) > 100 {
  930. messages = messages[:100]
  931. }
  932. data := struct {
  933. Messages []string `json:"messages"`
  934. }{messages}
  935. _, err = s.Request("POST", EndpointChannelMessagesBulkDelete(channelID), data)
  936. return
  937. }
  938. // ChannelMessagePin pins a message within a given channel.
  939. // channelID: The ID of a channel.
  940. // messageID: The ID of a message.
  941. func (s *Session) ChannelMessagePin(channelID, messageID string) (err error) {
  942. _, err = s.Request("PUT", EndpointChannelMessagePin(channelID, messageID), nil)
  943. return
  944. }
  945. // ChannelMessageUnpin unpins a message within a given channel.
  946. // channelID: The ID of a channel.
  947. // messageID: The ID of a message.
  948. func (s *Session) ChannelMessageUnpin(channelID, messageID string) (err error) {
  949. _, err = s.Request("DELETE", EndpointChannelMessagePin(channelID, messageID), nil)
  950. return
  951. }
  952. // ChannelMessagesPinned returns an array of Message structures for pinned messages
  953. // within a given channel
  954. // channelID : The ID of a Channel.
  955. func (s *Session) ChannelMessagesPinned(channelID string) (st []*Message, err error) {
  956. body, err := s.Request("GET", EndpointChannelMessagesPins(channelID), nil)
  957. if err != nil {
  958. return
  959. }
  960. err = unmarshal(body, &st)
  961. return
  962. }
  963. // ChannelFileSend sends a file to the given channel.
  964. // channelID : The ID of a Channel.
  965. // io.Reader : A reader for the file contents.
  966. func (s *Session) ChannelFileSend(channelID, name string, r io.Reader) (st *Message, err error) {
  967. body := &bytes.Buffer{}
  968. bodywriter := multipart.NewWriter(body)
  969. writer, err := bodywriter.CreateFormFile("file", name)
  970. if err != nil {
  971. return nil, err
  972. }
  973. _, err = io.Copy(writer, r)
  974. if err != nil {
  975. return
  976. }
  977. err = bodywriter.Close()
  978. if err != nil {
  979. return
  980. }
  981. response, err := s.request("POST", EndpointChannelMessages(channelID), bodywriter.FormDataContentType(), body.Bytes())
  982. if err != nil {
  983. return
  984. }
  985. err = unmarshal(response, &st)
  986. return
  987. }
  988. // ChannelInvites returns an array of Invite structures for the given channel
  989. // channelID : The ID of a Channel
  990. func (s *Session) ChannelInvites(channelID string) (st []*Invite, err error) {
  991. body, err := s.Request("GET", EndpointChannelInvites(channelID), nil)
  992. if err != nil {
  993. return
  994. }
  995. err = unmarshal(body, &st)
  996. return
  997. }
  998. // ChannelInviteCreate creates a new invite for the given channel.
  999. // channelID : The ID of a Channel
  1000. // i : An Invite struct with the values MaxAge, MaxUses, Temporary,
  1001. // and XkcdPass defined.
  1002. func (s *Session) ChannelInviteCreate(channelID string, i Invite) (st *Invite, err error) {
  1003. data := struct {
  1004. MaxAge int `json:"max_age"`
  1005. MaxUses int `json:"max_uses"`
  1006. Temporary bool `json:"temporary"`
  1007. XKCDPass string `json:"xkcdpass"`
  1008. }{i.MaxAge, i.MaxUses, i.Temporary, i.XkcdPass}
  1009. body, err := s.Request("POST", EndpointChannelInvites(channelID), data)
  1010. if err != nil {
  1011. return
  1012. }
  1013. err = unmarshal(body, &st)
  1014. return
  1015. }
  1016. // ChannelPermissionSet creates a Permission Override for the given channel.
  1017. // NOTE: This func name may changed. Using Set instead of Create because
  1018. // you can both create a new override or update an override with this function.
  1019. func (s *Session) ChannelPermissionSet(channelID, targetID, targetType string, allow, deny int) (err error) {
  1020. data := struct {
  1021. ID string `json:"id"`
  1022. Type string `json:"type"`
  1023. Allow int `json:"allow"`
  1024. Deny int `json:"deny"`
  1025. }{targetID, targetType, allow, deny}
  1026. _, err = s.Request("PUT", EndpointChannelPermission(channelID, targetID), data)
  1027. return
  1028. }
  1029. // ChannelPermissionDelete deletes a specific permission override for the given channel.
  1030. // NOTE: Name of this func may change.
  1031. func (s *Session) ChannelPermissionDelete(channelID, targetID string) (err error) {
  1032. _, err = s.Request("DELETE", EndpointChannelPermission(channelID, targetID), nil)
  1033. return
  1034. }
  1035. // ------------------------------------------------------------------------------------------------
  1036. // Functions specific to Discord Invites
  1037. // ------------------------------------------------------------------------------------------------
  1038. // Invite returns an Invite structure of the given invite
  1039. // inviteID : The invite code (or maybe xkcdpass?)
  1040. func (s *Session) Invite(inviteID string) (st *Invite, err error) {
  1041. body, err := s.Request("GET", EndpointInvite(inviteID), nil)
  1042. if err != nil {
  1043. return
  1044. }
  1045. err = unmarshal(body, &st)
  1046. return
  1047. }
  1048. // InviteDelete deletes an existing invite
  1049. // inviteID : the code (or maybe xkcdpass?) of an invite
  1050. func (s *Session) InviteDelete(inviteID string) (st *Invite, err error) {
  1051. body, err := s.Request("DELETE", EndpointInvite(inviteID), nil)
  1052. if err != nil {
  1053. return
  1054. }
  1055. err = unmarshal(body, &st)
  1056. return
  1057. }
  1058. // InviteAccept accepts an Invite to a Guild or Channel
  1059. // inviteID : The invite code (or maybe xkcdpass?)
  1060. func (s *Session) InviteAccept(inviteID string) (st *Invite, err error) {
  1061. body, err := s.Request("POST", EndpointInvite(inviteID), nil)
  1062. if err != nil {
  1063. return
  1064. }
  1065. err = unmarshal(body, &st)
  1066. return
  1067. }
  1068. // ------------------------------------------------------------------------------------------------
  1069. // Functions specific to Discord Voice
  1070. // ------------------------------------------------------------------------------------------------
  1071. // VoiceRegions returns the voice server regions
  1072. func (s *Session) VoiceRegions() (st []*VoiceRegion, err error) {
  1073. body, err := s.Request("GET", EndpointVoiceRegions, nil)
  1074. if err != nil {
  1075. return
  1076. }
  1077. err = unmarshal(body, &st)
  1078. return
  1079. }
  1080. // VoiceICE returns the voice server ICE information
  1081. func (s *Session) VoiceICE() (st *VoiceICE, err error) {
  1082. body, err := s.Request("GET", EndpointVoiceIce, nil)
  1083. if err != nil {
  1084. return
  1085. }
  1086. err = unmarshal(body, &st)
  1087. return
  1088. }
  1089. // ------------------------------------------------------------------------------------------------
  1090. // Functions specific to Discord Websockets
  1091. // ------------------------------------------------------------------------------------------------
  1092. // Gateway returns the a websocket Gateway address
  1093. func (s *Session) Gateway() (gateway string, err error) {
  1094. response, err := s.Request("GET", EndpointGateway, nil)
  1095. if err != nil {
  1096. return
  1097. }
  1098. temp := struct {
  1099. URL string `json:"url"`
  1100. }{}
  1101. err = unmarshal(response, &temp)
  1102. if err != nil {
  1103. return
  1104. }
  1105. gateway = temp.URL
  1106. return
  1107. }