wsapi.go 24 KB

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