wsapi.go 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782
  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. s.RLock()
  218. defer s.RUnlock()
  219. if s.wsConn == nil {
  220. return ErrWSNotFound
  221. }
  222. usd := updateStatusData{
  223. Status: "online",
  224. }
  225. if idle > 0 {
  226. usd.IdleSince = &idle
  227. }
  228. if game != "" {
  229. gameType := 0
  230. if url != "" {
  231. gameType = 1
  232. }
  233. usd.Game = &Game{
  234. Name: game,
  235. Type: gameType,
  236. URL: url,
  237. }
  238. }
  239. s.wsMutex.Lock()
  240. err = s.wsConn.WriteJSON(updateStatusOp{3, usd})
  241. s.wsMutex.Unlock()
  242. return
  243. }
  244. // UpdateStatus is used to update the user's status.
  245. // If idle>0 then set status to idle.
  246. // If game!="" then set game.
  247. // if otherwise, set status to active, and no game.
  248. func (s *Session) UpdateStatus(idle int, game string) (err error) {
  249. return s.UpdateStreamingStatus(idle, game, "")
  250. }
  251. type requestGuildMembersData struct {
  252. GuildID string `json:"guild_id"`
  253. Query string `json:"query"`
  254. Limit int `json:"limit"`
  255. }
  256. type requestGuildMembersOp struct {
  257. Op int `json:"op"`
  258. Data requestGuildMembersData `json:"d"`
  259. }
  260. // RequestGuildMembers requests guild members from the gateway
  261. // The gateway responds with GuildMembersChunk events
  262. // guildID : The ID of the guild to request members of
  263. // query : String that username starts with, leave empty to return all members
  264. // limit : Max number of items to return, or 0 to request all members matched
  265. func (s *Session) RequestGuildMembers(guildID, query string, limit int) (err error) {
  266. s.log(LogInformational, "called")
  267. s.RLock()
  268. defer s.RUnlock()
  269. if s.wsConn == nil {
  270. return ErrWSNotFound
  271. }
  272. data := requestGuildMembersData{
  273. GuildID: guildID,
  274. Query: query,
  275. Limit: limit,
  276. }
  277. s.wsMutex.Lock()
  278. err = s.wsConn.WriteJSON(requestGuildMembersOp{8, data})
  279. s.wsMutex.Unlock()
  280. return
  281. }
  282. // onEvent is the "event handler" for all messages received on the
  283. // Discord Gateway API websocket connection.
  284. //
  285. // If you use the AddHandler() function to register a handler for a
  286. // specific event this function will pass the event along to that handler.
  287. //
  288. // If you use the AddHandler() function to register a handler for the
  289. // "OnEvent" event then all events will be passed to that handler.
  290. //
  291. // TODO: You may also register a custom event handler entirely using...
  292. func (s *Session) onEvent(messageType int, message []byte) {
  293. var err error
  294. var reader io.Reader
  295. reader = bytes.NewBuffer(message)
  296. // If this is a compressed message, uncompress it.
  297. if messageType == websocket.BinaryMessage {
  298. z, err2 := zlib.NewReader(reader)
  299. if err2 != nil {
  300. s.log(LogError, "error uncompressing websocket message, %s", err)
  301. return
  302. }
  303. defer func() {
  304. err3 := z.Close()
  305. if err3 != nil {
  306. s.log(LogWarning, "error closing zlib, %s", err)
  307. }
  308. }()
  309. reader = z
  310. }
  311. // Decode the event into an Event struct.
  312. var e *Event
  313. decoder := json.NewDecoder(reader)
  314. if err = decoder.Decode(&e); err != nil {
  315. s.log(LogError, "error decoding websocket message, %s", err)
  316. return
  317. }
  318. s.log(LogDebug, "Op: %d, Seq: %d, Type: %s, Data: %s\n\n", e.Operation, e.Sequence, e.Type, string(e.RawData))
  319. // Ping request.
  320. // Must respond with a heartbeat packet within 5 seconds
  321. if e.Operation == 1 {
  322. s.log(LogInformational, "sending heartbeat in response to Op1")
  323. s.wsMutex.Lock()
  324. err = s.wsConn.WriteJSON(heartbeatOp{1, atomic.LoadInt64(s.sequence)})
  325. s.wsMutex.Unlock()
  326. if err != nil {
  327. s.log(LogError, "error sending heartbeat in response to Op1")
  328. return
  329. }
  330. return
  331. }
  332. // Reconnect
  333. // Must immediately disconnect from gateway and reconnect to new gateway.
  334. if e.Operation == 7 {
  335. s.log(LogInformational, "Closing and reconnecting in response to Op7")
  336. s.Close()
  337. s.reconnect()
  338. return
  339. }
  340. // Invalid Session
  341. // Must respond with a Identify packet.
  342. if e.Operation == 9 {
  343. s.log(LogInformational, "sending identify packet to gateway in response to Op9")
  344. err = s.identify()
  345. if err != nil {
  346. s.log(LogWarning, "error sending gateway identify packet, %s, %s", s.gateway, err)
  347. return
  348. }
  349. return
  350. }
  351. if e.Operation == 10 {
  352. var h helloOp
  353. if err = json.Unmarshal(e.RawData, &h); err != nil {
  354. s.log(LogError, "error unmarshalling helloOp, %s", err)
  355. } else {
  356. go s.heartbeat(s.wsConn, s.listening, h.HeartbeatInterval)
  357. }
  358. return
  359. }
  360. if e.Operation == 11 {
  361. s.Lock()
  362. s.LastHeartbeatAck = time.Now().UTC()
  363. s.Unlock()
  364. s.log(LogInformational, "got heartbeat ACK")
  365. return
  366. }
  367. // Do not try to Dispatch a non-Dispatch Message
  368. if e.Operation != 0 {
  369. // But we probably should be doing something with them.
  370. // TEMP
  371. 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))
  372. return
  373. }
  374. // Store the message sequence
  375. atomic.StoreInt64(s.sequence, e.Sequence)
  376. // Map event to registered event handlers and pass it along to any registered handlers.
  377. if eh, ok := registeredInterfaceProviders[e.Type]; ok {
  378. e.Struct = eh.New()
  379. // Attempt to unmarshal our event.
  380. if err = json.Unmarshal(e.RawData, e.Struct); err != nil {
  381. s.log(LogError, "error unmarshalling %s event, %s", e.Type, err)
  382. }
  383. // Send event to any registered event handlers for it's type.
  384. // Because the above doesn't cancel this, in case of an error
  385. // the struct could be partially populated or at default values.
  386. // However, most errors are due to a single field and I feel
  387. // it's better to pass along what we received than nothing at all.
  388. // TODO: Think about that decision :)
  389. // Either way, READY events must fire, even with errors.
  390. s.handleEvent(e.Type, e.Struct)
  391. } else {
  392. s.log(LogWarning, "unknown event: Op: %d, Seq: %d, Type: %s, Data: %s", e.Operation, e.Sequence, e.Type, string(e.RawData))
  393. }
  394. // For legacy reasons, we send the raw event also, this could be useful for handling unknown events.
  395. s.handleEvent(eventEventType, e)
  396. }
  397. // ------------------------------------------------------------------------------------------------
  398. // Code related to voice connections that initiate over the data websocket
  399. // ------------------------------------------------------------------------------------------------
  400. type voiceChannelJoinData struct {
  401. GuildID *string `json:"guild_id"`
  402. ChannelID *string `json:"channel_id"`
  403. SelfMute bool `json:"self_mute"`
  404. SelfDeaf bool `json:"self_deaf"`
  405. }
  406. type voiceChannelJoinOp struct {
  407. Op int `json:"op"`
  408. Data voiceChannelJoinData `json:"d"`
  409. }
  410. // ChannelVoiceJoin joins the session user to a voice channel.
  411. //
  412. // gID : Guild ID of the channel to join.
  413. // cID : Channel ID of the channel to join.
  414. // mute : If true, you will be set to muted upon joining.
  415. // deaf : If true, you will be set to deafened upon joining.
  416. func (s *Session) ChannelVoiceJoin(gID, cID string, mute, deaf bool) (voice *VoiceConnection, err error) {
  417. s.log(LogInformational, "called")
  418. s.RLock()
  419. voice, _ = s.VoiceConnections[gID]
  420. s.RUnlock()
  421. if voice == nil {
  422. voice = &VoiceConnection{}
  423. s.Lock()
  424. s.VoiceConnections[gID] = voice
  425. s.Unlock()
  426. }
  427. voice.Lock()
  428. voice.GuildID = gID
  429. voice.ChannelID = cID
  430. voice.deaf = deaf
  431. voice.mute = mute
  432. voice.session = s
  433. voice.Unlock()
  434. // Send the request to Discord that we want to join the voice channel
  435. data := voiceChannelJoinOp{4, voiceChannelJoinData{&gID, &cID, mute, deaf}}
  436. s.wsMutex.Lock()
  437. err = s.wsConn.WriteJSON(data)
  438. s.wsMutex.Unlock()
  439. if err != nil {
  440. return
  441. }
  442. // doesn't exactly work perfect yet.. TODO
  443. err = voice.waitUntilConnected()
  444. if err != nil {
  445. s.log(LogWarning, "error waiting for voice to connect, %s", err)
  446. voice.Close()
  447. return
  448. }
  449. return
  450. }
  451. // onVoiceStateUpdate handles Voice State Update events on the data websocket.
  452. func (s *Session) onVoiceStateUpdate(st *VoiceStateUpdate) {
  453. // If we don't have a connection for the channel, don't bother
  454. if st.ChannelID == "" {
  455. return
  456. }
  457. // Check if we have a voice connection to update
  458. s.RLock()
  459. voice, exists := s.VoiceConnections[st.GuildID]
  460. s.RUnlock()
  461. if !exists {
  462. return
  463. }
  464. // We only care about events that are about us.
  465. if s.State.User.ID != st.UserID {
  466. return
  467. }
  468. // Store the SessionID for later use.
  469. voice.Lock()
  470. voice.UserID = st.UserID
  471. voice.sessionID = st.SessionID
  472. voice.ChannelID = st.ChannelID
  473. voice.Unlock()
  474. }
  475. // onVoiceServerUpdate handles the Voice Server Update data websocket event.
  476. //
  477. // This is also fired if the Guild's voice region changes while connected
  478. // to a voice channel. In that case, need to re-establish connection to
  479. // the new region endpoint.
  480. func (s *Session) onVoiceServerUpdate(st *VoiceServerUpdate) {
  481. s.log(LogInformational, "called")
  482. s.RLock()
  483. voice, exists := s.VoiceConnections[st.GuildID]
  484. s.RUnlock()
  485. // If no VoiceConnection exists, just skip this
  486. if !exists {
  487. return
  488. }
  489. // If currently connected to voice ws/udp, then disconnect.
  490. // Has no effect if not connected.
  491. voice.Close()
  492. // Store values for later use
  493. voice.Lock()
  494. voice.token = st.Token
  495. voice.endpoint = st.Endpoint
  496. voice.GuildID = st.GuildID
  497. voice.Unlock()
  498. // Open a conenction to the voice server
  499. err := voice.open()
  500. if err != nil {
  501. s.log(LogError, "onVoiceServerUpdate voice.open, %s", err)
  502. }
  503. }
  504. type identifyProperties struct {
  505. OS string `json:"$os"`
  506. Browser string `json:"$browser"`
  507. Device string `json:"$device"`
  508. Referer string `json:"$referer"`
  509. ReferringDomain string `json:"$referring_domain"`
  510. }
  511. type identifyData struct {
  512. Token string `json:"token"`
  513. Properties identifyProperties `json:"properties"`
  514. LargeThreshold int `json:"large_threshold"`
  515. Compress bool `json:"compress"`
  516. Shard *[2]int `json:"shard,omitempty"`
  517. }
  518. type identifyOp struct {
  519. Op int `json:"op"`
  520. Data identifyData `json:"d"`
  521. }
  522. // identify sends the identify packet to the gateway
  523. func (s *Session) identify() error {
  524. properties := identifyProperties{runtime.GOOS,
  525. "Discordgo v" + VERSION,
  526. "",
  527. "",
  528. "",
  529. }
  530. data := identifyData{s.Token,
  531. properties,
  532. 250,
  533. s.Compress,
  534. nil,
  535. }
  536. if s.ShardCount > 1 {
  537. if s.ShardID >= s.ShardCount {
  538. return ErrWSShardBounds
  539. }
  540. data.Shard = &[2]int{s.ShardID, s.ShardCount}
  541. }
  542. op := identifyOp{2, data}
  543. s.wsMutex.Lock()
  544. err := s.wsConn.WriteJSON(op)
  545. s.wsMutex.Unlock()
  546. if err != nil {
  547. return err
  548. }
  549. return nil
  550. }
  551. func (s *Session) reconnect() {
  552. s.log(LogInformational, "called")
  553. var err error
  554. if s.ShouldReconnectOnError {
  555. wait := time.Duration(1)
  556. for {
  557. s.log(LogInformational, "trying to reconnect to gateway")
  558. err = s.Open()
  559. if err == nil {
  560. s.log(LogInformational, "successfully reconnected to gateway")
  561. // I'm not sure if this is actually needed.
  562. // if the gw reconnect works properly, voice should stay alive
  563. // However, there seems to be cases where something "weird"
  564. // happens. So we're doing this for now just to improve
  565. // stability in those edge cases.
  566. s.RLock()
  567. defer s.RUnlock()
  568. for _, v := range s.VoiceConnections {
  569. s.log(LogInformational, "reconnecting voice connection to guild %s", v.GuildID)
  570. go v.reconnect()
  571. // This is here just to prevent violently spamming the
  572. // voice reconnects
  573. time.Sleep(1 * time.Second)
  574. }
  575. return
  576. }
  577. // Certain race conditions can call reconnect() twice. If this happens, we
  578. // just break out of the reconnect loop
  579. if err == ErrWSAlreadyOpen {
  580. s.log(LogInformational, "Websocket already exists, no need to reconnect")
  581. return
  582. }
  583. s.log(LogError, "error reconnecting to gateway, %s", err)
  584. <-time.After(wait * time.Second)
  585. wait *= 2
  586. if wait > 600 {
  587. wait = 600
  588. }
  589. }
  590. }
  591. }
  592. // Close closes a websocket and stops all listening/heartbeat goroutines.
  593. // TODO: Add support for Voice WS/UDP connections
  594. func (s *Session) Close() (err error) {
  595. s.log(LogInformational, "called")
  596. s.Lock()
  597. s.DataReady = false
  598. if s.listening != nil {
  599. s.log(LogInformational, "closing listening channel")
  600. close(s.listening)
  601. s.listening = nil
  602. }
  603. // TODO: Close all active Voice Connections too
  604. // this should force stop any reconnecting voice channels too
  605. if s.wsConn != nil {
  606. s.log(LogInformational, "sending close frame")
  607. // To cleanly close a connection, a client should send a close
  608. // frame and wait for the server to close the connection.
  609. s.wsMutex.Lock()
  610. err := s.wsConn.WriteMessage(websocket.CloseMessage, websocket.FormatCloseMessage(websocket.CloseNormalClosure, ""))
  611. s.wsMutex.Unlock()
  612. if err != nil {
  613. s.log(LogInformational, "error closing websocket, %s", err)
  614. }
  615. // TODO: Wait for Discord to actually close the connection.
  616. time.Sleep(1 * time.Second)
  617. s.log(LogInformational, "closing gateway websocket")
  618. err = s.wsConn.Close()
  619. if err != nil {
  620. s.log(LogInformational, "error closing websocket, %s", err)
  621. }
  622. s.wsConn = nil
  623. }
  624. s.Unlock()
  625. s.log(LogInformational, "emit disconnect event")
  626. s.handleEvent(disconnectEventType, &Disconnect{})
  627. return
  628. }