wsapi.go 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912
  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. Activities []*Activity `json:"activities"`
  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, activityType ActivityType, name, url string) *UpdateStatusData {
  276. usd := &UpdateStatusData{
  277. Status: "online",
  278. }
  279. if idle > 0 {
  280. usd.IdleSince = &idle
  281. }
  282. if name != "" {
  283. usd.Activities = []*Activity{{
  284. Name: name,
  285. Type: activityType,
  286. URL: url,
  287. }}
  288. }
  289. return usd
  290. }
  291. // UpdateGameStatus is used to update the user's status.
  292. // If idle>0 then set status to idle.
  293. // If name!="" then set game.
  294. // if otherwise, set status to active, and no activity.
  295. func (s *Session) UpdateGameStatus(idle int, name string) (err error) {
  296. return s.UpdateStatusComplex(*newUpdateStatusData(idle, ActivityTypeGame, name, ""))
  297. }
  298. // UpdateStreamingStatus is used to update the user's streaming status.
  299. // If idle>0 then set status to idle.
  300. // If name!="" then set game.
  301. // If name!="" 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, name string, url string) (err error) {
  304. gameType := ActivityTypeGame
  305. if url != "" {
  306. gameType = ActivityTypeStreaming
  307. }
  308. return s.UpdateStatusComplex(*newUpdateStatusData(idle, gameType, name, url))
  309. }
  310. // UpdateListeningStatus is used to set the user to "Listening to..."
  311. // If name!="" then set to what user is listening to
  312. // Else, set user to active and no activity.
  313. func (s *Session) UpdateListeningStatus(name string) (err error) {
  314. return s.UpdateStatusComplex(*newUpdateStatusData(0, ActivityTypeListening, name, ""))
  315. }
  316. // UpdateStatusComplex allows for sending the raw status update data untouched by discordgo.
  317. func (s *Session) UpdateStatusComplex(usd UpdateStatusData) (err error) {
  318. // The comment does say "untouched by discordgo", but we might need to lie a bit here.
  319. // The Discord documentation lists `activites` as being nullable, but in practice this
  320. // doesn't seem to be the case. I had filed an issue about this at
  321. // https://github.com/discord/discord-api-docs/issues/2559, but as of writing this
  322. // haven't had any movement on it, so at this point I'm assuming this is an error,
  323. // and am fixing this bug accordingly. Because sending `null` for `activities` instantly
  324. // disconnects us, I think that disallowing it from being sent in `UpdateStatusComplex`
  325. // isn't that big of an issue.
  326. if usd.Activities == nil {
  327. usd.Activities = make([]*Activity, 0)
  328. }
  329. s.RLock()
  330. defer s.RUnlock()
  331. if s.wsConn == nil {
  332. return ErrWSNotFound
  333. }
  334. s.wsMutex.Lock()
  335. err = s.wsConn.WriteJSON(updateStatusOp{3, usd})
  336. s.wsMutex.Unlock()
  337. return
  338. }
  339. type requestGuildMembersData struct {
  340. GuildIDs []string `json:"guild_id"`
  341. Query string `json:"query"`
  342. Limit int `json:"limit"`
  343. Presences bool `json:"presences"`
  344. }
  345. type requestGuildMembersOp struct {
  346. Op int `json:"op"`
  347. Data requestGuildMembersData `json:"d"`
  348. }
  349. // RequestGuildMembers requests guild members from the gateway
  350. // The gateway responds with GuildMembersChunk events
  351. // guildID : Single Guild ID to request members of
  352. // query : String that username starts with, leave empty to return all members
  353. // limit : Max number of items to return, or 0 to request all members matched
  354. // presences : Whether to request presences of guild members
  355. func (s *Session) RequestGuildMembers(guildID string, query string, limit int, presences bool) (err error) {
  356. data := requestGuildMembersData{
  357. GuildIDs: []string{guildID},
  358. Query: query,
  359. Limit: limit,
  360. Presences: presences,
  361. }
  362. err = s.requestGuildMembers(data)
  363. return
  364. }
  365. // RequestGuildMembersBatch requests guild members from the gateway
  366. // The gateway responds with GuildMembersChunk events
  367. // guildID : Slice of guild IDs to request members of
  368. // query : String that username starts with, leave empty to return all members
  369. // limit : Max number of items to return, or 0 to request all members matched
  370. // presences : Whether to request presences of guild members
  371. func (s *Session) RequestGuildMembersBatch(guildIDs []string, query string, limit int, presences bool) (err error) {
  372. data := requestGuildMembersData{
  373. GuildIDs: guildIDs,
  374. Query: query,
  375. Limit: limit,
  376. Presences: presences,
  377. }
  378. err = s.requestGuildMembers(data)
  379. return
  380. }
  381. func (s *Session) requestGuildMembers(data requestGuildMembersData) (err error) {
  382. s.log(LogInformational, "called")
  383. s.RLock()
  384. defer s.RUnlock()
  385. if s.wsConn == nil {
  386. return ErrWSNotFound
  387. }
  388. s.wsMutex.Lock()
  389. err = s.wsConn.WriteJSON(requestGuildMembersOp{8, data})
  390. s.wsMutex.Unlock()
  391. return
  392. }
  393. // onEvent is the "event handler" for all messages received on the
  394. // Discord Gateway API websocket connection.
  395. //
  396. // If you use the AddHandler() function to register a handler for a
  397. // specific event this function will pass the event along to that handler.
  398. //
  399. // If you use the AddHandler() function to register a handler for the
  400. // "OnEvent" event then all events will be passed to that handler.
  401. func (s *Session) onEvent(messageType int, message []byte) (*Event, error) {
  402. var err error
  403. var reader io.Reader
  404. reader = bytes.NewBuffer(message)
  405. // If this is a compressed message, uncompress it.
  406. if messageType == websocket.BinaryMessage {
  407. z, err2 := zlib.NewReader(reader)
  408. if err2 != nil {
  409. s.log(LogError, "error uncompressing websocket message, %s", err)
  410. return nil, err2
  411. }
  412. defer func() {
  413. err3 := z.Close()
  414. if err3 != nil {
  415. s.log(LogWarning, "error closing zlib, %s", err)
  416. }
  417. }()
  418. reader = z
  419. }
  420. // Decode the event into an Event struct.
  421. var e *Event
  422. decoder := json.NewDecoder(reader)
  423. if err = decoder.Decode(&e); err != nil {
  424. s.log(LogError, "error decoding websocket message, %s", err)
  425. return e, err
  426. }
  427. s.log(LogDebug, "Op: %d, Seq: %d, Type: %s, Data: %s\n\n", e.Operation, e.Sequence, e.Type, string(e.RawData))
  428. // Ping request.
  429. // Must respond with a heartbeat packet within 5 seconds
  430. if e.Operation == 1 {
  431. s.log(LogInformational, "sending heartbeat in response to Op1")
  432. s.wsMutex.Lock()
  433. err = s.wsConn.WriteJSON(heartbeatOp{1, atomic.LoadInt64(s.sequence)})
  434. s.wsMutex.Unlock()
  435. if err != nil {
  436. s.log(LogError, "error sending heartbeat in response to Op1")
  437. return e, err
  438. }
  439. return e, nil
  440. }
  441. // Reconnect
  442. // Must immediately disconnect from gateway and reconnect to new gateway.
  443. if e.Operation == 7 {
  444. s.log(LogInformational, "Closing and reconnecting in response to Op7")
  445. s.CloseWithCode(websocket.CloseServiceRestart)
  446. s.reconnect()
  447. return e, nil
  448. }
  449. // Invalid Session
  450. // Must respond with a Identify packet.
  451. if e.Operation == 9 {
  452. s.log(LogInformational, "sending identify packet to gateway in response to Op9")
  453. err = s.identify()
  454. if err != nil {
  455. s.log(LogWarning, "error sending gateway identify packet, %s, %s", s.gateway, err)
  456. return e, err
  457. }
  458. return e, nil
  459. }
  460. if e.Operation == 10 {
  461. // Op10 is handled by Open()
  462. return e, nil
  463. }
  464. if e.Operation == 11 {
  465. s.Lock()
  466. s.LastHeartbeatAck = time.Now().UTC()
  467. s.Unlock()
  468. s.log(LogDebug, "got heartbeat ACK")
  469. return e, nil
  470. }
  471. // Do not try to Dispatch a non-Dispatch Message
  472. if e.Operation != 0 {
  473. // But we probably should be doing something with them.
  474. // TEMP
  475. 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))
  476. return e, nil
  477. }
  478. // Store the message sequence
  479. atomic.StoreInt64(s.sequence, e.Sequence)
  480. // Map event to registered event handlers and pass it along to any registered handlers.
  481. if eh, ok := registeredInterfaceProviders[e.Type]; ok {
  482. e.Struct = eh.New()
  483. // Attempt to unmarshal our event.
  484. if err = json.Unmarshal(e.RawData, e.Struct); err != nil {
  485. s.log(LogError, "error unmarshalling %s event, %s", e.Type, err)
  486. }
  487. // Send event to any registered event handlers for it's type.
  488. // Because the above doesn't cancel this, in case of an error
  489. // the struct could be partially populated or at default values.
  490. // However, most errors are due to a single field and I feel
  491. // it's better to pass along what we received than nothing at all.
  492. // TODO: Think about that decision :)
  493. // Either way, READY events must fire, even with errors.
  494. s.handleEvent(e.Type, e.Struct)
  495. } else {
  496. s.log(LogWarning, "unknown event: Op: %d, Seq: %d, Type: %s, Data: %s", e.Operation, e.Sequence, e.Type, string(e.RawData))
  497. }
  498. // For legacy reasons, we send the raw event also, this could be useful for handling unknown events.
  499. s.handleEvent(eventEventType, e)
  500. return e, nil
  501. }
  502. // ------------------------------------------------------------------------------------------------
  503. // Code related to voice connections that initiate over the data websocket
  504. // ------------------------------------------------------------------------------------------------
  505. type voiceChannelJoinData struct {
  506. GuildID *string `json:"guild_id"`
  507. ChannelID *string `json:"channel_id"`
  508. SelfMute bool `json:"self_mute"`
  509. SelfDeaf bool `json:"self_deaf"`
  510. }
  511. type voiceChannelJoinOp struct {
  512. Op int `json:"op"`
  513. Data voiceChannelJoinData `json:"d"`
  514. }
  515. // ChannelVoiceJoin joins the session user to a voice channel.
  516. //
  517. // gID : Guild ID of the channel to join.
  518. // cID : Channel ID of the channel to join.
  519. // mute : If true, you will be set to muted upon joining.
  520. // deaf : If true, you will be set to deafened upon joining.
  521. func (s *Session) ChannelVoiceJoin(gID, cID string, mute, deaf bool) (voice *VoiceConnection, err error) {
  522. s.log(LogInformational, "called")
  523. s.RLock()
  524. voice, _ = s.VoiceConnections[gID]
  525. s.RUnlock()
  526. if voice == nil {
  527. voice = &VoiceConnection{}
  528. s.Lock()
  529. s.VoiceConnections[gID] = voice
  530. s.Unlock()
  531. }
  532. voice.Lock()
  533. voice.GuildID = gID
  534. voice.ChannelID = cID
  535. voice.deaf = deaf
  536. voice.mute = mute
  537. voice.session = s
  538. voice.Unlock()
  539. err = s.ChannelVoiceJoinManual(gID, cID, mute, deaf)
  540. if err != nil {
  541. return
  542. }
  543. // doesn't exactly work perfect yet.. TODO
  544. err = voice.waitUntilConnected()
  545. if err != nil {
  546. s.log(LogWarning, "error waiting for voice to connect, %s", err)
  547. voice.Close()
  548. return
  549. }
  550. return
  551. }
  552. // ChannelVoiceJoinManual initiates a voice session to a voice channel, but does not complete it.
  553. //
  554. // This should only be used when the VoiceServerUpdate will be intercepted and used elsewhere.
  555. //
  556. // gID : Guild ID of the channel to join.
  557. // cID : Channel ID of the channel to join, leave empty to disconnect.
  558. // mute : If true, you will be set to muted upon joining.
  559. // deaf : If true, you will be set to deafened upon joining.
  560. func (s *Session) ChannelVoiceJoinManual(gID, cID string, mute, deaf bool) (err error) {
  561. s.log(LogInformational, "called")
  562. var channelID *string
  563. if cID == "" {
  564. channelID = nil
  565. } else {
  566. channelID = &cID
  567. }
  568. // Send the request to Discord that we want to join the voice channel
  569. data := voiceChannelJoinOp{4, voiceChannelJoinData{&gID, channelID, mute, deaf}}
  570. s.wsMutex.Lock()
  571. err = s.wsConn.WriteJSON(data)
  572. s.wsMutex.Unlock()
  573. return
  574. }
  575. // onVoiceStateUpdate handles Voice State Update events on the data websocket.
  576. func (s *Session) onVoiceStateUpdate(st *VoiceStateUpdate) {
  577. // If we don't have a connection for the channel, don't bother
  578. if st.ChannelID == "" {
  579. return
  580. }
  581. // Check if we have a voice connection to update
  582. s.RLock()
  583. voice, exists := s.VoiceConnections[st.GuildID]
  584. s.RUnlock()
  585. if !exists {
  586. return
  587. }
  588. // We only care about events that are about us.
  589. if s.State.User.ID != st.UserID {
  590. return
  591. }
  592. // Store the SessionID for later use.
  593. voice.Lock()
  594. voice.UserID = st.UserID
  595. voice.sessionID = st.SessionID
  596. voice.ChannelID = st.ChannelID
  597. voice.Unlock()
  598. }
  599. // onVoiceServerUpdate handles the Voice Server Update data websocket event.
  600. //
  601. // This is also fired if the Guild's voice region changes while connected
  602. // to a voice channel. In that case, need to re-establish connection to
  603. // the new region endpoint.
  604. func (s *Session) onVoiceServerUpdate(st *VoiceServerUpdate) {
  605. s.log(LogInformational, "called")
  606. s.RLock()
  607. voice, exists := s.VoiceConnections[st.GuildID]
  608. s.RUnlock()
  609. // If no VoiceConnection exists, just skip this
  610. if !exists {
  611. return
  612. }
  613. // If currently connected to voice ws/udp, then disconnect.
  614. // Has no effect if not connected.
  615. voice.Close()
  616. // Store values for later use
  617. voice.Lock()
  618. voice.token = st.Token
  619. voice.endpoint = st.Endpoint
  620. voice.GuildID = st.GuildID
  621. voice.Unlock()
  622. // Open a connection to the voice server
  623. err := voice.open()
  624. if err != nil {
  625. s.log(LogError, "onVoiceServerUpdate voice.open, %s", err)
  626. }
  627. }
  628. type identifyOp struct {
  629. Op int `json:"op"`
  630. Data Identify `json:"d"`
  631. }
  632. // identify sends the identify packet to the gateway
  633. func (s *Session) identify() error {
  634. s.log(LogDebug, "called")
  635. // TODO: This is a temporary block of code to help
  636. // maintain backwards compatability
  637. if s.Compress == false {
  638. s.Identify.Compress = false
  639. }
  640. // TODO: This is a temporary block of code to help
  641. // maintain backwards compatability
  642. if s.Token != "" && s.Identify.Token == "" {
  643. s.Identify.Token = s.Token
  644. }
  645. // TODO: Below block should be refactored so ShardID and ShardCount
  646. // can be deprecated and their usage moved to the Session.Identify
  647. // struct
  648. if s.ShardCount > 1 {
  649. if s.ShardID >= s.ShardCount {
  650. return ErrWSShardBounds
  651. }
  652. s.Identify.Shard = &[2]int{s.ShardID, s.ShardCount}
  653. }
  654. // Send Identify packet to Discord
  655. op := identifyOp{2, s.Identify}
  656. s.log(LogDebug, "Identify Packet: \n%#v", op)
  657. s.wsMutex.Lock()
  658. err := s.wsConn.WriteJSON(op)
  659. s.wsMutex.Unlock()
  660. return err
  661. }
  662. func (s *Session) reconnect() {
  663. s.log(LogInformational, "called")
  664. var err error
  665. if s.ShouldReconnectOnError {
  666. wait := time.Duration(1)
  667. for {
  668. s.log(LogInformational, "trying to reconnect to gateway")
  669. err = s.Open()
  670. if err == nil {
  671. s.log(LogInformational, "successfully reconnected to gateway")
  672. // I'm not sure if this is actually needed.
  673. // if the gw reconnect works properly, voice should stay alive
  674. // However, there seems to be cases where something "weird"
  675. // happens. So we're doing this for now just to improve
  676. // stability in those edge cases.
  677. s.RLock()
  678. defer s.RUnlock()
  679. for _, v := range s.VoiceConnections {
  680. s.log(LogInformational, "reconnecting voice connection to guild %s", v.GuildID)
  681. go v.reconnect()
  682. // This is here just to prevent violently spamming the
  683. // voice reconnects
  684. time.Sleep(1 * time.Second)
  685. }
  686. return
  687. }
  688. // Certain race conditions can call reconnect() twice. If this happens, we
  689. // just break out of the reconnect loop
  690. if err == ErrWSAlreadyOpen {
  691. s.log(LogInformational, "Websocket already exists, no need to reconnect")
  692. return
  693. }
  694. s.log(LogError, "error reconnecting to gateway, %s", err)
  695. <-time.After(wait * time.Second)
  696. wait *= 2
  697. if wait > 600 {
  698. wait = 600
  699. }
  700. }
  701. }
  702. }
  703. // Close closes a websocket and stops all listening/heartbeat goroutines.
  704. // TODO: Add support for Voice WS/UDP
  705. func (s *Session) Close() error {
  706. return s.CloseWithCode(websocket.CloseNormalClosure)
  707. }
  708. // CloseWithCode closes a websocket using the provided closeCode and stops all
  709. // listening/heartbeat goroutines.
  710. // TODO: Add support for Voice WS/UDP connections
  711. func (s *Session) CloseWithCode(closeCode int) (err error) {
  712. s.log(LogInformational, "called")
  713. s.Lock()
  714. s.DataReady = false
  715. if s.listening != nil {
  716. s.log(LogInformational, "closing listening channel")
  717. close(s.listening)
  718. s.listening = nil
  719. }
  720. // TODO: Close all active Voice Connections too
  721. // this should force stop any reconnecting voice channels too
  722. if s.wsConn != nil {
  723. s.log(LogInformational, "sending close frame")
  724. // To cleanly close a connection, a client should send a close
  725. // frame and wait for the server to close the connection.
  726. s.wsMutex.Lock()
  727. err := s.wsConn.WriteMessage(websocket.CloseMessage, websocket.FormatCloseMessage(closeCode, ""))
  728. s.wsMutex.Unlock()
  729. if err != nil {
  730. s.log(LogInformational, "error closing websocket, %s", err)
  731. }
  732. // TODO: Wait for Discord to actually close the connection.
  733. time.Sleep(1 * time.Second)
  734. s.log(LogInformational, "closing gateway websocket")
  735. err = s.wsConn.Close()
  736. if err != nil {
  737. s.log(LogInformational, "error closing websocket, %s", err)
  738. }
  739. s.wsConn = nil
  740. }
  741. s.Unlock()
  742. s.log(LogInformational, "emit disconnect event")
  743. s.handleEvent(disconnectEventType, &Disconnect{})
  744. return
  745. }