restapi.go 55 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911
  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,omitempty"`
  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. body, err := s.RequestWithBucketID("PATCH", EndpointGuild(guildID), g, EndpointGuild(guildID))
  499. if err != nil {
  500. return
  501. }
  502. err = unmarshal(body, &st)
  503. return
  504. }
  505. // GuildDelete deletes a Guild.
  506. // guildID : The ID of a Guild
  507. func (s *Session) GuildDelete(guildID string) (st *Guild, err error) {
  508. body, err := s.RequestWithBucketID("DELETE", EndpointGuild(guildID), nil, EndpointGuild(guildID))
  509. if err != nil {
  510. return
  511. }
  512. err = unmarshal(body, &st)
  513. return
  514. }
  515. // GuildLeave leaves a Guild.
  516. // guildID : The ID of a Guild
  517. func (s *Session) GuildLeave(guildID string) (err error) {
  518. _, err = s.RequestWithBucketID("DELETE", EndpointUserGuild("@me", guildID), nil, EndpointUserGuild("", guildID))
  519. return
  520. }
  521. // GuildBans returns an array of User structures for all bans of a
  522. // given guild.
  523. // guildID : The ID of a Guild.
  524. func (s *Session) GuildBans(guildID string) (st []*GuildBan, err error) {
  525. body, err := s.RequestWithBucketID("GET", EndpointGuildBans(guildID), nil, EndpointGuildBans(guildID))
  526. if err != nil {
  527. return
  528. }
  529. err = unmarshal(body, &st)
  530. return
  531. }
  532. // GuildBanCreate bans the given user from the given guild.
  533. // guildID : The ID of a Guild.
  534. // userID : The ID of a User
  535. // days : The number of days of previous comments to delete.
  536. func (s *Session) GuildBanCreate(guildID, userID string, days int) (err error) {
  537. uri := EndpointGuildBan(guildID, userID)
  538. if days > 0 {
  539. uri = fmt.Sprintf("%s?delete-message-days=%d", uri, days)
  540. }
  541. _, err = s.RequestWithBucketID("PUT", uri, nil, EndpointGuildBan(guildID, ""))
  542. return
  543. }
  544. // GuildBanDelete removes the given user from the guild bans
  545. // guildID : The ID of a Guild.
  546. // userID : The ID of a User
  547. func (s *Session) GuildBanDelete(guildID, userID string) (err error) {
  548. _, err = s.RequestWithBucketID("DELETE", EndpointGuildBan(guildID, userID), nil, EndpointGuildBan(guildID, ""))
  549. return
  550. }
  551. // GuildMembers returns a list of members for a guild.
  552. // guildID : The ID of a Guild.
  553. // after : The id of the member to return members after
  554. // limit : max number of members to return (max 1000)
  555. func (s *Session) GuildMembers(guildID string, after string, limit int) (st []*Member, err error) {
  556. uri := EndpointGuildMembers(guildID)
  557. v := url.Values{}
  558. if after != "" {
  559. v.Set("after", after)
  560. }
  561. if limit > 0 {
  562. v.Set("limit", strconv.Itoa(limit))
  563. }
  564. if len(v) > 0 {
  565. uri = fmt.Sprintf("%s?%s", uri, v.Encode())
  566. }
  567. body, err := s.RequestWithBucketID("GET", uri, nil, EndpointGuildMembers(guildID))
  568. if err != nil {
  569. return
  570. }
  571. err = unmarshal(body, &st)
  572. return
  573. }
  574. // GuildMember returns a member of a guild.
  575. // guildID : The ID of a Guild.
  576. // userID : The ID of a User
  577. func (s *Session) GuildMember(guildID, userID string) (st *Member, err error) {
  578. body, err := s.RequestWithBucketID("GET", EndpointGuildMember(guildID, userID), nil, EndpointGuildMember(guildID, ""))
  579. if err != nil {
  580. return
  581. }
  582. err = unmarshal(body, &st)
  583. return
  584. }
  585. // GuildMemberDelete removes the given user from the given guild.
  586. // guildID : The ID of a Guild.
  587. // userID : The ID of a User
  588. func (s *Session) GuildMemberDelete(guildID, userID string) (err error) {
  589. _, err = s.RequestWithBucketID("DELETE", EndpointGuildMember(guildID, userID), nil, EndpointGuildMember(guildID, ""))
  590. return
  591. }
  592. // GuildMemberEdit edits the roles of a member.
  593. // guildID : The ID of a Guild.
  594. // userID : The ID of a User.
  595. // roles : A list of role ID's to set on the member.
  596. func (s *Session) GuildMemberEdit(guildID, userID string, roles []string) (err error) {
  597. data := struct {
  598. Roles []string `json:"roles"`
  599. }{roles}
  600. _, err = s.RequestWithBucketID("PATCH", EndpointGuildMember(guildID, userID), data, EndpointGuildMember(guildID, ""))
  601. if err != nil {
  602. return
  603. }
  604. return
  605. }
  606. // GuildMemberMove moves a guild member from one voice channel to another/none
  607. // guildID : The ID of a Guild.
  608. // userID : The ID of a User.
  609. // channelID : The ID of a channel to move user to, or null?
  610. // NOTE : I am not entirely set on the name of this function and it may change
  611. // prior to the final 1.0.0 release of Discordgo
  612. func (s *Session) GuildMemberMove(guildID, userID, channelID string) (err error) {
  613. data := struct {
  614. ChannelID string `json:"channel_id"`
  615. }{channelID}
  616. _, err = s.RequestWithBucketID("PATCH", EndpointGuildMember(guildID, userID), data, EndpointGuildMember(guildID, ""))
  617. if err != nil {
  618. return
  619. }
  620. return
  621. }
  622. // GuildMemberNickname updates the nickname of a guild member
  623. // guildID : The ID of a guild
  624. // userID : The ID of a user
  625. // userID : The ID of a user or "@me" which is a shortcut of the current user ID
  626. func (s *Session) GuildMemberNickname(guildID, userID, nickname string) (err error) {
  627. data := struct {
  628. Nick string `json:"nick"`
  629. }{nickname}
  630. if userID == "@me" {
  631. userID += "/nick"
  632. }
  633. _, err = s.RequestWithBucketID("PATCH", EndpointGuildMember(guildID, userID), data, EndpointGuildMember(guildID, ""))
  634. return
  635. }
  636. // GuildMemberRoleAdd adds the specified role to a given member
  637. // guildID : The ID of a Guild.
  638. // userID : The ID of a User.
  639. // roleID : The ID of a Role to be assigned to the user.
  640. func (s *Session) GuildMemberRoleAdd(guildID, userID, roleID string) (err error) {
  641. _, err = s.RequestWithBucketID("PUT", EndpointGuildMemberRole(guildID, userID, roleID), nil, EndpointGuildMemberRole(guildID, "", ""))
  642. return
  643. }
  644. // GuildMemberRoleRemove removes the specified role to a given member
  645. // guildID : The ID of a Guild.
  646. // userID : The ID of a User.
  647. // roleID : The ID of a Role to be removed from the user.
  648. func (s *Session) GuildMemberRoleRemove(guildID, userID, roleID string) (err error) {
  649. _, err = s.RequestWithBucketID("DELETE", EndpointGuildMemberRole(guildID, userID, roleID), nil, EndpointGuildMemberRole(guildID, "", ""))
  650. return
  651. }
  652. // GuildChannels returns an array of Channel structures for all channels of a
  653. // given guild.
  654. // guildID : The ID of a Guild.
  655. func (s *Session) GuildChannels(guildID string) (st []*Channel, err error) {
  656. body, err := s.request("GET", EndpointGuildChannels(guildID), "", nil, EndpointGuildChannels(guildID), 0)
  657. if err != nil {
  658. return
  659. }
  660. err = unmarshal(body, &st)
  661. return
  662. }
  663. // GuildChannelCreate creates a new channel in the given guild
  664. // guildID : The ID of a Guild.
  665. // name : Name of the channel (2-100 chars length)
  666. // ctype : Tpye of the channel (voice or text)
  667. func (s *Session) GuildChannelCreate(guildID, name, ctype string) (st *Channel, err error) {
  668. data := struct {
  669. Name string `json:"name"`
  670. Type string `json:"type"`
  671. }{name, ctype}
  672. body, err := s.RequestWithBucketID("POST", EndpointGuildChannels(guildID), data, EndpointGuildChannels(guildID))
  673. if err != nil {
  674. return
  675. }
  676. err = unmarshal(body, &st)
  677. return
  678. }
  679. // GuildChannelsReorder updates the order of channels in a guild
  680. // guildID : The ID of a Guild.
  681. // channels : Updated channels.
  682. func (s *Session) GuildChannelsReorder(guildID string, channels []*Channel) (err error) {
  683. _, err = s.RequestWithBucketID("PATCH", EndpointGuildChannels(guildID), channels, EndpointGuildChannels(guildID))
  684. return
  685. }
  686. // GuildInvites returns an array of Invite structures for the given guild
  687. // guildID : The ID of a Guild.
  688. func (s *Session) GuildInvites(guildID string) (st []*Invite, err error) {
  689. body, err := s.RequestWithBucketID("GET", EndpointGuildInvites(guildID), nil, EndpointGuildInivtes(guildID))
  690. if err != nil {
  691. return
  692. }
  693. err = unmarshal(body, &st)
  694. return
  695. }
  696. // GuildRoles returns all roles for a given guild.
  697. // guildID : The ID of a Guild.
  698. func (s *Session) GuildRoles(guildID string) (st []*Role, err error) {
  699. body, err := s.RequestWithBucketID("GET", EndpointGuildRoles(guildID), nil, EndpointGuildRoles(guildID))
  700. if err != nil {
  701. return
  702. }
  703. err = unmarshal(body, &st)
  704. return // TODO return pointer
  705. }
  706. // GuildRoleCreate returns a new Guild Role.
  707. // guildID: The ID of a Guild.
  708. func (s *Session) GuildRoleCreate(guildID string) (st *Role, err error) {
  709. body, err := s.RequestWithBucketID("POST", EndpointGuildRoles(guildID), nil, EndpointGuildRoles(guildID))
  710. if err != nil {
  711. return
  712. }
  713. err = unmarshal(body, &st)
  714. return
  715. }
  716. // GuildRoleEdit updates an existing Guild Role with new values
  717. // guildID : The ID of a Guild.
  718. // roleID : The ID of a Role.
  719. // name : The name of the Role.
  720. // color : The color of the role (decimal, not hex).
  721. // hoist : Whether to display the role's users separately.
  722. // perm : The permissions for the role.
  723. // mention : Whether this role is mentionable
  724. func (s *Session) GuildRoleEdit(guildID, roleID, name string, color int, hoist bool, perm int, mention bool) (st *Role, err error) {
  725. // Prevent sending a color int that is too big.
  726. if color > 0xFFFFFF {
  727. err = fmt.Errorf("color value cannot be larger than 0xFFFFFF")
  728. }
  729. data := struct {
  730. Name string `json:"name"` // The role's name (overwrites existing)
  731. Color int `json:"color"` // The color the role should have (as a decimal, not hex)
  732. Hoist bool `json:"hoist"` // Whether to display the role's users separately
  733. Permissions int `json:"permissions"` // The overall permissions number of the role (overwrites existing)
  734. Mentionable bool `json:"mentionable"` // Whether this role is mentionable
  735. }{name, color, hoist, perm, mention}
  736. body, err := s.RequestWithBucketID("PATCH", EndpointGuildRole(guildID, roleID), data, EndpointGuildRole(guildID, ""))
  737. if err != nil {
  738. return
  739. }
  740. err = unmarshal(body, &st)
  741. return
  742. }
  743. // GuildRoleReorder reoders guild roles
  744. // guildID : The ID of a Guild.
  745. // roles : A list of ordered roles.
  746. func (s *Session) GuildRoleReorder(guildID string, roles []*Role) (st []*Role, err error) {
  747. body, err := s.RequestWithBucketID("PATCH", EndpointGuildRoles(guildID), roles, EndpointGuildRoles(guildID))
  748. if err != nil {
  749. return
  750. }
  751. err = unmarshal(body, &st)
  752. return
  753. }
  754. // GuildRoleDelete deletes an existing role.
  755. // guildID : The ID of a Guild.
  756. // roleID : The ID of a Role.
  757. func (s *Session) GuildRoleDelete(guildID, roleID string) (err error) {
  758. _, err = s.RequestWithBucketID("DELETE", EndpointGuildRole(guildID, roleID), nil, EndpointGuildRole(guildID, ""))
  759. return
  760. }
  761. // GuildPruneCount Returns the number of members that would be removed in a prune operation.
  762. // Requires 'KICK_MEMBER' permission.
  763. // guildID : The ID of a Guild.
  764. // days : The number of days to count prune for (1 or more).
  765. func (s *Session) GuildPruneCount(guildID string, days uint32) (count uint32, err error) {
  766. count = 0
  767. if days <= 0 {
  768. err = errors.New("the number of days should be more than or equal to 1")
  769. return
  770. }
  771. p := struct {
  772. Pruned uint32 `json:"pruned"`
  773. }{}
  774. uri := EndpointGuildPrune(guildID) + fmt.Sprintf("?days=%d", days)
  775. body, err := s.RequestWithBucketID("GET", uri, nil, EndpointGuildPrune(guildID))
  776. err = unmarshal(body, &p)
  777. if err != nil {
  778. return
  779. }
  780. count = p.Pruned
  781. return
  782. }
  783. // GuildPrune Begin as prune operation. Requires the 'KICK_MEMBERS' permission.
  784. // Returns an object with one 'pruned' key indicating the number of members that were removed in the prune operation.
  785. // guildID : The ID of a Guild.
  786. // days : The number of days to count prune for (1 or more).
  787. func (s *Session) GuildPrune(guildID string, days uint32) (count uint32, err error) {
  788. count = 0
  789. if days <= 0 {
  790. err = errors.New("the number of days should be more than or equal to 1")
  791. return
  792. }
  793. data := struct {
  794. days uint32
  795. }{days}
  796. p := struct {
  797. Pruned uint32 `json:"pruned"`
  798. }{}
  799. body, err := s.RequestWithBucketID("POST", EndpointGuildPrune(guildID), data, EndpointGuildPrune(guildID))
  800. if err != nil {
  801. return
  802. }
  803. err = unmarshal(body, &p)
  804. if err != nil {
  805. return
  806. }
  807. count = p.Pruned
  808. return
  809. }
  810. // GuildIntegrations returns an array of Integrations for a guild.
  811. // guildID : The ID of a Guild.
  812. func (s *Session) GuildIntegrations(guildID string) (st []*GuildIntegration, err error) {
  813. body, err := s.RequestWithBucketID("GET", EndpointGuildIntegrations(guildID), nil, EndpointGuildIntegrations(guildID))
  814. if err != nil {
  815. return
  816. }
  817. err = unmarshal(body, &st)
  818. return
  819. }
  820. // GuildIntegrationCreate creates a Guild Integration.
  821. // guildID : The ID of a Guild.
  822. // integrationType : The Integration type.
  823. // integrationID : The ID of an integration.
  824. func (s *Session) GuildIntegrationCreate(guildID, integrationType, integrationID string) (err error) {
  825. data := struct {
  826. Type string `json:"type"`
  827. ID string `json:"id"`
  828. }{integrationType, integrationID}
  829. _, err = s.RequestWithBucketID("POST", EndpointGuildIntegrations(guildID), data, EndpointGuildIntegrations(guildID))
  830. return
  831. }
  832. // GuildIntegrationEdit edits a Guild Integration.
  833. // guildID : The ID of a Guild.
  834. // integrationType : The Integration type.
  835. // integrationID : The ID of an integration.
  836. // expireBehavior : The behavior when an integration subscription lapses (see the integration object documentation).
  837. // expireGracePeriod : Period (in seconds) where the integration will ignore lapsed subscriptions.
  838. // enableEmoticons : Whether emoticons should be synced for this integration (twitch only currently).
  839. func (s *Session) GuildIntegrationEdit(guildID, integrationID string, expireBehavior, expireGracePeriod int, enableEmoticons bool) (err error) {
  840. data := struct {
  841. ExpireBehavior int `json:"expire_behavior"`
  842. ExpireGracePeriod int `json:"expire_grace_period"`
  843. EnableEmoticons bool `json:"enable_emoticons"`
  844. }{expireBehavior, expireGracePeriod, enableEmoticons}
  845. _, err = s.RequestWithBucketID("PATCH", EndpointGuildIntegration(guildID, integrationID), data, EndpointGuildIntegration(guildID, ""))
  846. return
  847. }
  848. // GuildIntegrationDelete removes the given integration from the Guild.
  849. // guildID : The ID of a Guild.
  850. // integrationID : The ID of an integration.
  851. func (s *Session) GuildIntegrationDelete(guildID, integrationID string) (err error) {
  852. _, err = s.RequestWithBucketID("DELETE", EndpointGuildIntegration(guildID, integrationID), nil, EndpointGuildIntegration(guildID, ""))
  853. return
  854. }
  855. // GuildIntegrationSync syncs an integration.
  856. // guildID : The ID of a Guild.
  857. // integrationID : The ID of an integration.
  858. func (s *Session) GuildIntegrationSync(guildID, integrationID string) (err error) {
  859. _, err = s.RequestWithBucketID("POST", EndpointGuildIntegrationSync(guildID, integrationID), nil, EndpointGuildIntegration(guildID, ""))
  860. return
  861. }
  862. // GuildIcon returns an image.Image of a guild icon.
  863. // guildID : The ID of a Guild.
  864. func (s *Session) GuildIcon(guildID string) (img image.Image, err error) {
  865. g, err := s.Guild(guildID)
  866. if err != nil {
  867. return
  868. }
  869. if g.Icon == "" {
  870. err = errors.New("guild does not have an icon set")
  871. return
  872. }
  873. body, err := s.RequestWithBucketID("GET", EndpointGuildIcon(guildID, g.Icon), nil, EndpointGuildIcon(guildID, ""))
  874. if err != nil {
  875. return
  876. }
  877. img, _, err = image.Decode(bytes.NewReader(body))
  878. return
  879. }
  880. // GuildSplash returns an image.Image of a guild splash image.
  881. // guildID : The ID of a Guild.
  882. func (s *Session) GuildSplash(guildID string) (img image.Image, err error) {
  883. g, err := s.Guild(guildID)
  884. if err != nil {
  885. return
  886. }
  887. if g.Splash == "" {
  888. err = errors.New("guild does not have a splash set")
  889. return
  890. }
  891. body, err := s.RequestWithBucketID("GET", EndpointGuildSplash(guildID, g.Splash), nil, EndpointGuildSplash(guildID, ""))
  892. if err != nil {
  893. return
  894. }
  895. img, _, err = image.Decode(bytes.NewReader(body))
  896. return
  897. }
  898. // GuildEmbed returns the embed for a Guild.
  899. // guildID : The ID of a Guild.
  900. func (s *Session) GuildEmbed(guildID string) (st *GuildEmbed, err error) {
  901. body, err := s.RequestWithBucketID("GET", EndpointGuildEmbed(guildID), nil, EndpointGuildEmbed(guildID))
  902. if err != nil {
  903. return
  904. }
  905. err = unmarshal(body, &st)
  906. return
  907. }
  908. // GuildEmbedEdit returns the embed for a Guild.
  909. // guildID : The ID of a Guild.
  910. func (s *Session) GuildEmbedEdit(guildID string, enabled bool, channelID string) (err error) {
  911. data := GuildEmbed{enabled, channelID}
  912. _, err = s.RequestWithBucketID("PATCH", EndpointGuildEmbed(guildID), data, EndpointGuildEmbed(guildID))
  913. return
  914. }
  915. // ------------------------------------------------------------------------------------------------
  916. // Functions specific to Discord Channels
  917. // ------------------------------------------------------------------------------------------------
  918. // Channel returns a Channel strucutre of a specific Channel.
  919. // channelID : The ID of the Channel you want returned.
  920. func (s *Session) Channel(channelID string) (st *Channel, err error) {
  921. body, err := s.RequestWithBucketID("GET", EndpointChannel(channelID), nil, EndpointChannel(channelID))
  922. if err != nil {
  923. return
  924. }
  925. err = unmarshal(body, &st)
  926. return
  927. }
  928. // ChannelEdit edits the given channel
  929. // channelID : The ID of a Channel
  930. // name : The new name to assign the channel.
  931. func (s *Session) ChannelEdit(channelID, name string) (st *Channel, err error) {
  932. data := struct {
  933. Name string `json:"name"`
  934. }{name}
  935. body, err := s.RequestWithBucketID("PATCH", EndpointChannel(channelID), data, EndpointChannel(channelID))
  936. if err != nil {
  937. return
  938. }
  939. err = unmarshal(body, &st)
  940. return
  941. }
  942. // ChannelDelete deletes the given channel
  943. // channelID : The ID of a Channel
  944. func (s *Session) ChannelDelete(channelID string) (st *Channel, err error) {
  945. body, err := s.RequestWithBucketID("DELETE", EndpointChannel(channelID), nil, EndpointChannel(channelID))
  946. if err != nil {
  947. return
  948. }
  949. err = unmarshal(body, &st)
  950. return
  951. }
  952. // ChannelTyping broadcasts to all members that authenticated user is typing in
  953. // the given channel.
  954. // channelID : The ID of a Channel
  955. func (s *Session) ChannelTyping(channelID string) (err error) {
  956. _, err = s.RequestWithBucketID("POST", EndpointChannelTyping(channelID), nil, EndpointChannelTyping(channelID))
  957. return
  958. }
  959. // ChannelMessages returns an array of Message structures for messages within
  960. // a given channel.
  961. // channelID : The ID of a Channel.
  962. // limit : The number messages that can be returned. (max 100)
  963. // beforeID : If provided all messages returned will be before given ID.
  964. // afterID : If provided all messages returned will be after given ID.
  965. // aroundID : If provided all messages returned will be around given ID.
  966. func (s *Session) ChannelMessages(channelID string, limit int, beforeID, afterID, aroundID string) (st []*Message, err error) {
  967. uri := EndpointChannelMessages(channelID)
  968. v := url.Values{}
  969. if limit > 0 {
  970. v.Set("limit", strconv.Itoa(limit))
  971. }
  972. if afterID != "" {
  973. v.Set("after", afterID)
  974. }
  975. if beforeID != "" {
  976. v.Set("before", beforeID)
  977. }
  978. if aroundID != "" {
  979. v.Set("around", aroundID)
  980. }
  981. if len(v) > 0 {
  982. uri = fmt.Sprintf("%s?%s", uri, v.Encode())
  983. }
  984. body, err := s.RequestWithBucketID("GET", uri, nil, EndpointChannelMessages(channelID))
  985. if err != nil {
  986. return
  987. }
  988. err = unmarshal(body, &st)
  989. return
  990. }
  991. // ChannelMessage gets a single message by ID from a given channel.
  992. // channeld : The ID of a Channel
  993. // messageID : the ID of a Message
  994. func (s *Session) ChannelMessage(channelID, messageID string) (st *Message, err error) {
  995. response, err := s.RequestWithBucketID("GET", EndpointChannelMessage(channelID, messageID), nil, EndpointChannelMessage(channelID, ""))
  996. if err != nil {
  997. return
  998. }
  999. err = unmarshal(response, &st)
  1000. return
  1001. }
  1002. // ChannelMessageAck acknowledges and marks the given message as read
  1003. // channeld : The ID of a Channel
  1004. // messageID : the ID of a Message
  1005. // lastToken : token returned by last ack
  1006. func (s *Session) ChannelMessageAck(channelID, messageID, lastToken string) (st *Ack, err error) {
  1007. body, err := s.RequestWithBucketID("POST", EndpointChannelMessageAck(channelID, messageID), &Ack{Token: lastToken}, EndpointChannelMessageAck(channelID, ""))
  1008. if err != nil {
  1009. return
  1010. }
  1011. err = unmarshal(body, &st)
  1012. return
  1013. }
  1014. // ChannelMessageSend sends a message to the given channel.
  1015. // channelID : The ID of a Channel.
  1016. // content : The message to send.
  1017. func (s *Session) ChannelMessageSend(channelID string, content string) (*Message, error) {
  1018. return s.ChannelMessageSendComplex(channelID, &MessageSend{MessageParams: MessageParams{Content: &content}})
  1019. }
  1020. // ChannelMessageSendComplex sends a message to the given channel.
  1021. // channelID : The ID of a Channel.
  1022. // data : The message struct to send.
  1023. func (s *Session) ChannelMessageSendComplex(channelID string, data *MessageSend) (st *Message, err error) {
  1024. if data.Embed != nil && data.Embed.Type == "" {
  1025. data.Embed.Type = "rich"
  1026. }
  1027. response, err := s.RequestWithBucketID("POST", EndpointChannelMessages(channelID), data, EndpointChannelMessages(channelID))
  1028. if err != nil {
  1029. return
  1030. }
  1031. err = unmarshal(response, &st)
  1032. return
  1033. }
  1034. // ChannelMessageSendTTS sends a message to the given channel with Text to Speech.
  1035. // channelID : The ID of a Channel.
  1036. // content : The message to send.
  1037. func (s *Session) ChannelMessageSendTTS(channelID string, content string) (*Message, error) {
  1038. return s.ChannelMessageSendComplex(channelID, &MessageSend{MessageParams: MessageParams{Content: &content}, Tts: true})
  1039. }
  1040. // ChannelMessageSendEmbed sends a message to the given channel with embedded data.
  1041. // channelID : The ID of a Channel.
  1042. // embed : The embed data to send.
  1043. func (s *Session) ChannelMessageSendEmbed(channelID string, embed *MessageEmbed) (*Message, error) {
  1044. return s.ChannelMessageSendComplex(channelID, &MessageSend{MessageParams: MessageParams{Embed: embed}})
  1045. }
  1046. // ChannelMessageEdit edits an existing message, replacing it entirely with
  1047. // the given content.
  1048. // channeld : The ID of a Channel
  1049. // messageID : The ID of a Message
  1050. // content : The contents of the message
  1051. func (s *Session) ChannelMessageEdit(channelID, messageID, content string) (*Message, error) {
  1052. return s.ChannelMessageEditComplex(channelID, messageID, &MessageEdit{MessageParams: MessageParams{Content: &content}})
  1053. }
  1054. // ChannelMessageEditComplex edits an existing message, replacing it entirely with
  1055. // the given MessageEdit struct
  1056. // channeld : The ID of a Channel
  1057. // messageID : The ID of a Message
  1058. // data : The MessageEdit struct to send
  1059. func (s *Session) ChannelMessageEditComplex(channelID, messageID string, data *MessageEdit) (st *Message, err error) {
  1060. if data.Embed != nil && data.Embed.Type == "" {
  1061. data.Embed.Type = "rich"
  1062. }
  1063. response, err := s.RequestWithBucketID("PATCH", EndpointChannelMessage(channelID, messageID), data, EndpointChannelMessage(channelID, ""))
  1064. if err != nil {
  1065. return
  1066. }
  1067. err = unmarshal(response, &st)
  1068. return
  1069. }
  1070. // ChannelMessageEditEmbed edits an existing message with embedded data.
  1071. // channelID : The ID of a Channel
  1072. // messageID : The ID of a Message
  1073. // embed : The embed data to send
  1074. func (s *Session) ChannelMessageEditEmbed(channelID, messageID string, embed *MessageEmbed) (*Message, error) {
  1075. return s.ChannelMessageEditComplex(channelID, messageID, &MessageEdit{MessageParams: MessageParams{Embed: embed}})
  1076. }
  1077. // ChannelMessageDelete deletes a message from the Channel.
  1078. func (s *Session) ChannelMessageDelete(channelID, messageID string) (err error) {
  1079. _, err = s.RequestWithBucketID("DELETE", EndpointChannelMessage(channelID, messageID), nil, EndpointChannelMessage(channelID, ""))
  1080. return
  1081. }
  1082. // ChannelMessagesBulkDelete bulk deletes the messages from the channel for the provided messageIDs.
  1083. // If only one messageID is in the slice call channelMessageDelete funciton.
  1084. // If the slice is empty do nothing.
  1085. // channelID : The ID of the channel for the messages to delete.
  1086. // messages : The IDs of the messages to be deleted. A slice of string IDs. A maximum of 100 messages.
  1087. func (s *Session) ChannelMessagesBulkDelete(channelID string, messages []string) (err error) {
  1088. if len(messages) == 0 {
  1089. return
  1090. }
  1091. if len(messages) == 1 {
  1092. err = s.ChannelMessageDelete(channelID, messages[0])
  1093. return
  1094. }
  1095. if len(messages) > 100 {
  1096. messages = messages[:100]
  1097. }
  1098. data := struct {
  1099. Messages []string `json:"messages"`
  1100. }{messages}
  1101. _, err = s.RequestWithBucketID("POST", EndpointChannelMessagesBulkDelete(channelID), data, EndpointChannelMessagesBulkDelete(channelID))
  1102. return
  1103. }
  1104. // ChannelMessagePin pins a message within a given channel.
  1105. // channelID: The ID of a channel.
  1106. // messageID: The ID of a message.
  1107. func (s *Session) ChannelMessagePin(channelID, messageID string) (err error) {
  1108. _, err = s.RequestWithBucketID("PUT", EndpointChannelMessagePin(channelID, messageID), nil, EndpointChannelMessagePin(channelID, ""))
  1109. return
  1110. }
  1111. // ChannelMessageUnpin unpins a message within a given channel.
  1112. // channelID: The ID of a channel.
  1113. // messageID: The ID of a message.
  1114. func (s *Session) ChannelMessageUnpin(channelID, messageID string) (err error) {
  1115. _, err = s.RequestWithBucketID("DELETE", EndpointChannelMessagePin(channelID, messageID), nil, EndpointChannelMessagePin(channelID, ""))
  1116. return
  1117. }
  1118. // ChannelMessagesPinned returns an array of Message structures for pinned messages
  1119. // within a given channel
  1120. // channelID : The ID of a Channel.
  1121. func (s *Session) ChannelMessagesPinned(channelID string) (st []*Message, err error) {
  1122. body, err := s.RequestWithBucketID("GET", EndpointChannelMessagesPins(channelID), nil, EndpointChannelMessagesPins(channelID))
  1123. if err != nil {
  1124. return
  1125. }
  1126. err = unmarshal(body, &st)
  1127. return
  1128. }
  1129. // ChannelFileSend sends a file to the given channel.
  1130. // channelID : The ID of a Channel.
  1131. // name: The name of the file.
  1132. // io.Reader : A reader for the file contents.
  1133. func (s *Session) ChannelFileSend(channelID, name string, r io.Reader) (st *Message, err error) {
  1134. return s.ChannelFileSendWithMessage(channelID, "", name, r)
  1135. }
  1136. // ChannelFileSendWithMessage sends a file to the given channel with an message.
  1137. // channelID : The ID of a Channel.
  1138. // content: Optional Message content.
  1139. // name: The name of the file.
  1140. // io.Reader : A reader for the file contents.
  1141. func (s *Session) ChannelFileSendWithMessage(channelID, content string, name string, r io.Reader) (st *Message, err error) {
  1142. body := &bytes.Buffer{}
  1143. bodywriter := multipart.NewWriter(body)
  1144. if len(content) != 0 {
  1145. if err := bodywriter.WriteField("content", content); err != nil {
  1146. return nil, err
  1147. }
  1148. }
  1149. writer, err := bodywriter.CreateFormFile("file", name)
  1150. if err != nil {
  1151. return nil, err
  1152. }
  1153. _, err = io.Copy(writer, r)
  1154. if err != nil {
  1155. return
  1156. }
  1157. err = bodywriter.Close()
  1158. if err != nil {
  1159. return
  1160. }
  1161. response, err := s.request("POST", EndpointChannelMessages(channelID), bodywriter.FormDataContentType(), body.Bytes(), EndpointChannelMessages(channelID), 0)
  1162. if err != nil {
  1163. return
  1164. }
  1165. err = unmarshal(response, &st)
  1166. return
  1167. }
  1168. // ChannelInvites returns an array of Invite structures for the given channel
  1169. // channelID : The ID of a Channel
  1170. func (s *Session) ChannelInvites(channelID string) (st []*Invite, err error) {
  1171. body, err := s.RequestWithBucketID("GET", EndpointChannelInvites(channelID), nil, EndpointChannelInvites(channelID))
  1172. if err != nil {
  1173. return
  1174. }
  1175. err = unmarshal(body, &st)
  1176. return
  1177. }
  1178. // ChannelInviteCreate creates a new invite for the given channel.
  1179. // channelID : The ID of a Channel
  1180. // i : An Invite struct with the values MaxAge, MaxUses, Temporary,
  1181. // and XkcdPass defined.
  1182. func (s *Session) ChannelInviteCreate(channelID string, i Invite) (st *Invite, err error) {
  1183. data := struct {
  1184. MaxAge int `json:"max_age"`
  1185. MaxUses int `json:"max_uses"`
  1186. Temporary bool `json:"temporary"`
  1187. XKCDPass string `json:"xkcdpass"`
  1188. }{i.MaxAge, i.MaxUses, i.Temporary, i.XkcdPass}
  1189. body, err := s.RequestWithBucketID("POST", EndpointChannelInvites(channelID), data, EndpointChannelInvites(channelID))
  1190. if err != nil {
  1191. return
  1192. }
  1193. err = unmarshal(body, &st)
  1194. return
  1195. }
  1196. // ChannelPermissionSet creates a Permission Override for the given channel.
  1197. // NOTE: This func name may changed. Using Set instead of Create because
  1198. // you can both create a new override or update an override with this function.
  1199. func (s *Session) ChannelPermissionSet(channelID, targetID, targetType string, allow, deny int) (err error) {
  1200. data := struct {
  1201. ID string `json:"id"`
  1202. Type string `json:"type"`
  1203. Allow int `json:"allow"`
  1204. Deny int `json:"deny"`
  1205. }{targetID, targetType, allow, deny}
  1206. _, err = s.RequestWithBucketID("PUT", EndpointChannelPermission(channelID, targetID), data, EndpointChannelPermission(channelID, ""))
  1207. return
  1208. }
  1209. // ChannelPermissionDelete deletes a specific permission override for the given channel.
  1210. // NOTE: Name of this func may change.
  1211. func (s *Session) ChannelPermissionDelete(channelID, targetID string) (err error) {
  1212. _, err = s.RequestWithBucketID("DELETE", EndpointChannelPermission(channelID, targetID), nil, EndpointChannelPermission(channelID, ""))
  1213. return
  1214. }
  1215. // ------------------------------------------------------------------------------------------------
  1216. // Functions specific to Discord Invites
  1217. // ------------------------------------------------------------------------------------------------
  1218. // Invite returns an Invite structure of the given invite
  1219. // inviteID : The invite code (or maybe xkcdpass?)
  1220. func (s *Session) Invite(inviteID string) (st *Invite, err error) {
  1221. body, err := s.RequestWithBucketID("GET", EndpointInvite(inviteID), nil, EndpointInvite(""))
  1222. if err != nil {
  1223. return
  1224. }
  1225. err = unmarshal(body, &st)
  1226. return
  1227. }
  1228. // InviteDelete deletes an existing invite
  1229. // inviteID : the code (or maybe xkcdpass?) of an invite
  1230. func (s *Session) InviteDelete(inviteID string) (st *Invite, err error) {
  1231. body, err := s.RequestWithBucketID("DELETE", EndpointInvite(inviteID), nil, EndpointInvite(""))
  1232. if err != nil {
  1233. return
  1234. }
  1235. err = unmarshal(body, &st)
  1236. return
  1237. }
  1238. // InviteAccept accepts an Invite to a Guild or Channel
  1239. // inviteID : The invite code (or maybe xkcdpass?)
  1240. func (s *Session) InviteAccept(inviteID string) (st *Invite, err error) {
  1241. body, err := s.RequestWithBucketID("POST", EndpointInvite(inviteID), nil, EndpointInvite(""))
  1242. if err != nil {
  1243. return
  1244. }
  1245. err = unmarshal(body, &st)
  1246. return
  1247. }
  1248. // ------------------------------------------------------------------------------------------------
  1249. // Functions specific to Discord Voice
  1250. // ------------------------------------------------------------------------------------------------
  1251. // VoiceRegions returns the voice server regions
  1252. func (s *Session) VoiceRegions() (st []*VoiceRegion, err error) {
  1253. body, err := s.RequestWithBucketID("GET", EndpointVoiceRegions, nil, EndpointVoiceRegions)
  1254. if err != nil {
  1255. return
  1256. }
  1257. err = unmarshal(body, &st)
  1258. return
  1259. }
  1260. // VoiceICE returns the voice server ICE information
  1261. func (s *Session) VoiceICE() (st *VoiceICE, err error) {
  1262. body, err := s.RequestWithBucketID("GET", EndpointVoiceIce, nil, EndpointVoiceIce)
  1263. if err != nil {
  1264. return
  1265. }
  1266. err = unmarshal(body, &st)
  1267. return
  1268. }
  1269. // ------------------------------------------------------------------------------------------------
  1270. // Functions specific to Discord Websockets
  1271. // ------------------------------------------------------------------------------------------------
  1272. // Gateway returns the a websocket Gateway address
  1273. func (s *Session) Gateway() (gateway string, err error) {
  1274. response, err := s.RequestWithBucketID("GET", EndpointGateway, nil, EndpointGateway)
  1275. if err != nil {
  1276. return
  1277. }
  1278. temp := struct {
  1279. URL string `json:"url"`
  1280. }{}
  1281. err = unmarshal(response, &temp)
  1282. if err != nil {
  1283. return
  1284. }
  1285. gateway = temp.URL
  1286. // Ensure the gateway always has a trailing slash.
  1287. // MacOS will fail to connect if we add query params without a trailing slash on the base domain.
  1288. if !strings.HasSuffix(gateway, "/") {
  1289. gateway += "/"
  1290. }
  1291. return
  1292. }
  1293. // Functions specific to Webhooks
  1294. // WebhookCreate returns a new Webhook.
  1295. // channelID: The ID of a Channel.
  1296. // name : The name of the webhook.
  1297. // avatar : The avatar of the webhook.
  1298. func (s *Session) WebhookCreate(channelID, name, avatar string) (st *Webhook, err error) {
  1299. data := struct {
  1300. Name string `json:"name"`
  1301. Avatar string `json:"avatar,omitempty"`
  1302. }{name, avatar}
  1303. body, err := s.RequestWithBucketID("POST", EndpointChannelWebhooks(channelID), data, EndpointChannelWebhooks(channelID))
  1304. if err != nil {
  1305. return
  1306. }
  1307. err = unmarshal(body, &st)
  1308. return
  1309. }
  1310. // ChannelWebhooks returns all webhooks for a given channel.
  1311. // channelID: The ID of a channel.
  1312. func (s *Session) ChannelWebhooks(channelID string) (st []*Webhook, err error) {
  1313. body, err := s.RequestWithBucketID("GET", EndpointChannelWebhooks(channelID), nil, EndpointChannelWebhooks(channelID))
  1314. if err != nil {
  1315. return
  1316. }
  1317. err = unmarshal(body, &st)
  1318. return
  1319. }
  1320. // GuildWebhooks returns all webhooks for a given guild.
  1321. // guildID: The ID of a Guild.
  1322. func (s *Session) GuildWebhooks(guildID string) (st []*Webhook, err error) {
  1323. body, err := s.RequestWithBucketID("GET", EndpointGuildWebhooks(guildID), nil, EndpointGuildWebhooks(guildID))
  1324. if err != nil {
  1325. return
  1326. }
  1327. err = unmarshal(body, &st)
  1328. return
  1329. }
  1330. // Webhook returns a webhook for a given ID
  1331. // webhookID: The ID of a webhook.
  1332. func (s *Session) Webhook(webhookID string) (st *Webhook, err error) {
  1333. body, err := s.RequestWithBucketID("GET", EndpointWebhook(webhookID), nil, EndpointWebhooks)
  1334. if err != nil {
  1335. return
  1336. }
  1337. err = unmarshal(body, &st)
  1338. return
  1339. }
  1340. // WebhookWithToken returns a webhook for a given ID
  1341. // webhookID: The ID of a webhook.
  1342. // token : The auth token for the webhook.
  1343. func (s *Session) WebhookWithToken(webhookID, token string) (st *Webhook, err error) {
  1344. body, err := s.RequestWithBucketID("GET", EndpointWebhookToken(webhookID, token), nil, EndpointWebhookToken("", ""))
  1345. if err != nil {
  1346. return
  1347. }
  1348. err = unmarshal(body, &st)
  1349. return
  1350. }
  1351. // WebhookEdit updates an existing Webhook.
  1352. // webhookID: The ID of a webhook.
  1353. // name : The name of the webhook.
  1354. // avatar : The avatar of the webhook.
  1355. func (s *Session) WebhookEdit(webhookID, name, avatar string) (st *Role, err error) {
  1356. data := struct {
  1357. Name string `json:"name,omitempty"`
  1358. Avatar string `json:"avatar,omitempty"`
  1359. }{name, avatar}
  1360. body, err := s.RequestWithBucketID("PATCH", EndpointWebhook(webhookID), data, EndpointWebhooks)
  1361. if err != nil {
  1362. return
  1363. }
  1364. err = unmarshal(body, &st)
  1365. return
  1366. }
  1367. // WebhookEditWithToken updates an existing Webhook with an auth token.
  1368. // webhookID: The ID of a webhook.
  1369. // token : The auth token for the webhook.
  1370. // name : The name of the webhook.
  1371. // avatar : The avatar of the webhook.
  1372. func (s *Session) WebhookEditWithToken(webhookID, token, name, avatar string) (st *Role, err error) {
  1373. data := struct {
  1374. Name string `json:"name,omitempty"`
  1375. Avatar string `json:"avatar,omitempty"`
  1376. }{name, avatar}
  1377. body, err := s.RequestWithBucketID("PATCH", EndpointWebhookToken(webhookID, token), data, EndpointWebhookToken("", ""))
  1378. if err != nil {
  1379. return
  1380. }
  1381. err = unmarshal(body, &st)
  1382. return
  1383. }
  1384. // WebhookDelete deletes a webhook for a given ID
  1385. // webhookID: The ID of a webhook.
  1386. func (s *Session) WebhookDelete(webhookID string) (st *Webhook, err error) {
  1387. body, err := s.RequestWithBucketID("DELETE", EndpointWebhook(webhookID), nil, EndpointWebhooks)
  1388. if err != nil {
  1389. return
  1390. }
  1391. err = unmarshal(body, &st)
  1392. return
  1393. }
  1394. // WebhookDeleteWithToken deletes a webhook for a given ID with an auth token.
  1395. // webhookID: The ID of a webhook.
  1396. // token : The auth token for the webhook.
  1397. func (s *Session) WebhookDeleteWithToken(webhookID, token string) (st *Webhook, err error) {
  1398. body, err := s.RequestWithBucketID("DELETE", EndpointWebhookToken(webhookID, token), nil, EndpointWebhookToken("", ""))
  1399. if err != nil {
  1400. return
  1401. }
  1402. err = unmarshal(body, &st)
  1403. return
  1404. }
  1405. // WebhookExecute executes a webhook.
  1406. // webhookID: The ID of a webhook.
  1407. // token : The auth token for the webhook
  1408. func (s *Session) WebhookExecute(webhookID, token string, wait bool, data *WebhookParams) (err error) {
  1409. uri := EndpointWebhookToken(webhookID, token)
  1410. if wait {
  1411. uri += "?wait=true"
  1412. }
  1413. _, err = s.RequestWithBucketID("POST", uri, data, EndpointWebhookToken("", ""))
  1414. return
  1415. }
  1416. // MessageReactionAdd creates an emoji reaction to a message.
  1417. // channelID : The channel ID.
  1418. // messageID : The message ID.
  1419. // emojiID : Either the unicode emoji for the reaction, or a guild emoji identifier.
  1420. func (s *Session) MessageReactionAdd(channelID, messageID, emojiID string) error {
  1421. _, err := s.RequestWithBucketID("PUT", EndpointMessageReaction(channelID, messageID, emojiID, "@me"), nil, EndpointMessageReaction(channelID, "", "", ""))
  1422. return err
  1423. }
  1424. // MessageReactionRemove deletes an emoji reaction to a message.
  1425. // channelID : The channel ID.
  1426. // messageID : The message ID.
  1427. // emojiID : Either the unicode emoji for the reaction, or a guild emoji identifier.
  1428. // userID : @me or ID of the user to delete the reaction for.
  1429. func (s *Session) MessageReactionRemove(channelID, messageID, emojiID, userID string) error {
  1430. _, err := s.RequestWithBucketID("DELETE", EndpointMessageReaction(channelID, messageID, emojiID, userID), nil, EndpointMessageReaction(channelID, "", "", ""))
  1431. return err
  1432. }
  1433. // MessageReactions gets all the users reactions for a specific emoji.
  1434. // channelID : The channel ID.
  1435. // messageID : The message ID.
  1436. // emojiID : Either the unicode emoji for the reaction, or a guild emoji identifier.
  1437. // limit : max number of users to return (max 100)
  1438. func (s *Session) MessageReactions(channelID, messageID, emojiID string, limit int) (st []*User, err error) {
  1439. uri := EndpointMessageReactions(channelID, messageID, emojiID)
  1440. v := url.Values{}
  1441. if limit > 0 {
  1442. v.Set("limit", strconv.Itoa(limit))
  1443. }
  1444. if len(v) > 0 {
  1445. uri = fmt.Sprintf("%s?%s", uri, v.Encode())
  1446. }
  1447. body, err := s.RequestWithBucketID("GET", uri, nil, EndpointMessageReaction(channelID, "", "", ""))
  1448. if err != nil {
  1449. return
  1450. }
  1451. err = unmarshal(body, &st)
  1452. return
  1453. }
  1454. // ------------------------------------------------------------------------------------------------
  1455. // Functions specific to Discord Relationships (Friends list)
  1456. // ------------------------------------------------------------------------------------------------
  1457. // RelationshipsGet returns an array of all the relationships of the user.
  1458. func (s *Session) RelationshipsGet() (r []*Relationship, err error) {
  1459. body, err := s.RequestWithBucketID("GET", EndpointRelationships(), nil, EndpointRelationships())
  1460. if err != nil {
  1461. return
  1462. }
  1463. err = unmarshal(body, &r)
  1464. return
  1465. }
  1466. // relationshipCreate creates a new relationship. (I.e. send or accept a friend request, block a user.)
  1467. // relationshipType : 1 = friend, 2 = blocked, 3 = incoming friend req, 4 = sent friend req
  1468. func (s *Session) relationshipCreate(userID string, relationshipType int) (err error) {
  1469. data := struct {
  1470. Type int `json:"type"`
  1471. }{relationshipType}
  1472. _, err = s.RequestWithBucketID("PUT", EndpointRelationship(userID), data, EndpointRelationships())
  1473. return
  1474. }
  1475. // RelationshipFriendRequestSend sends a friend request to a user.
  1476. // userID: ID of the user.
  1477. func (s *Session) RelationshipFriendRequestSend(userID string) (err error) {
  1478. err = s.relationshipCreate(userID, 4)
  1479. return
  1480. }
  1481. // RelationshipFriendRequestAccept accepts a friend request from a user.
  1482. // userID: ID of the user.
  1483. func (s *Session) RelationshipFriendRequestAccept(userID string) (err error) {
  1484. err = s.relationshipCreate(userID, 1)
  1485. return
  1486. }
  1487. // RelationshipUserBlock blocks a user.
  1488. // userID: ID of the user.
  1489. func (s *Session) RelationshipUserBlock(userID string) (err error) {
  1490. err = s.relationshipCreate(userID, 2)
  1491. return
  1492. }
  1493. // RelationshipDelete removes the relationship with a user.
  1494. // userID: ID of the user.
  1495. func (s *Session) RelationshipDelete(userID string) (err error) {
  1496. _, err = s.RequestWithBucketID("DELETE", EndpointRelationship(userID), nil, EndpointRelationships())
  1497. return
  1498. }
  1499. // RelationshipsMutualGet returns an array of all the users both @me and the given user is friends with.
  1500. // userID: ID of the user.
  1501. func (s *Session) RelationshipsMutualGet(userID string) (mf []*User, err error) {
  1502. body, err := s.RequestWithBucketID("GET", EndpointRelationshipsMutual(userID), nil, EndpointRelationshipsMutual(userID))
  1503. if err != nil {
  1504. return
  1505. }
  1506. err = unmarshal(body, &mf)
  1507. return
  1508. }