restapi.go 44 KB

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