wsapi.go 19 KB

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