wsapi.go 22 KB

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