wsapi.go 22 KB

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