restapi.go 58 KB

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