restapi.go 56 KB

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