wsapi.go 24 KB

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