restapi.go 53 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846
  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. // GuildPruneCount Returns the number of members that would be removed in a prune operation.
  697. // Requires 'KICK_MEMBER' permission.
  698. // guildID : The ID of a Guild.
  699. // days : The number of days to count prune for (1 or more).
  700. func (s *Session) GuildPruneCount(guildID string, days uint32) (count uint32, err error) {
  701. count = 0
  702. if days <= 0 {
  703. err = errors.New("The number of days should be more than or equal to 1.")
  704. return
  705. }
  706. p := struct {
  707. Pruned uint32 `json:"pruned"`
  708. }{}
  709. uri := EndpointGuildPrune(guildID) + fmt.Sprintf("?days=%d", days)
  710. body, err := s.RequestWithBucketID("GET", uri, nil, EndpointGuildPrune(guildID))
  711. err = unmarshal(body, &p)
  712. if err != nil {
  713. return
  714. }
  715. count = p.Pruned
  716. return
  717. }
  718. // GuildPrune Begin as prune operation. Requires the 'KICK_MEMBERS' permission.
  719. // Returns an object with one 'pruned' key indicating the number of members that were removed in the prune operation.
  720. // guildID : The ID of a Guild.
  721. // days : The number of days to count prune for (1 or more).
  722. func (s *Session) GuildPrune(guildID string, days uint32) (count uint32, err error) {
  723. count = 0
  724. if days <= 0 {
  725. err = errors.New("The number of days should be more than or equal to 1.")
  726. return
  727. }
  728. data := struct {
  729. days uint32
  730. }{days}
  731. p := struct {
  732. Pruned uint32 `json:"pruned"`
  733. }{}
  734. body, err := s.RequestWithBucketID("POST", EndpointGuildPrune(guildID), data, EndpointGuildPrune(guildID))
  735. if err != nil {
  736. return
  737. }
  738. err = unmarshal(body, &p)
  739. if err != nil {
  740. return
  741. }
  742. count = p.Pruned
  743. return
  744. }
  745. // GuildIntegrations returns an array of Integrations for a guild.
  746. // guildID : The ID of a Guild.
  747. func (s *Session) GuildIntegrations(guildID string) (st []*GuildIntegration, err error) {
  748. body, err := s.RequestWithBucketID("GET", EndpointGuildIntegrations(guildID), nil, EndpointGuildIntegrations(guildID))
  749. if err != nil {
  750. return
  751. }
  752. err = unmarshal(body, &st)
  753. return
  754. }
  755. // GuildIntegrationCreate creates a Guild Integration.
  756. // guildID : The ID of a Guild.
  757. // integrationType : The Integration type.
  758. // integrationID : The ID of an integration.
  759. func (s *Session) GuildIntegrationCreate(guildID, integrationType, integrationID string) (err error) {
  760. data := struct {
  761. Type string `json:"type"`
  762. ID string `json:"id"`
  763. }{integrationType, integrationID}
  764. _, err = s.RequestWithBucketID("POST", EndpointGuildIntegrations(guildID), data, EndpointGuildIntegrations(guildID))
  765. return
  766. }
  767. // GuildIntegrationEdit edits a Guild Integration.
  768. // guildID : The ID of a Guild.
  769. // integrationType : The Integration type.
  770. // integrationID : The ID of an integration.
  771. // expireBehavior : The behavior when an integration subscription lapses (see the integration object documentation).
  772. // expireGracePeriod : Period (in seconds) where the integration will ignore lapsed subscriptions.
  773. // enableEmoticons : Whether emoticons should be synced for this integration (twitch only currently).
  774. func (s *Session) GuildIntegrationEdit(guildID, integrationID string, expireBehavior, expireGracePeriod int, enableEmoticons bool) (err error) {
  775. data := struct {
  776. ExpireBehavior int `json:"expire_behavior"`
  777. ExpireGracePeriod int `json:"expire_grace_period"`
  778. EnableEmoticons bool `json:"enable_emoticons"`
  779. }{expireBehavior, expireGracePeriod, enableEmoticons}
  780. _, err = s.RequestWithBucketID("PATCH", EndpointGuildIntegration(guildID, integrationID), data, EndpointGuildIntegration(guildID, ""))
  781. return
  782. }
  783. // GuildIntegrationDelete removes the given integration from the Guild.
  784. // guildID : The ID of a Guild.
  785. // integrationID : The ID of an integration.
  786. func (s *Session) GuildIntegrationDelete(guildID, integrationID string) (err error) {
  787. _, err = s.RequestWithBucketID("DELETE", EndpointGuildIntegration(guildID, integrationID), nil, EndpointGuildIntegration(guildID, ""))
  788. return
  789. }
  790. // GuildIntegrationSync syncs an integration.
  791. // guildID : The ID of a Guild.
  792. // integrationID : The ID of an integration.
  793. func (s *Session) GuildIntegrationSync(guildID, integrationID string) (err error) {
  794. _, err = s.RequestWithBucketID("POST", EndpointGuildIntegrationSync(guildID, integrationID), nil, EndpointGuildIntegration(guildID, ""))
  795. return
  796. }
  797. // GuildIcon returns an image.Image of a guild icon.
  798. // guildID : The ID of a Guild.
  799. func (s *Session) GuildIcon(guildID string) (img image.Image, err error) {
  800. g, err := s.Guild(guildID)
  801. if err != nil {
  802. return
  803. }
  804. if g.Icon == "" {
  805. err = errors.New("Guild does not have an icon set.")
  806. return
  807. }
  808. body, err := s.RequestWithBucketID("GET", EndpointGuildIcon(guildID, g.Icon), nil, EndpointGuildIcon(guildID, ""))
  809. if err != nil {
  810. return
  811. }
  812. img, _, err = image.Decode(bytes.NewReader(body))
  813. return
  814. }
  815. // GuildSplash returns an image.Image of a guild splash image.
  816. // guildID : The ID of a Guild.
  817. func (s *Session) GuildSplash(guildID string) (img image.Image, err error) {
  818. g, err := s.Guild(guildID)
  819. if err != nil {
  820. return
  821. }
  822. if g.Splash == "" {
  823. err = errors.New("Guild does not have a splash set.")
  824. return
  825. }
  826. body, err := s.RequestWithBucketID("GET", EndpointGuildSplash(guildID, g.Splash), nil, EndpointGuildSplash(guildID, ""))
  827. if err != nil {
  828. return
  829. }
  830. img, _, err = image.Decode(bytes.NewReader(body))
  831. return
  832. }
  833. // GuildEmbed returns the embed for a Guild.
  834. // guildID : The ID of a Guild.
  835. func (s *Session) GuildEmbed(guildID string) (st *GuildEmbed, err error) {
  836. body, err := s.RequestWithBucketID("GET", EndpointGuildEmbed(guildID), nil, EndpointGuildEmbed(guildID))
  837. if err != nil {
  838. return
  839. }
  840. err = unmarshal(body, &st)
  841. return
  842. }
  843. // GuildEmbedEdit returns the embed for a Guild.
  844. // guildID : The ID of a Guild.
  845. func (s *Session) GuildEmbedEdit(guildID string, enabled bool, channelID string) (err error) {
  846. data := GuildEmbed{enabled, channelID}
  847. _, err = s.RequestWithBucketID("PATCH", EndpointGuildEmbed(guildID), data, EndpointGuildEmbed(guildID))
  848. return
  849. }
  850. // ------------------------------------------------------------------------------------------------
  851. // Functions specific to Discord Channels
  852. // ------------------------------------------------------------------------------------------------
  853. // Channel returns a Channel strucutre of a specific Channel.
  854. // channelID : The ID of the Channel you want returned.
  855. func (s *Session) Channel(channelID string) (st *Channel, err error) {
  856. body, err := s.RequestWithBucketID("GET", EndpointChannel(channelID), nil, EndpointChannel(channelID))
  857. if err != nil {
  858. return
  859. }
  860. err = unmarshal(body, &st)
  861. return
  862. }
  863. // ChannelEdit edits the given channel
  864. // channelID : The ID of a Channel
  865. // name : The new name to assign the channel.
  866. func (s *Session) ChannelEdit(channelID, name string) (st *Channel, err error) {
  867. data := struct {
  868. Name string `json:"name"`
  869. }{name}
  870. body, err := s.RequestWithBucketID("PATCH", EndpointChannel(channelID), data, EndpointChannel(channelID))
  871. if err != nil {
  872. return
  873. }
  874. err = unmarshal(body, &st)
  875. return
  876. }
  877. // ChannelDelete deletes the given channel
  878. // channelID : The ID of a Channel
  879. func (s *Session) ChannelDelete(channelID string) (st *Channel, err error) {
  880. body, err := s.RequestWithBucketID("DELETE", EndpointChannel(channelID), nil, EndpointChannel(channelID))
  881. if err != nil {
  882. return
  883. }
  884. err = unmarshal(body, &st)
  885. return
  886. }
  887. // ChannelTyping broadcasts to all members that authenticated user is typing in
  888. // the given channel.
  889. // channelID : The ID of a Channel
  890. func (s *Session) ChannelTyping(channelID string) (err error) {
  891. _, err = s.RequestWithBucketID("POST", EndpointChannelTyping(channelID), nil, EndpointChannelTyping(channelID))
  892. return
  893. }
  894. // ChannelMessages returns an array of Message structures for messages within
  895. // a given channel.
  896. // channelID : The ID of a Channel.
  897. // limit : The number messages that can be returned. (max 100)
  898. // beforeID : If provided all messages returned will be before given ID.
  899. // afterID : If provided all messages returned will be after given ID.
  900. func (s *Session) ChannelMessages(channelID string, limit int, beforeID, afterID string) (st []*Message, err error) {
  901. uri := EndpointChannelMessages(channelID)
  902. v := url.Values{}
  903. if limit > 0 {
  904. v.Set("limit", strconv.Itoa(limit))
  905. }
  906. if afterID != "" {
  907. v.Set("after", afterID)
  908. }
  909. if beforeID != "" {
  910. v.Set("before", beforeID)
  911. }
  912. if len(v) > 0 {
  913. uri = fmt.Sprintf("%s?%s", uri, v.Encode())
  914. }
  915. body, err := s.RequestWithBucketID("GET", uri, nil, EndpointChannelMessages(channelID))
  916. if err != nil {
  917. return
  918. }
  919. err = unmarshal(body, &st)
  920. return
  921. }
  922. // ChannelMessage gets a single message by ID from a given channel.
  923. // channeld : The ID of a Channel
  924. // messageID : the ID of a Message
  925. func (s *Session) ChannelMessage(channelID, messageID string) (st *Message, err error) {
  926. response, err := s.RequestWithBucketID("GET", EndpointChannelMessage(channelID, messageID), nil, EndpointChannelMessage(channelID, ""))
  927. if err != nil {
  928. return
  929. }
  930. err = unmarshal(response, &st)
  931. return
  932. }
  933. // ChannelMessageAck acknowledges and marks the given message as read
  934. // channeld : The ID of a Channel
  935. // messageID : the ID of a Message
  936. // lastToken : token returned by last ack
  937. func (s *Session) ChannelMessageAck(channelID, messageID, lastToken string) (st *Ack, err error) {
  938. body, err := s.RequestWithBucketID("POST", EndpointChannelMessageAck(channelID, messageID), &Ack{Token: lastToken}, EndpointChannelMessageAck(channelID, ""))
  939. if err != nil {
  940. return
  941. }
  942. err = unmarshal(body, &st)
  943. return
  944. }
  945. // channelMessageSend sends a message to the given channel.
  946. // channelID : The ID of a Channel.
  947. // content : The message to send.
  948. // tts : Whether to send the message with TTS.
  949. func (s *Session) channelMessageSend(channelID, content string, tts bool) (st *Message, err error) {
  950. // TODO: nonce string ?
  951. data := struct {
  952. Content string `json:"content"`
  953. TTS bool `json:"tts"`
  954. }{content, tts}
  955. // Send the message to the given channel
  956. response, err := s.RequestWithBucketID("POST", EndpointChannelMessages(channelID), data, EndpointChannelMessages(channelID))
  957. if err != nil {
  958. return
  959. }
  960. err = unmarshal(response, &st)
  961. return
  962. }
  963. // ChannelMessageSend sends a message to the given channel.
  964. // channelID : The ID of a Channel.
  965. // content : The message to send.
  966. func (s *Session) ChannelMessageSend(channelID string, content string) (st *Message, err error) {
  967. return s.channelMessageSend(channelID, content, false)
  968. }
  969. // ChannelMessageSendTTS sends a message to the given channel with Text to Speech.
  970. // channelID : The ID of a Channel.
  971. // content : The message to send.
  972. func (s *Session) ChannelMessageSendTTS(channelID string, content string) (st *Message, err error) {
  973. return s.channelMessageSend(channelID, content, true)
  974. }
  975. // ChannelMessageSendEmbed sends a message to the given channel with embedded data (bot only).
  976. // channelID : The ID of a Channel.
  977. // embed : The embed data to send.
  978. func (s *Session) ChannelMessageSendEmbed(channelID string, embed *MessageEmbed) (st *Message, err error) {
  979. if embed != nil && embed.Type == "" {
  980. embed.Type = "rich"
  981. }
  982. data := struct {
  983. Embed *MessageEmbed `json:"embed"`
  984. }{embed}
  985. // Send the message to the given channel
  986. response, err := s.RequestWithBucketID("POST", EndpointChannelMessages(channelID), data, EndpointChannelMessages(channelID))
  987. if err != nil {
  988. return
  989. }
  990. err = unmarshal(response, &st)
  991. return
  992. }
  993. // ChannelMessageEdit edits an existing message, replacing it entirely with
  994. // the given content.
  995. // channeld : The ID of a Channel
  996. // messageID : the ID of a Message
  997. func (s *Session) ChannelMessageEdit(channelID, messageID, content string) (st *Message, err error) {
  998. data := struct {
  999. Content string `json:"content"`
  1000. }{content}
  1001. response, err := s.RequestWithBucketID("PATCH", EndpointChannelMessage(channelID, messageID), data, EndpointChannelMessage(channelID, ""))
  1002. if err != nil {
  1003. return
  1004. }
  1005. err = unmarshal(response, &st)
  1006. return
  1007. }
  1008. // ChannelMessageEditEmbed edits an existing message with embedded data (bot only).
  1009. // channelID : The ID of a Channel
  1010. // messageID : The ID of a Message
  1011. // embed : The embed data to send
  1012. func (s *Session) ChannelMessageEditEmbed(channelID, messageID string, embed *MessageEmbed) (st *Message, err error) {
  1013. if embed != nil && embed.Type == "" {
  1014. embed.Type = "rich"
  1015. }
  1016. data := struct {
  1017. Embed *MessageEmbed `json:"embed"`
  1018. }{embed}
  1019. response, err := s.RequestWithBucketID("PATCH", EndpointChannelMessage(channelID, messageID), data, EndpointChannelMessage(channelID, ""))
  1020. if err != nil {
  1021. return
  1022. }
  1023. err = unmarshal(response, &st)
  1024. return
  1025. }
  1026. // ChannelMessageDelete deletes a message from the Channel.
  1027. func (s *Session) ChannelMessageDelete(channelID, messageID string) (err error) {
  1028. _, err = s.RequestWithBucketID("DELETE", EndpointChannelMessage(channelID, messageID), nil, EndpointChannelMessage(channelID, ""))
  1029. return
  1030. }
  1031. // ChannelMessagesBulkDelete bulk deletes the messages from the channel for the provided messageIDs.
  1032. // If only one messageID is in the slice call channelMessageDelete funciton.
  1033. // If the slice is empty do nothing.
  1034. // channelID : The ID of the channel for the messages to delete.
  1035. // messages : The IDs of the messages to be deleted. A slice of string IDs. A maximum of 100 messages.
  1036. func (s *Session) ChannelMessagesBulkDelete(channelID string, messages []string) (err error) {
  1037. if len(messages) == 0 {
  1038. return
  1039. }
  1040. if len(messages) == 1 {
  1041. err = s.ChannelMessageDelete(channelID, messages[0])
  1042. return
  1043. }
  1044. if len(messages) > 100 {
  1045. messages = messages[:100]
  1046. }
  1047. data := struct {
  1048. Messages []string `json:"messages"`
  1049. }{messages}
  1050. _, err = s.RequestWithBucketID("POST", EndpointChannelMessagesBulkDelete(channelID), data, EndpointChannelMessagesBulkDelete(channelID))
  1051. return
  1052. }
  1053. // ChannelMessagePin pins a message within a given channel.
  1054. // channelID: The ID of a channel.
  1055. // messageID: The ID of a message.
  1056. func (s *Session) ChannelMessagePin(channelID, messageID string) (err error) {
  1057. _, err = s.RequestWithBucketID("PUT", EndpointChannelMessagePin(channelID, messageID), nil, EndpointChannelMessagePin(channelID, ""))
  1058. return
  1059. }
  1060. // ChannelMessageUnpin unpins a message within a given channel.
  1061. // channelID: The ID of a channel.
  1062. // messageID: The ID of a message.
  1063. func (s *Session) ChannelMessageUnpin(channelID, messageID string) (err error) {
  1064. _, err = s.RequestWithBucketID("DELETE", EndpointChannelMessagePin(channelID, messageID), nil, EndpointChannelMessagePin(channelID, ""))
  1065. return
  1066. }
  1067. // ChannelMessagesPinned returns an array of Message structures for pinned messages
  1068. // within a given channel
  1069. // channelID : The ID of a Channel.
  1070. func (s *Session) ChannelMessagesPinned(channelID string) (st []*Message, err error) {
  1071. body, err := s.RequestWithBucketID("GET", EndpointChannelMessagesPins(channelID), nil, EndpointChannelMessagesPins(channelID))
  1072. if err != nil {
  1073. return
  1074. }
  1075. err = unmarshal(body, &st)
  1076. return
  1077. }
  1078. // ChannelFileSend sends a file to the given channel.
  1079. // channelID : The ID of a Channel.
  1080. // name: The name of the file.
  1081. // io.Reader : A reader for the file contents.
  1082. func (s *Session) ChannelFileSend(channelID, name string, r io.Reader) (st *Message, err error) {
  1083. return s.ChannelFileSendWithMessage(channelID, "", name, r)
  1084. }
  1085. // ChannelFileSendWithMessage sends a file to the given channel with an message.
  1086. // channelID : The ID of a Channel.
  1087. // content: Optional Message content.
  1088. // name: The name of the file.
  1089. // io.Reader : A reader for the file contents.
  1090. func (s *Session) ChannelFileSendWithMessage(channelID, content string, name string, r io.Reader) (st *Message, err error) {
  1091. body := &bytes.Buffer{}
  1092. bodywriter := multipart.NewWriter(body)
  1093. if len(content) != 0 {
  1094. if err := bodywriter.WriteField("content", content); err != nil {
  1095. return nil, err
  1096. }
  1097. }
  1098. writer, err := bodywriter.CreateFormFile("file", name)
  1099. if err != nil {
  1100. return nil, err
  1101. }
  1102. _, err = io.Copy(writer, r)
  1103. if err != nil {
  1104. return
  1105. }
  1106. err = bodywriter.Close()
  1107. if err != nil {
  1108. return
  1109. }
  1110. response, err := s.request("POST", EndpointChannelMessages(channelID), bodywriter.FormDataContentType(), body.Bytes(), EndpointChannelMessages(channelID), 0)
  1111. if err != nil {
  1112. return
  1113. }
  1114. err = unmarshal(response, &st)
  1115. return
  1116. }
  1117. // ChannelInvites returns an array of Invite structures for the given channel
  1118. // channelID : The ID of a Channel
  1119. func (s *Session) ChannelInvites(channelID string) (st []*Invite, err error) {
  1120. body, err := s.RequestWithBucketID("GET", EndpointChannelInvites(channelID), nil, EndpointChannelInvites(channelID))
  1121. if err != nil {
  1122. return
  1123. }
  1124. err = unmarshal(body, &st)
  1125. return
  1126. }
  1127. // ChannelInviteCreate creates a new invite for the given channel.
  1128. // channelID : The ID of a Channel
  1129. // i : An Invite struct with the values MaxAge, MaxUses, Temporary,
  1130. // and XkcdPass defined.
  1131. func (s *Session) ChannelInviteCreate(channelID string, i Invite) (st *Invite, err error) {
  1132. data := struct {
  1133. MaxAge int `json:"max_age"`
  1134. MaxUses int `json:"max_uses"`
  1135. Temporary bool `json:"temporary"`
  1136. XKCDPass string `json:"xkcdpass"`
  1137. }{i.MaxAge, i.MaxUses, i.Temporary, i.XkcdPass}
  1138. body, err := s.RequestWithBucketID("POST", EndpointChannelInvites(channelID), data, EndpointChannelInvites(channelID))
  1139. if err != nil {
  1140. return
  1141. }
  1142. err = unmarshal(body, &st)
  1143. return
  1144. }
  1145. // ChannelPermissionSet creates a Permission Override for the given channel.
  1146. // NOTE: This func name may changed. Using Set instead of Create because
  1147. // you can both create a new override or update an override with this function.
  1148. func (s *Session) ChannelPermissionSet(channelID, targetID, targetType string, allow, deny int) (err error) {
  1149. data := struct {
  1150. ID string `json:"id"`
  1151. Type string `json:"type"`
  1152. Allow int `json:"allow"`
  1153. Deny int `json:"deny"`
  1154. }{targetID, targetType, allow, deny}
  1155. _, err = s.RequestWithBucketID("PUT", EndpointChannelPermission(channelID, targetID), data, EndpointChannelPermission(channelID, ""))
  1156. return
  1157. }
  1158. // ChannelPermissionDelete deletes a specific permission override for the given channel.
  1159. // NOTE: Name of this func may change.
  1160. func (s *Session) ChannelPermissionDelete(channelID, targetID string) (err error) {
  1161. _, err = s.RequestWithBucketID("DELETE", EndpointChannelPermission(channelID, targetID), nil, EndpointChannelPermission(channelID, ""))
  1162. return
  1163. }
  1164. // ------------------------------------------------------------------------------------------------
  1165. // Functions specific to Discord Invites
  1166. // ------------------------------------------------------------------------------------------------
  1167. // Invite returns an Invite structure of the given invite
  1168. // inviteID : The invite code (or maybe xkcdpass?)
  1169. func (s *Session) Invite(inviteID string) (st *Invite, err error) {
  1170. body, err := s.RequestWithBucketID("GET", EndpointInvite(inviteID), nil, EndpointInvite(""))
  1171. if err != nil {
  1172. return
  1173. }
  1174. err = unmarshal(body, &st)
  1175. return
  1176. }
  1177. // InviteDelete deletes an existing invite
  1178. // inviteID : the code (or maybe xkcdpass?) of an invite
  1179. func (s *Session) InviteDelete(inviteID string) (st *Invite, err error) {
  1180. body, err := s.RequestWithBucketID("DELETE", EndpointInvite(inviteID), nil, EndpointInvite(""))
  1181. if err != nil {
  1182. return
  1183. }
  1184. err = unmarshal(body, &st)
  1185. return
  1186. }
  1187. // InviteAccept accepts an Invite to a Guild or Channel
  1188. // inviteID : The invite code (or maybe xkcdpass?)
  1189. func (s *Session) InviteAccept(inviteID string) (st *Invite, err error) {
  1190. body, err := s.RequestWithBucketID("POST", EndpointInvite(inviteID), nil, EndpointInvite(""))
  1191. if err != nil {
  1192. return
  1193. }
  1194. err = unmarshal(body, &st)
  1195. return
  1196. }
  1197. // ------------------------------------------------------------------------------------------------
  1198. // Functions specific to Discord Voice
  1199. // ------------------------------------------------------------------------------------------------
  1200. // VoiceRegions returns the voice server regions
  1201. func (s *Session) VoiceRegions() (st []*VoiceRegion, err error) {
  1202. body, err := s.RequestWithBucketID("GET", EndpointVoiceRegions, nil, EndpointVoiceRegions)
  1203. if err != nil {
  1204. return
  1205. }
  1206. err = unmarshal(body, &st)
  1207. return
  1208. }
  1209. // VoiceICE returns the voice server ICE information
  1210. func (s *Session) VoiceICE() (st *VoiceICE, err error) {
  1211. body, err := s.RequestWithBucketID("GET", EndpointVoiceIce, nil, EndpointVoiceIce)
  1212. if err != nil {
  1213. return
  1214. }
  1215. err = unmarshal(body, &st)
  1216. return
  1217. }
  1218. // ------------------------------------------------------------------------------------------------
  1219. // Functions specific to Discord Websockets
  1220. // ------------------------------------------------------------------------------------------------
  1221. // Gateway returns the a websocket Gateway address
  1222. func (s *Session) Gateway() (gateway string, err error) {
  1223. response, err := s.RequestWithBucketID("GET", EndpointGateway, nil, EndpointGateway)
  1224. if err != nil {
  1225. return
  1226. }
  1227. temp := struct {
  1228. URL string `json:"url"`
  1229. }{}
  1230. err = unmarshal(response, &temp)
  1231. if err != nil {
  1232. return
  1233. }
  1234. gateway = temp.URL
  1235. return
  1236. }
  1237. // Functions specific to Webhooks
  1238. // WebhookCreate returns a new Webhook.
  1239. // channelID: The ID of a Channel.
  1240. // name : The name of the webhook.
  1241. // avatar : The avatar of the webhook.
  1242. func (s *Session) WebhookCreate(channelID, name, avatar string) (st *Webhook, err error) {
  1243. data := struct {
  1244. Name string `json:"name"`
  1245. Avatar string `json:"avatar,omitempty"`
  1246. }{name, avatar}
  1247. body, err := s.RequestWithBucketID("POST", EndpointChannelWebhooks(channelID), data, EndpointChannelWebhooks(channelID))
  1248. if err != nil {
  1249. return
  1250. }
  1251. err = unmarshal(body, &st)
  1252. return
  1253. }
  1254. // ChannelWebhooks returns all webhooks for a given channel.
  1255. // channelID: The ID of a channel.
  1256. func (s *Session) ChannelWebhooks(channelID string) (st []*Webhook, err error) {
  1257. body, err := s.RequestWithBucketID("GET", EndpointChannelWebhooks(channelID), nil, EndpointChannelWebhooks(channelID))
  1258. if err != nil {
  1259. return
  1260. }
  1261. err = unmarshal(body, &st)
  1262. return
  1263. }
  1264. // GuildWebhooks returns all webhooks for a given guild.
  1265. // guildID: The ID of a Guild.
  1266. func (s *Session) GuildWebhooks(guildID string) (st []*Webhook, err error) {
  1267. body, err := s.RequestWithBucketID("GET", EndpointGuildWebhooks(guildID), nil, EndpointGuildWebhooks(guildID))
  1268. if err != nil {
  1269. return
  1270. }
  1271. err = unmarshal(body, &st)
  1272. return
  1273. }
  1274. // Webhook returns a webhook for a given ID
  1275. // webhookID: The ID of a webhook.
  1276. func (s *Session) Webhook(webhookID string) (st *Webhook, err error) {
  1277. body, err := s.RequestWithBucketID("GET", EndpointWebhook(webhookID), nil, EndpointWebhooks)
  1278. if err != nil {
  1279. return
  1280. }
  1281. err = unmarshal(body, &st)
  1282. return
  1283. }
  1284. // WebhookWithToken returns a webhook for a given ID
  1285. // webhookID: The ID of a webhook.
  1286. // token : The auth token for the webhook.
  1287. func (s *Session) WebhookWithToken(webhookID, token string) (st *Webhook, err error) {
  1288. body, err := s.RequestWithBucketID("GET", EndpointWebhookToken(webhookID, token), nil, EndpointWebhookToken("", ""))
  1289. if err != nil {
  1290. return
  1291. }
  1292. err = unmarshal(body, &st)
  1293. return
  1294. }
  1295. // WebhookEdit updates an existing Webhook.
  1296. // webhookID: The ID of a webhook.
  1297. // name : The name of the webhook.
  1298. // avatar : The avatar of the webhook.
  1299. func (s *Session) WebhookEdit(webhookID, name, avatar string) (st *Role, err error) {
  1300. data := struct {
  1301. Name string `json:"name,omitempty"`
  1302. Avatar string `json:"avatar,omitempty"`
  1303. }{name, avatar}
  1304. body, err := s.RequestWithBucketID("PATCH", EndpointWebhook(webhookID), data, EndpointWebhooks)
  1305. if err != nil {
  1306. return
  1307. }
  1308. err = unmarshal(body, &st)
  1309. return
  1310. }
  1311. // WebhookEditWithToken updates an existing Webhook with an auth token.
  1312. // webhookID: The ID of a webhook.
  1313. // token : The auth token for the webhook.
  1314. // name : The name of the webhook.
  1315. // avatar : The avatar of the webhook.
  1316. func (s *Session) WebhookEditWithToken(webhookID, token, name, avatar string) (st *Role, err error) {
  1317. data := struct {
  1318. Name string `json:"name,omitempty"`
  1319. Avatar string `json:"avatar,omitempty"`
  1320. }{name, avatar}
  1321. body, err := s.RequestWithBucketID("PATCH", EndpointWebhookToken(webhookID, token), data, EndpointWebhookToken("", ""))
  1322. if err != nil {
  1323. return
  1324. }
  1325. err = unmarshal(body, &st)
  1326. return
  1327. }
  1328. // WebhookDelete deletes a webhook for a given ID
  1329. // webhookID: The ID of a webhook.
  1330. func (s *Session) WebhookDelete(webhookID string) (st *Webhook, err error) {
  1331. body, err := s.RequestWithBucketID("DELETE", EndpointWebhook(webhookID), nil, EndpointWebhooks)
  1332. if err != nil {
  1333. return
  1334. }
  1335. err = unmarshal(body, &st)
  1336. return
  1337. }
  1338. // WebhookDeleteWithToken deletes a webhook for a given ID with an auth token.
  1339. // webhookID: The ID of a webhook.
  1340. // token : The auth token for the webhook.
  1341. func (s *Session) WebhookDeleteWithToken(webhookID, token string) (st *Webhook, err error) {
  1342. body, err := s.RequestWithBucketID("DELETE", EndpointWebhookToken(webhookID, token), nil, EndpointWebhookToken("", ""))
  1343. if err != nil {
  1344. return
  1345. }
  1346. err = unmarshal(body, &st)
  1347. return
  1348. }
  1349. // WebhookExecute executes a webhook.
  1350. // webhookID: The ID of a webhook.
  1351. // token : The auth token for the webhook
  1352. func (s *Session) WebhookExecute(webhookID, token string, wait bool, data *WebhookParams) (err error) {
  1353. uri := EndpointWebhookToken(webhookID, token)
  1354. if wait {
  1355. uri += "?wait=true"
  1356. }
  1357. _, err = s.RequestWithBucketID("POST", uri, data, EndpointWebhookToken("", ""))
  1358. return
  1359. }
  1360. // MessageReactionAdd creates an emoji reaction to a message.
  1361. // channelID : The channel ID.
  1362. // messageID : The message ID.
  1363. // emojiID : Either the unicode emoji for the reaction, or a guild emoji identifier.
  1364. func (s *Session) MessageReactionAdd(channelID, messageID, emojiID string) error {
  1365. _, err := s.RequestWithBucketID("PUT", EndpointMessageReaction(channelID, messageID, emojiID, "@me"), nil, EndpointMessageReaction(channelID, "", "", ""))
  1366. return err
  1367. }
  1368. // MessageReactionRemove deletes an emoji reaction to a message.
  1369. // channelID : The channel ID.
  1370. // messageID : The message ID.
  1371. // emojiID : Either the unicode emoji for the reaction, or a guild emoji identifier.
  1372. // userID : @me or ID of the user to delete the reaction for.
  1373. func (s *Session) MessageReactionRemove(channelID, messageID, emojiID, userID string) error {
  1374. _, err := s.RequestWithBucketID("DELETE", EndpointMessageReaction(channelID, messageID, emojiID, userID), nil, EndpointMessageReaction(channelID, "", "", ""))
  1375. return err
  1376. }
  1377. // MessageReactions gets all the users reactions for a specific emoji.
  1378. // channelID : The channel ID.
  1379. // messageID : The message ID.
  1380. // emojiID : Either the unicode emoji for the reaction, or a guild emoji identifier.
  1381. // limit : max number of users to return (max 100)
  1382. func (s *Session) MessageReactions(channelID, messageID, emojiID string, limit int) (st []*User, err error) {
  1383. uri := EndpointMessageReactions(channelID, messageID, emojiID)
  1384. v := url.Values{}
  1385. if limit > 0 {
  1386. v.Set("limit", strconv.Itoa(limit))
  1387. }
  1388. if len(v) > 0 {
  1389. uri = fmt.Sprintf("%s?%s", uri, v.Encode())
  1390. }
  1391. body, err := s.RequestWithBucketID("GET", uri, nil, EndpointMessageReaction(channelID, "", "", ""))
  1392. if err != nil {
  1393. return
  1394. }
  1395. err = unmarshal(body, &st)
  1396. return
  1397. }
  1398. // ------------------------------------------------------------------------------------------------
  1399. // Functions specific to Discord Relationships (Friends list)
  1400. // ------------------------------------------------------------------------------------------------
  1401. // RelationshipsGet returns an array of all the relationships of the user.
  1402. func (s *Session) RelationshipsGet() (r []*Relationship, err error) {
  1403. body, err := s.RequestWithBucketID("GET", EndpointRelationships(), nil, EndpointRelationships())
  1404. if err != nil {
  1405. return
  1406. }
  1407. err = unmarshal(body, &r)
  1408. return
  1409. }
  1410. // relationshipCreate creates a new relationship. (I.e. send or accept a friend request, block a user.)
  1411. // relationshipType : 1 = friend, 2 = blocked, 3 = incoming friend req, 4 = sent friend req
  1412. func (s *Session) relationshipCreate(userID string, relationshipType int) (err error) {
  1413. data := struct {
  1414. Type int `json:"type"`
  1415. }{relationshipType}
  1416. _, err = s.RequestWithBucketID("PUT", EndpointRelationship(userID), data, EndpointRelationships())
  1417. return
  1418. }
  1419. // RelationshipFriendRequestSend sends a friend request to a user.
  1420. // userID: ID of the user.
  1421. func (s *Session) RelationshipFriendRequestSend(userID string) (err error) {
  1422. err = s.relationshipCreate(userID, 4)
  1423. return
  1424. }
  1425. // RelationshipFriendRequestAccept accepts a friend request from a user.
  1426. // userID: ID of the user.
  1427. func (s *Session) RelationshipFriendRequestAccept(userID string) (err error) {
  1428. err = s.relationshipCreate(userID, 1)
  1429. return
  1430. }
  1431. // RelationshipUserBlock blocks a user.
  1432. // userID: ID of the user.
  1433. func (s *Session) RelationshipUserBlock(userID string) (err error) {
  1434. err = s.relationshipCreate(userID, 2)
  1435. return
  1436. }
  1437. // RelationshipDelete removes the relationship with a user.
  1438. // userID: ID of the user.
  1439. func (s *Session) RelationshipDelete(userID string) (err error) {
  1440. _, err = s.RequestWithBucketID("DELETE", EndpointRelationship(userID), nil, EndpointRelationships())
  1441. return
  1442. }
  1443. // RelationshipsMutualGet returns an array of all the users both @me and the given user is friends with.
  1444. // userID: ID of the user.
  1445. func (s *Session) RelationshipsMutualGet(userID string) (mf []*User, err error) {
  1446. body, err := s.RequestWithBucketID("GET", EndpointRelationshipsMutual(userID), nil, EndpointRelationshipsMutual(userID))
  1447. if err != nil {
  1448. return
  1449. }
  1450. err = unmarshal(body, &mf)
  1451. return
  1452. }