wsapi.go 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788
  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 low level functions for interacting with the Discord
  7. // data websocket interface.
  8. package discordgo
  9. import (
  10. "bytes"
  11. "compress/zlib"
  12. "encoding/json"
  13. "errors"
  14. "io"
  15. "net/http"
  16. "runtime"
  17. "sync/atomic"
  18. "time"
  19. "github.com/gorilla/websocket"
  20. )
  21. // ErrWSAlreadyOpen is thrown when you attempt to open
  22. // a websocket that already is open.
  23. var ErrWSAlreadyOpen = errors.New("web socket already opened")
  24. // ErrWSNotFound is thrown when you attempt to use a websocket
  25. // that doesn't exist
  26. var ErrWSNotFound = errors.New("no websocket connection exists")
  27. // ErrWSShardBounds is thrown when you try to use a shard ID that is
  28. // less than the total shard count
  29. var ErrWSShardBounds = errors.New("ShardID must be less than ShardCount")
  30. type resumePacket struct {
  31. Op int `json:"op"`
  32. Data struct {
  33. Token string `json:"token"`
  34. SessionID string `json:"session_id"`
  35. Sequence int64 `json:"seq"`
  36. } `json:"d"`
  37. }
  38. // Open opens a websocket connection to Discord.
  39. func (s *Session) Open() (err error) {
  40. s.log(LogInformational, "called")
  41. s.Lock()
  42. defer func() {
  43. if err != nil {
  44. s.Unlock()
  45. }
  46. }()
  47. // A basic state is a hard requirement for Voice.
  48. if s.State == nil {
  49. state := NewState()
  50. state.TrackChannels = false
  51. state.TrackEmojis = false
  52. state.TrackMembers = false
  53. state.TrackRoles = false
  54. state.TrackVoice = false
  55. s.State = state
  56. }
  57. if s.wsConn != nil {
  58. err = ErrWSAlreadyOpen
  59. return
  60. }
  61. if s.VoiceConnections == nil {
  62. s.log(LogInformational, "creating new VoiceConnections map")
  63. s.VoiceConnections = make(map[string]*VoiceConnection)
  64. }
  65. // Get the gateway to use for the Websocket connection
  66. if s.gateway == "" {
  67. s.gateway, err = s.Gateway()
  68. if err != nil {
  69. return
  70. }
  71. // Add the version and encoding to the URL
  72. s.gateway = s.gateway + "?v=" + APIVersion + "&encoding=json"
  73. }
  74. header := http.Header{}
  75. header.Add("accept-encoding", "zlib")
  76. s.log(LogInformational, "connecting to gateway %s", s.gateway)
  77. s.wsConn, _, err = websocket.DefaultDialer.Dial(s.gateway, header)
  78. if err != nil {
  79. s.log(LogWarning, "error connecting to gateway %s, %s", s.gateway, err)
  80. s.gateway = "" // clear cached gateway
  81. // TODO: should we add a retry block here?
  82. return
  83. }
  84. sequence := atomic.LoadInt64(s.sequence)
  85. if s.sessionID != "" && sequence > 0 {
  86. p := resumePacket{}
  87. p.Op = 6
  88. p.Data.Token = s.Token
  89. p.Data.SessionID = s.sessionID
  90. p.Data.Sequence = sequence
  91. s.log(LogInformational, "sending resume packet to gateway")
  92. err = s.wsConn.WriteJSON(p)
  93. if err != nil {
  94. s.log(LogWarning, "error sending gateway resume packet, %s, %s", s.gateway, err)
  95. return
  96. }
  97. } else {
  98. err = s.identify()
  99. if err != nil {
  100. s.log(LogWarning, "error sending gateway identify packet, %s, %s", s.gateway, err)
  101. return
  102. }
  103. }
  104. // Create listening outside of listen, as it needs to happen inside the mutex
  105. // lock.
  106. s.listening = make(chan interface{})
  107. go s.listen(s.wsConn, s.listening)
  108. s.LastHeartbeatAck = time.Now().UTC()
  109. s.Unlock()
  110. s.log(LogInformational, "emit connect event")
  111. s.handleEvent(connectEventType, &Connect{})
  112. s.log(LogInformational, "exiting")
  113. return
  114. }
  115. // listen polls the websocket connection for events, it will stop when the
  116. // listening channel is closed, or an error occurs.
  117. func (s *Session) listen(wsConn *websocket.Conn, listening <-chan interface{}) {
  118. s.log(LogInformational, "called")
  119. for {
  120. messageType, message, err := wsConn.ReadMessage()
  121. if err != nil {
  122. // Detect if we have been closed manually. If a Close() has already
  123. // happened, the websocket we are listening on will be different to
  124. // the current session.
  125. s.RLock()
  126. sameConnection := s.wsConn == wsConn
  127. s.RUnlock()
  128. if sameConnection {
  129. s.log(LogWarning, "error reading from gateway %s websocket, %s", s.gateway, err)
  130. // There has been an error reading, close the websocket so that
  131. // OnDisconnect event is emitted.
  132. err := s.Close()
  133. if err != nil {
  134. s.log(LogWarning, "error closing session connection, %s", err)
  135. }
  136. s.log(LogInformational, "calling reconnect() now")
  137. s.reconnect()
  138. }
  139. return
  140. }
  141. select {
  142. case <-listening:
  143. return
  144. default:
  145. s.onEvent(messageType, message)
  146. }
  147. }
  148. }
  149. type heartbeatOp struct {
  150. Op int `json:"op"`
  151. Data int64 `json:"d"`
  152. }
  153. type helloOp struct {
  154. HeartbeatInterval time.Duration `json:"heartbeat_interval"`
  155. Trace []string `json:"_trace"`
  156. }
  157. // FailedHeartbeatAcks is the Number of heartbeat intervals to wait until forcing a connection restart.
  158. const FailedHeartbeatAcks time.Duration = 5 * time.Millisecond
  159. // heartbeat sends regular heartbeats to Discord so it knows the client
  160. // is still connected. If you do not send these heartbeats Discord will
  161. // disconnect the websocket connection after a few seconds.
  162. func (s *Session) heartbeat(wsConn *websocket.Conn, listening <-chan interface{}, heartbeatIntervalMsec time.Duration) {
  163. s.log(LogInformational, "called")
  164. if listening == nil || wsConn == nil {
  165. return
  166. }
  167. var err error
  168. ticker := time.NewTicker(heartbeatIntervalMsec * time.Millisecond)
  169. defer ticker.Stop()
  170. for {
  171. s.RLock()
  172. last := s.LastHeartbeatAck
  173. s.RUnlock()
  174. sequence := atomic.LoadInt64(s.sequence)
  175. s.log(LogInformational, "sending gateway websocket heartbeat seq %d", sequence)
  176. s.wsMutex.Lock()
  177. err = wsConn.WriteJSON(heartbeatOp{1, sequence})
  178. s.wsMutex.Unlock()
  179. if err != nil || time.Now().UTC().Sub(last) > (heartbeatIntervalMsec*FailedHeartbeatAcks) {
  180. if err != nil {
  181. s.log(LogError, "error sending heartbeat to gateway %s, %s", s.gateway, err)
  182. } else {
  183. s.log(LogError, "haven't gotten a heartbeat ACK in %v, triggering a reconnection", time.Now().UTC().Sub(last))
  184. }
  185. s.Close()
  186. s.reconnect()
  187. return
  188. }
  189. s.Lock()
  190. s.DataReady = true
  191. s.Unlock()
  192. select {
  193. case <-ticker.C:
  194. // continue loop and send heartbeat
  195. case <-listening:
  196. return
  197. }
  198. }
  199. }
  200. type UpdateStatusData struct {
  201. IdleSince *int `json:"since"`
  202. Game *Game `json:"game"`
  203. AFK bool `json:"afk"`
  204. Status string `json:"status"`
  205. }
  206. type updateStatusOp struct {
  207. Op int `json:"op"`
  208. Data UpdateStatusData `json:"d"`
  209. }
  210. // UpdateStreamingStatus is used to update the user's streaming status.
  211. // If idle>0 then set status to idle.
  212. // If game!="" then set game.
  213. // If game!="" and url!="" then set the status type to streaming with the URL set.
  214. // if otherwise, set status to active, and no game.
  215. func (s *Session) UpdateStreamingStatus(idle int, game string, url string) (err error) {
  216. s.log(LogInformational, "called")
  217. usd := UpdateStatusData{
  218. Status: "online",
  219. }
  220. if idle > 0 {
  221. usd.IdleSince = &idle
  222. }
  223. if game != "" {
  224. gameType := GameTypeGame
  225. if url != "" {
  226. gameType = GameTypeStreaming
  227. }
  228. usd.Game = &Game{
  229. Name: game,
  230. Type: gameType,
  231. URL: url,
  232. }
  233. }
  234. return s.UpdateStatusComplex(usd)
  235. }
  236. // UpdateStatusComplex allows for sending the raw status update data untouched by discordgo.
  237. func (s *Session) UpdateStatusComplex(usd UpdateStatusData) (err error) {
  238. s.RLock()
  239. defer s.RUnlock()
  240. if s.wsConn == nil {
  241. return ErrWSNotFound
  242. }
  243. s.wsMutex.Lock()
  244. err = s.wsConn.WriteJSON(updateStatusOp{3, usd})
  245. s.wsMutex.Unlock()
  246. return
  247. }
  248. // UpdateStatus is used to update the user's status.
  249. // If idle>0 then set status to idle.
  250. // If game!="" then set game.
  251. // if otherwise, set status to active, and no game.
  252. func (s *Session) UpdateStatus(idle int, game string) (err error) {
  253. return s.UpdateStreamingStatus(idle, game, "")
  254. }
  255. type requestGuildMembersData struct {
  256. GuildID string `json:"guild_id"`
  257. Query string `json:"query"`
  258. Limit int `json:"limit"`
  259. }
  260. type requestGuildMembersOp struct {
  261. Op int `json:"op"`
  262. Data requestGuildMembersData `json:"d"`
  263. }
  264. // RequestGuildMembers requests guild members from the gateway
  265. // The gateway responds with GuildMembersChunk events
  266. // guildID : The ID of the guild to request members of
  267. // query : String that username starts with, leave empty to return all members
  268. // limit : Max number of items to return, or 0 to request all members matched
  269. func (s *Session) RequestGuildMembers(guildID, query string, limit int) (err error) {
  270. s.log(LogInformational, "called")
  271. s.RLock()
  272. defer s.RUnlock()
  273. if s.wsConn == nil {
  274. return ErrWSNotFound
  275. }
  276. data := requestGuildMembersData{
  277. GuildID: guildID,
  278. Query: query,
  279. Limit: limit,
  280. }
  281. s.wsMutex.Lock()
  282. err = s.wsConn.WriteJSON(requestGuildMembersOp{8, data})
  283. s.wsMutex.Unlock()
  284. return
  285. }
  286. // onEvent is the "event handler" for all messages received on the
  287. // Discord Gateway API websocket connection.
  288. //
  289. // If you use the AddHandler() function to register a handler for a
  290. // specific event this function will pass the event along to that handler.
  291. //
  292. // If you use the AddHandler() function to register a handler for the
  293. // "OnEvent" event then all events will be passed to that handler.
  294. //
  295. // TODO: You may also register a custom event handler entirely using...
  296. func (s *Session) onEvent(messageType int, message []byte) {
  297. var err error
  298. var reader io.Reader
  299. reader = bytes.NewBuffer(message)
  300. // If this is a compressed message, uncompress it.
  301. if messageType == websocket.BinaryMessage {
  302. z, err2 := zlib.NewReader(reader)
  303. if err2 != nil {
  304. s.log(LogError, "error uncompressing websocket message, %s", err)
  305. return
  306. }
  307. defer func() {
  308. err3 := z.Close()
  309. if err3 != nil {
  310. s.log(LogWarning, "error closing zlib, %s", err)
  311. }
  312. }()
  313. reader = z
  314. }
  315. // Decode the event into an Event struct.
  316. var e *Event
  317. decoder := json.NewDecoder(reader)
  318. if err = decoder.Decode(&e); err != nil {
  319. s.log(LogError, "error decoding websocket message, %s", err)
  320. return
  321. }
  322. s.log(LogDebug, "Op: %d, Seq: %d, Type: %s, Data: %s\n\n", e.Operation, e.Sequence, e.Type, string(e.RawData))
  323. // Ping request.
  324. // Must respond with a heartbeat packet within 5 seconds
  325. if e.Operation == 1 {
  326. s.log(LogInformational, "sending heartbeat in response to Op1")
  327. s.wsMutex.Lock()
  328. err = s.wsConn.WriteJSON(heartbeatOp{1, atomic.LoadInt64(s.sequence)})
  329. s.wsMutex.Unlock()
  330. if err != nil {
  331. s.log(LogError, "error sending heartbeat in response to Op1")
  332. return
  333. }
  334. return
  335. }
  336. // Reconnect
  337. // Must immediately disconnect from gateway and reconnect to new gateway.
  338. if e.Operation == 7 {
  339. s.log(LogInformational, "Closing and reconnecting in response to Op7")
  340. s.Close()
  341. s.reconnect()
  342. return
  343. }
  344. // Invalid Session
  345. // Must respond with a Identify packet.
  346. if e.Operation == 9 {
  347. s.log(LogInformational, "sending identify packet to gateway in response to Op9")
  348. err = s.identify()
  349. if err != nil {
  350. s.log(LogWarning, "error sending gateway identify packet, %s, %s", s.gateway, err)
  351. return
  352. }
  353. return
  354. }
  355. if e.Operation == 10 {
  356. var h helloOp
  357. if err = json.Unmarshal(e.RawData, &h); err != nil {
  358. s.log(LogError, "error unmarshalling helloOp, %s", err)
  359. } else {
  360. go s.heartbeat(s.wsConn, s.listening, h.HeartbeatInterval)
  361. }
  362. return
  363. }
  364. if e.Operation == 11 {
  365. s.Lock()
  366. s.LastHeartbeatAck = time.Now().UTC()
  367. s.Unlock()
  368. s.log(LogInformational, "got heartbeat ACK")
  369. return
  370. }
  371. // Do not try to Dispatch a non-Dispatch Message
  372. if e.Operation != 0 {
  373. // But we probably should be doing something with them.
  374. // TEMP
  375. s.log(LogWarning, "unknown Op: %d, Seq: %d, Type: %s, Data: %s, message: %s", e.Operation, e.Sequence, e.Type, string(e.RawData), string(message))
  376. return
  377. }
  378. // Store the message sequence
  379. atomic.StoreInt64(s.sequence, e.Sequence)
  380. // Map event to registered event handlers and pass it along to any registered handlers.
  381. if eh, ok := registeredInterfaceProviders[e.Type]; ok {
  382. e.Struct = eh.New()
  383. // Attempt to unmarshal our event.
  384. if err = json.Unmarshal(e.RawData, e.Struct); err != nil {
  385. s.log(LogError, "error unmarshalling %s event, %s", e.Type, err)
  386. }
  387. // Send event to any registered event handlers for it's type.
  388. // Because the above doesn't cancel this, in case of an error
  389. // the struct could be partially populated or at default values.
  390. // However, most errors are due to a single field and I feel
  391. // it's better to pass along what we received than nothing at all.
  392. // TODO: Think about that decision :)
  393. // Either way, READY events must fire, even with errors.
  394. s.handleEvent(e.Type, e.Struct)
  395. } else {
  396. s.log(LogWarning, "unknown event: Op: %d, Seq: %d, Type: %s, Data: %s", e.Operation, e.Sequence, e.Type, string(e.RawData))
  397. }
  398. // For legacy reasons, we send the raw event also, this could be useful for handling unknown events.
  399. s.handleEvent(eventEventType, e)
  400. }
  401. // ------------------------------------------------------------------------------------------------
  402. // Code related to voice connections that initiate over the data websocket
  403. // ------------------------------------------------------------------------------------------------
  404. type voiceChannelJoinData struct {
  405. GuildID *string `json:"guild_id"`
  406. ChannelID *string `json:"channel_id"`
  407. SelfMute bool `json:"self_mute"`
  408. SelfDeaf bool `json:"self_deaf"`
  409. }
  410. type voiceChannelJoinOp struct {
  411. Op int `json:"op"`
  412. Data voiceChannelJoinData `json:"d"`
  413. }
  414. // ChannelVoiceJoin joins the session user to a voice channel.
  415. //
  416. // gID : Guild ID of the channel to join.
  417. // cID : Channel ID of the channel to join.
  418. // mute : If true, you will be set to muted upon joining.
  419. // deaf : If true, you will be set to deafened upon joining.
  420. func (s *Session) ChannelVoiceJoin(gID, cID string, mute, deaf bool) (voice *VoiceConnection, err error) {
  421. s.log(LogInformational, "called")
  422. s.RLock()
  423. voice, _ = s.VoiceConnections[gID]
  424. s.RUnlock()
  425. if voice == nil {
  426. voice = &VoiceConnection{}
  427. s.Lock()
  428. s.VoiceConnections[gID] = voice
  429. s.Unlock()
  430. }
  431. voice.Lock()
  432. voice.GuildID = gID
  433. voice.ChannelID = cID
  434. voice.deaf = deaf
  435. voice.mute = mute
  436. voice.session = s
  437. voice.Unlock()
  438. // Send the request to Discord that we want to join the voice channel
  439. data := voiceChannelJoinOp{4, voiceChannelJoinData{&gID, &cID, mute, deaf}}
  440. s.wsMutex.Lock()
  441. err = s.wsConn.WriteJSON(data)
  442. s.wsMutex.Unlock()
  443. if err != nil {
  444. return
  445. }
  446. // doesn't exactly work perfect yet.. TODO
  447. err = voice.waitUntilConnected()
  448. if err != nil {
  449. s.log(LogWarning, "error waiting for voice to connect, %s", err)
  450. voice.Close()
  451. return
  452. }
  453. return
  454. }
  455. // onVoiceStateUpdate handles Voice State Update events on the data websocket.
  456. func (s *Session) onVoiceStateUpdate(st *VoiceStateUpdate) {
  457. // If we don't have a connection for the channel, don't bother
  458. if st.ChannelID == "" {
  459. return
  460. }
  461. // Check if we have a voice connection to update
  462. s.RLock()
  463. voice, exists := s.VoiceConnections[st.GuildID]
  464. s.RUnlock()
  465. if !exists {
  466. return
  467. }
  468. // We only care about events that are about us.
  469. if s.State.User.ID != st.UserID {
  470. return
  471. }
  472. // Store the SessionID for later use.
  473. voice.Lock()
  474. voice.UserID = st.UserID
  475. voice.sessionID = st.SessionID
  476. voice.ChannelID = st.ChannelID
  477. voice.Unlock()
  478. }
  479. // onVoiceServerUpdate handles the Voice Server Update data websocket event.
  480. //
  481. // This is also fired if the Guild's voice region changes while connected
  482. // to a voice channel. In that case, need to re-establish connection to
  483. // the new region endpoint.
  484. func (s *Session) onVoiceServerUpdate(st *VoiceServerUpdate) {
  485. s.log(LogInformational, "called")
  486. s.RLock()
  487. voice, exists := s.VoiceConnections[st.GuildID]
  488. s.RUnlock()
  489. // If no VoiceConnection exists, just skip this
  490. if !exists {
  491. return
  492. }
  493. // If currently connected to voice ws/udp, then disconnect.
  494. // Has no effect if not connected.
  495. voice.Close()
  496. // Store values for later use
  497. voice.Lock()
  498. voice.token = st.Token
  499. voice.endpoint = st.Endpoint
  500. voice.GuildID = st.GuildID
  501. voice.Unlock()
  502. // Open a conenction to the voice server
  503. err := voice.open()
  504. if err != nil {
  505. s.log(LogError, "onVoiceServerUpdate voice.open, %s", err)
  506. }
  507. }
  508. type identifyProperties struct {
  509. OS string `json:"$os"`
  510. Browser string `json:"$browser"`
  511. Device string `json:"$device"`
  512. Referer string `json:"$referer"`
  513. ReferringDomain string `json:"$referring_domain"`
  514. }
  515. type identifyData struct {
  516. Token string `json:"token"`
  517. Properties identifyProperties `json:"properties"`
  518. LargeThreshold int `json:"large_threshold"`
  519. Compress bool `json:"compress"`
  520. Shard *[2]int `json:"shard,omitempty"`
  521. }
  522. type identifyOp struct {
  523. Op int `json:"op"`
  524. Data identifyData `json:"d"`
  525. }
  526. // identify sends the identify packet to the gateway
  527. func (s *Session) identify() error {
  528. properties := identifyProperties{runtime.GOOS,
  529. "Discordgo v" + VERSION,
  530. "",
  531. "",
  532. "",
  533. }
  534. data := identifyData{s.Token,
  535. properties,
  536. 250,
  537. s.Compress,
  538. nil,
  539. }
  540. if s.ShardCount > 1 {
  541. if s.ShardID >= s.ShardCount {
  542. return ErrWSShardBounds
  543. }
  544. data.Shard = &[2]int{s.ShardID, s.ShardCount}
  545. }
  546. op := identifyOp{2, data}
  547. s.wsMutex.Lock()
  548. err := s.wsConn.WriteJSON(op)
  549. s.wsMutex.Unlock()
  550. if err != nil {
  551. return err
  552. }
  553. return nil
  554. }
  555. func (s *Session) reconnect() {
  556. s.log(LogInformational, "called")
  557. var err error
  558. if s.ShouldReconnectOnError {
  559. wait := time.Duration(1)
  560. for {
  561. s.log(LogInformational, "trying to reconnect to gateway")
  562. err = s.Open()
  563. if err == nil {
  564. s.log(LogInformational, "successfully reconnected to gateway")
  565. // I'm not sure if this is actually needed.
  566. // if the gw reconnect works properly, voice should stay alive
  567. // However, there seems to be cases where something "weird"
  568. // happens. So we're doing this for now just to improve
  569. // stability in those edge cases.
  570. s.RLock()
  571. defer s.RUnlock()
  572. for _, v := range s.VoiceConnections {
  573. s.log(LogInformational, "reconnecting voice connection to guild %s", v.GuildID)
  574. go v.reconnect()
  575. // This is here just to prevent violently spamming the
  576. // voice reconnects
  577. time.Sleep(1 * time.Second)
  578. }
  579. return
  580. }
  581. // Certain race conditions can call reconnect() twice. If this happens, we
  582. // just break out of the reconnect loop
  583. if err == ErrWSAlreadyOpen {
  584. s.log(LogInformational, "Websocket already exists, no need to reconnect")
  585. return
  586. }
  587. s.log(LogError, "error reconnecting to gateway, %s", err)
  588. <-time.After(wait * time.Second)
  589. wait *= 2
  590. if wait > 600 {
  591. wait = 600
  592. }
  593. }
  594. }
  595. }
  596. // Close closes a websocket and stops all listening/heartbeat goroutines.
  597. // TODO: Add support for Voice WS/UDP connections
  598. func (s *Session) Close() (err error) {
  599. s.log(LogInformational, "called")
  600. s.Lock()
  601. s.DataReady = false
  602. if s.listening != nil {
  603. s.log(LogInformational, "closing listening channel")
  604. close(s.listening)
  605. s.listening = nil
  606. }
  607. // TODO: Close all active Voice Connections too
  608. // this should force stop any reconnecting voice channels too
  609. if s.wsConn != nil {
  610. s.log(LogInformational, "sending close frame")
  611. // To cleanly close a connection, a client should send a close
  612. // frame and wait for the server to close the connection.
  613. s.wsMutex.Lock()
  614. err := s.wsConn.WriteMessage(websocket.CloseMessage, websocket.FormatCloseMessage(websocket.CloseNormalClosure, ""))
  615. s.wsMutex.Unlock()
  616. if err != nil {
  617. s.log(LogInformational, "error closing websocket, %s", err)
  618. }
  619. // TODO: Wait for Discord to actually close the connection.
  620. time.Sleep(1 * time.Second)
  621. s.log(LogInformational, "closing gateway websocket")
  622. err = s.wsConn.Close()
  623. if err != nil {
  624. s.log(LogInformational, "error closing websocket, %s", err)
  625. }
  626. s.wsConn = nil
  627. }
  628. s.Unlock()
  629. s.log(LogInformational, "emit disconnect event")
  630. s.handleEvent(disconnectEventType, &Disconnect{})
  631. return
  632. }