restapi.go 47 KB

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