wsapi.go 19 KB

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