restapi.go 56 KB

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