github.com/meowstercatel/discordgo@v0.0.0-20250615204139-29b43d676735/wsapi.go (about)

     1  // Discordgo - Discord bindings for Go
     2  // Available at https://github.com/bwmarrin/discordgo
     3  
     4  // Copyright 2015-2016 Bruce Marriner <bruce@sqls.net>.  All rights reserved.
     5  // Use of this source code is governed by a BSD-style
     6  // license that can be found in the LICENSE file.
     7  
     8  // This file contains low level functions for interacting with the Discord
     9  // data websocket interface.
    10  
    11  package discordgo
    12  
    13  import (
    14  	"bytes"
    15  	"compress/zlib"
    16  	"encoding/json"
    17  	"errors"
    18  	"fmt"
    19  	"io"
    20  	"net/http"
    21  	"sync/atomic"
    22  	"time"
    23  
    24  	"github.com/gorilla/websocket"
    25  )
    26  
    27  // ErrWSAlreadyOpen is thrown when you attempt to open
    28  // a websocket that already is open.
    29  var ErrWSAlreadyOpen = errors.New("web socket already opened")
    30  
    31  // ErrWSNotFound is thrown when you attempt to use a websocket
    32  // that doesn't exist
    33  var ErrWSNotFound = errors.New("no websocket connection exists")
    34  
    35  // ErrWSShardBounds is thrown when you try to use a shard ID that is
    36  // more than the total shard count
    37  var ErrWSShardBounds = errors.New("ShardID must be less than ShardCount")
    38  
    39  type resumePacket struct {
    40  	Op   int `json:"op"`
    41  	Data struct {
    42  		Token     string `json:"token"`
    43  		SessionID string `json:"session_id"`
    44  		Sequence  int64  `json:"seq"`
    45  	} `json:"d"`
    46  }
    47  
    48  // Open creates a websocket connection to Discord.
    49  // See: https://discord.com/developers/docs/topics/gateway#connecting
    50  func (s *Session) Open() error {
    51  	s.log(LogInformational, "called")
    52  
    53  	var err error
    54  
    55  	// Prevent Open or other major Session functions from
    56  	// being called while Open is still running.
    57  	s.Lock()
    58  	defer s.Unlock()
    59  
    60  	// If the websock is already open, bail out here.
    61  	if s.wsConn != nil {
    62  		return ErrWSAlreadyOpen
    63  	}
    64  
    65  	// Get the gateway to use for the Websocket connection
    66  	if s.gateway == "" {
    67  		s.gateway, err = s.Gateway()
    68  		if err != nil {
    69  			return err
    70  		}
    71  
    72  		// Add the version and encoding to the URL
    73  		s.gateway = s.gateway + "?v=" + APIVersion + "&encoding=json"
    74  	}
    75  
    76  	// Connect to the Gateway
    77  	s.log(LogInformational, "connecting to gateway %s", s.gateway)
    78  	header := http.Header{}
    79  	header.Add("accept-encoding", "zlib")
    80  	s.wsConn, _, err = s.Dialer.Dial(s.gateway, header)
    81  	if err != nil {
    82  		s.log(LogError, "error connecting to gateway %s, %s", s.gateway, err)
    83  		s.gateway = "" // clear cached gateway
    84  		s.wsConn = nil // Just to be safe.
    85  		return err
    86  	}
    87  
    88  	s.wsConn.SetCloseHandler(func(code int, text string) error {
    89  		return nil
    90  	})
    91  
    92  	defer func() {
    93  		// because of this, all code below must set err to the error
    94  		// when exiting with an error :)  Maybe someone has a better
    95  		// way :)
    96  		if err != nil {
    97  			s.wsConn.Close()
    98  			s.wsConn = nil
    99  		}
   100  	}()
   101  
   102  	// The first response from Discord should be an Op 10 (Hello) Packet.
   103  	// When processed by onEvent the heartbeat goroutine will be started.
   104  	mt, m, err := s.wsConn.ReadMessage()
   105  	if err != nil {
   106  		return err
   107  	}
   108  	e, err := s.onEvent(mt, m)
   109  	if err != nil {
   110  		return err
   111  	}
   112  	if e.Operation != 10 {
   113  		err = fmt.Errorf("expecting Op 10, got Op %d instead", e.Operation)
   114  		return err
   115  	}
   116  	s.log(LogInformational, "Op 10 Hello Packet received from Discord")
   117  	s.LastHeartbeatAck = time.Now().UTC()
   118  	var h helloOp
   119  	if err = json.Unmarshal(e.RawData, &h); err != nil {
   120  		err = fmt.Errorf("error unmarshalling helloOp, %s", err)
   121  		return err
   122  	}
   123  
   124  	// Now we send either an Op 2 Identity if this is a brand new
   125  	// connection or Op 6 Resume if we are resuming an existing connection.
   126  	sequence := atomic.LoadInt64(s.sequence)
   127  	if s.sessionID == "" && sequence == 0 {
   128  
   129  		// Send Op 2 Identity Packet
   130  		err = s.identify()
   131  		if err != nil {
   132  			err = fmt.Errorf("error sending identify packet to gateway, %s, %s", s.gateway, err)
   133  			return err
   134  		}
   135  
   136  	} else {
   137  
   138  		// Send Op 6 Resume Packet
   139  		p := resumePacket{}
   140  		p.Op = 6
   141  		p.Data.Token = s.Token
   142  		p.Data.SessionID = s.sessionID
   143  		p.Data.Sequence = sequence
   144  
   145  		s.log(LogInformational, "sending resume packet to gateway")
   146  		s.wsMutex.Lock()
   147  		err = s.wsConn.WriteJSON(p)
   148  		s.wsMutex.Unlock()
   149  		if err != nil {
   150  			err = fmt.Errorf("error sending gateway resume packet, %s, %s", s.gateway, err)
   151  			return err
   152  		}
   153  
   154  	}
   155  
   156  	// A basic state is a hard requirement for Voice.
   157  	// We create it here so the below READY/RESUMED packet can populate
   158  	// the state :)
   159  	// XXX: Move to New() func?
   160  	if s.State == nil {
   161  		state := NewState()
   162  		state.TrackChannels = false
   163  		state.TrackEmojis = false
   164  		state.TrackMembers = false
   165  		state.TrackRoles = false
   166  		state.TrackVoice = false
   167  		s.State = state
   168  	}
   169  
   170  	// Now Discord should send us a READY or RESUMED packet.
   171  	mt, m, err = s.wsConn.ReadMessage()
   172  	if err != nil {
   173  		return err
   174  	}
   175  	e, err = s.onEvent(mt, m)
   176  	if err != nil {
   177  		return err
   178  	}
   179  	if e.Type != `READY` && e.Type != `RESUMED` {
   180  		// This is not fatal, but it does not follow their API documentation.
   181  		s.log(LogWarning, "Expected READY/RESUMED, instead got:\n%#v\n", e)
   182  	}
   183  	s.log(LogInformational, "First Packet:\n%#v\n", e)
   184  
   185  	s.log(LogInformational, "We are now connected to Discord, emitting connect event")
   186  	s.handleEvent(connectEventType, &Connect{})
   187  
   188  	// A VoiceConnections map is a hard requirement for Voice.
   189  	// XXX: can this be moved to when opening a voice connection?
   190  	if s.VoiceConnections == nil {
   191  		s.log(LogInformational, "creating new VoiceConnections map")
   192  		s.VoiceConnections = make(map[string]*VoiceConnection)
   193  	}
   194  
   195  	// Create listening chan outside of listen, as it needs to happen inside the
   196  	// mutex lock and needs to exist before calling heartbeat and listen
   197  	// go rountines.
   198  	s.listening = make(chan interface{})
   199  
   200  	// Start sending heartbeats and reading messages from Discord.
   201  	go s.heartbeat(s.wsConn, s.listening, h.HeartbeatInterval)
   202  	go s.listen(s.wsConn, s.listening)
   203  
   204  	s.log(LogInformational, "exiting")
   205  	return nil
   206  }
   207  
   208  // listen polls the websocket connection for events, it will stop when the
   209  // listening channel is closed, or an error occurs.
   210  func (s *Session) listen(wsConn *websocket.Conn, listening <-chan interface{}) {
   211  
   212  	s.log(LogInformational, "called")
   213  
   214  	for {
   215  
   216  		messageType, message, err := wsConn.ReadMessage()
   217  
   218  		if err != nil {
   219  
   220  			// Detect if we have been closed manually. If a Close() has already
   221  			// happened, the websocket we are listening on will be different to
   222  			// the current session.
   223  			s.RLock()
   224  			sameConnection := s.wsConn == wsConn
   225  			s.RUnlock()
   226  
   227  			if sameConnection {
   228  
   229  				s.log(LogWarning, "error reading from gateway %s websocket, %s", s.gateway, err)
   230  				// There has been an error reading, close the websocket so that
   231  				// OnDisconnect event is emitted.
   232  				err := s.Close()
   233  				if err != nil {
   234  					s.log(LogWarning, "error closing session connection, %s", err)
   235  				}
   236  
   237  				s.log(LogInformational, "calling reconnect() now")
   238  				s.reconnect()
   239  			}
   240  
   241  			return
   242  		}
   243  
   244  		select {
   245  
   246  		case <-listening:
   247  			return
   248  
   249  		default:
   250  			s.onEvent(messageType, message)
   251  
   252  		}
   253  	}
   254  }
   255  
   256  type heartbeatOp struct {
   257  	Op   int   `json:"op"`
   258  	Data int64 `json:"d"`
   259  }
   260  
   261  type helloOp struct {
   262  	HeartbeatInterval time.Duration `json:"heartbeat_interval"`
   263  }
   264  
   265  // FailedHeartbeatAcks is the Number of heartbeat intervals to wait until forcing a connection restart.
   266  const FailedHeartbeatAcks time.Duration = 5 * time.Millisecond
   267  
   268  // HeartbeatLatency returns the latency between heartbeat acknowledgement and heartbeat send.
   269  func (s *Session) HeartbeatLatency() time.Duration {
   270  
   271  	return s.LastHeartbeatAck.Sub(s.LastHeartbeatSent)
   272  
   273  }
   274  
   275  // heartbeat sends regular heartbeats to Discord so it knows the client
   276  // is still connected.  If you do not send these heartbeats Discord will
   277  // disconnect the websocket connection after a few seconds.
   278  func (s *Session) heartbeat(wsConn *websocket.Conn, listening <-chan interface{}, heartbeatIntervalMsec time.Duration) {
   279  
   280  	s.log(LogInformational, "called")
   281  
   282  	if listening == nil || wsConn == nil {
   283  		return
   284  	}
   285  
   286  	var err error
   287  	ticker := time.NewTicker(heartbeatIntervalMsec * time.Millisecond)
   288  	defer ticker.Stop()
   289  
   290  	for {
   291  		s.RLock()
   292  		last := s.LastHeartbeatAck
   293  		s.RUnlock()
   294  		sequence := atomic.LoadInt64(s.sequence)
   295  		s.log(LogDebug, "sending gateway websocket heartbeat seq %d", sequence)
   296  		s.wsMutex.Lock()
   297  		s.LastHeartbeatSent = time.Now().UTC()
   298  		err = wsConn.WriteJSON(heartbeatOp{1, sequence})
   299  		s.wsMutex.Unlock()
   300  		if err != nil || time.Now().UTC().Sub(last) > (heartbeatIntervalMsec*FailedHeartbeatAcks) {
   301  			if err != nil {
   302  				s.log(LogError, "error sending heartbeat to gateway %s, %s", s.gateway, err)
   303  			} else {
   304  				s.log(LogError, "haven't gotten a heartbeat ACK in %v, triggering a reconnection", time.Now().UTC().Sub(last))
   305  			}
   306  			s.Close()
   307  			s.reconnect()
   308  			return
   309  		}
   310  		s.Lock()
   311  		s.DataReady = true
   312  		s.Unlock()
   313  
   314  		select {
   315  		case <-ticker.C:
   316  			// continue loop and send heartbeat
   317  		case <-listening:
   318  			return
   319  		}
   320  	}
   321  }
   322  
   323  // UpdateStatusData is provided to UpdateStatusComplex()
   324  type UpdateStatusData struct {
   325  	IdleSince  *int        `json:"since"`
   326  	Activities []*Activity `json:"activities"`
   327  	AFK        bool        `json:"afk"`
   328  	Status     string      `json:"status"`
   329  }
   330  
   331  type updateStatusOp struct {
   332  	Op   int              `json:"op"`
   333  	Data UpdateStatusData `json:"d"`
   334  }
   335  
   336  func newUpdateStatusData(idle int, activityType ActivityType, name, url string) *UpdateStatusData {
   337  	usd := &UpdateStatusData{
   338  		Status: "online",
   339  	}
   340  
   341  	if idle > 0 {
   342  		usd.IdleSince = &idle
   343  	}
   344  
   345  	if name != "" {
   346  		usd.Activities = []*Activity{{
   347  			Name: name,
   348  			Type: activityType,
   349  			URL:  url,
   350  		}}
   351  	}
   352  
   353  	return usd
   354  }
   355  
   356  // UpdateGameStatus is used to update the user's status.
   357  // If idle>0 then set status to idle.
   358  // If name!="" then set game.
   359  // if otherwise, set status to active, and no activity.
   360  func (s *Session) UpdateGameStatus(idle int, name string) (err error) {
   361  	return s.UpdateStatusComplex(*newUpdateStatusData(idle, ActivityTypeGame, name, ""))
   362  }
   363  
   364  // UpdateWatchStatus is used to update the user's watch status.
   365  // If idle>0 then set status to idle.
   366  // If name!="" then set movie/stream.
   367  // if otherwise, set status to active, and no activity.
   368  func (s *Session) UpdateWatchStatus(idle int, name string) (err error) {
   369  	return s.UpdateStatusComplex(*newUpdateStatusData(idle, ActivityTypeWatching, name, ""))
   370  }
   371  
   372  // UpdateStreamingStatus is used to update the user's streaming status.
   373  // If idle>0 then set status to idle.
   374  // If name!="" then set game.
   375  // If name!="" and url!="" then set the status type to streaming with the URL set.
   376  // if otherwise, set status to active, and no game.
   377  func (s *Session) UpdateStreamingStatus(idle int, name string, url string) (err error) {
   378  	gameType := ActivityTypeGame
   379  	if url != "" {
   380  		gameType = ActivityTypeStreaming
   381  	}
   382  	return s.UpdateStatusComplex(*newUpdateStatusData(idle, gameType, name, url))
   383  }
   384  
   385  // UpdateListeningStatus is used to set the user to "Listening to..."
   386  // If name!="" then set to what user is listening to
   387  // Else, set user to active and no activity.
   388  func (s *Session) UpdateListeningStatus(name string) (err error) {
   389  	return s.UpdateStatusComplex(*newUpdateStatusData(0, ActivityTypeListening, name, ""))
   390  }
   391  
   392  // UpdateCustomStatus is used to update the user's custom status.
   393  // If state!="" then set the custom status.
   394  // Else, set user to active and remove the custom status.
   395  func (s *Session) UpdateCustomStatus(state string) (err error) {
   396  	data := UpdateStatusData{
   397  		Status: "online",
   398  	}
   399  
   400  	if state != "" {
   401  		// Discord requires a non-empty activity name, therefore we provide "Custom Status" as a placeholder.
   402  		data.Activities = []*Activity{{
   403  			Name:  "Custom Status",
   404  			Type:  ActivityTypeCustom,
   405  			State: state,
   406  		}}
   407  	}
   408  
   409  	return s.UpdateStatusComplex(data)
   410  }
   411  
   412  // UpdateStatusComplex allows for sending the raw status update data untouched by discordgo.
   413  func (s *Session) UpdateStatusComplex(usd UpdateStatusData) (err error) {
   414  	// The comment does say "untouched by discordgo", but we might need to lie a bit here.
   415  	// The Discord documentation lists `activities` as being nullable, but in practice this
   416  	// doesn't seem to be the case. I had filed an issue about this at
   417  	// https://github.com/discord/discord-api-docs/issues/2559, but as of writing this
   418  	// haven't had any movement on it, so at this point I'm assuming this is an error,
   419  	// and am fixing this bug accordingly. Because sending `null` for `activities` instantly
   420  	// disconnects us, I think that disallowing it from being sent in `UpdateStatusComplex`
   421  	// isn't that big of an issue.
   422  	if usd.Activities == nil {
   423  		usd.Activities = make([]*Activity, 0)
   424  	}
   425  
   426  	s.RLock()
   427  	defer s.RUnlock()
   428  	if s.wsConn == nil {
   429  		return ErrWSNotFound
   430  	}
   431  
   432  	s.wsMutex.Lock()
   433  	err = s.wsConn.WriteJSON(updateStatusOp{3, usd})
   434  	s.wsMutex.Unlock()
   435  
   436  	return
   437  }
   438  
   439  type requestGuildMembersData struct {
   440  	// TODO: Deprecated. Use string instead of []string
   441  	GuildIDs  []string  `json:"guild_id"`
   442  	Query     *string   `json:"query,omitempty"`
   443  	UserIDs   *[]string `json:"user_ids,omitempty"`
   444  	Limit     int       `json:"limit"`
   445  	Nonce     string    `json:"nonce,omitempty"`
   446  	Presences bool      `json:"presences"`
   447  }
   448  
   449  type requestGuildMembersOp struct {
   450  	Op   int                     `json:"op"`
   451  	Data requestGuildMembersData `json:"d"`
   452  }
   453  
   454  // RequestGuildMembers requests guild members from the gateway
   455  // The gateway responds with GuildMembersChunk events
   456  // guildID   : Single Guild ID to request members of
   457  // query     : String that username starts with, leave empty to return all members
   458  // limit     : Max number of items to return, or 0 to request all members matched
   459  // nonce     : Nonce to identify the Guild Members Chunk response
   460  // presences : Whether to request presences of guild members
   461  func (s *Session) RequestGuildMembers(guildID, query string, limit int, nonce string, presences bool) error {
   462  	return s.RequestGuildMembersBatch([]string{guildID}, query, limit, nonce, presences)
   463  }
   464  
   465  // RequestGuildMembersList requests guild members from the gateway
   466  // The gateway responds with GuildMembersChunk events
   467  // guildID   : Single Guild ID to request members of
   468  // userIDs   : IDs of users to fetch
   469  // limit     : Max number of items to return, or 0 to request all members matched
   470  // nonce     : Nonce to identify the Guild Members Chunk response
   471  // presences : Whether to request presences of guild members
   472  func (s *Session) RequestGuildMembersList(guildID string, userIDs []string, limit int, nonce string, presences bool) error {
   473  	return s.RequestGuildMembersBatchList([]string{guildID}, userIDs, limit, nonce, presences)
   474  }
   475  
   476  // RequestGuildMembersBatch requests guild members from the gateway
   477  // The gateway responds with GuildMembersChunk events
   478  // guildID   : Slice of guild IDs to request members of
   479  // query     : String that username starts with, leave empty to return all members
   480  // limit     : Max number of items to return, or 0 to request all members matched
   481  // nonce     : Nonce to identify the Guild Members Chunk response
   482  // presences : Whether to request presences of guild members
   483  //
   484  // NOTE: this function is deprecated, please use RequestGuildMembers instead
   485  func (s *Session) RequestGuildMembersBatch(guildIDs []string, query string, limit int, nonce string, presences bool) (err error) {
   486  	data := requestGuildMembersData{
   487  		GuildIDs:  guildIDs,
   488  		Query:     &query,
   489  		Limit:     limit,
   490  		Nonce:     nonce,
   491  		Presences: presences,
   492  	}
   493  	err = s.requestGuildMembers(data)
   494  	return
   495  }
   496  
   497  // RequestGuildMembersBatchList requests guild members from the gateway
   498  // The gateway responds with GuildMembersChunk events
   499  // guildID   : Slice of guild IDs to request members of
   500  // userIDs   : IDs of users to fetch
   501  // limit     : Max number of items to return, or 0 to request all members matched
   502  // nonce     : Nonce to identify the Guild Members Chunk response
   503  // presences : Whether to request presences of guild members
   504  //
   505  // NOTE: this function is deprecated, please use RequestGuildMembersList instead
   506  func (s *Session) RequestGuildMembersBatchList(guildIDs []string, userIDs []string, limit int, nonce string, presences bool) (err error) {
   507  	data := requestGuildMembersData{
   508  		GuildIDs:  guildIDs,
   509  		UserIDs:   &userIDs,
   510  		Limit:     limit,
   511  		Nonce:     nonce,
   512  		Presences: presences,
   513  	}
   514  	err = s.requestGuildMembers(data)
   515  	return
   516  }
   517  
   518  // GatewayWriteStruct allows for sending raw gateway structs over the gateway.
   519  func (s *Session) GatewayWriteStruct(data interface{}) (err error) {
   520  	s.RLock()
   521  	defer s.RUnlock()
   522  	if s.wsConn == nil {
   523  		return ErrWSNotFound
   524  	}
   525  
   526  	s.wsMutex.Lock()
   527  	err = s.wsConn.WriteJSON(data)
   528  	s.wsMutex.Unlock()
   529  
   530  	return err
   531  }
   532  
   533  func (s *Session) requestGuildMembers(data requestGuildMembersData) (err error) {
   534  	s.log(LogInformational, "called")
   535  
   536  	s.RLock()
   537  	defer s.RUnlock()
   538  	if s.wsConn == nil {
   539  		return ErrWSNotFound
   540  	}
   541  
   542  	s.wsMutex.Lock()
   543  	err = s.wsConn.WriteJSON(requestGuildMembersOp{8, data})
   544  	s.wsMutex.Unlock()
   545  
   546  	return
   547  }
   548  
   549  // onEvent is the "event handler" for all messages received on the
   550  // Discord Gateway API websocket connection.
   551  //
   552  // If you use the AddHandler() function to register a handler for a
   553  // specific event this function will pass the event along to that handler.
   554  //
   555  // If you use the AddHandler() function to register a handler for the
   556  // "OnEvent" event then all events will be passed to that handler.
   557  func (s *Session) onEvent(messageType int, message []byte) (*Event, error) {
   558  
   559  	var err error
   560  	var reader io.Reader
   561  	reader = bytes.NewBuffer(message)
   562  
   563  	// If this is a compressed message, uncompress it.
   564  	if messageType == websocket.BinaryMessage {
   565  
   566  		z, err2 := zlib.NewReader(reader)
   567  		if err2 != nil {
   568  			s.log(LogError, "error uncompressing websocket message, %s", err)
   569  			return nil, err2
   570  		}
   571  
   572  		defer func() {
   573  			err3 := z.Close()
   574  			if err3 != nil {
   575  				s.log(LogWarning, "error closing zlib, %s", err)
   576  			}
   577  		}()
   578  
   579  		reader = z
   580  	}
   581  
   582  	// Decode the event into an Event struct.
   583  	var e *Event
   584  	decoder := json.NewDecoder(reader)
   585  	if err = decoder.Decode(&e); err != nil {
   586  		s.log(LogError, "error decoding websocket message, %s", err)
   587  		return e, err
   588  	}
   589  
   590  	s.log(LogDebug, "Op: %d, Seq: %d, Type: %s, Data: %s\n\n", e.Operation, e.Sequence, e.Type, string(e.RawData))
   591  
   592  	// Ping request.
   593  	// Must respond with a heartbeat packet within 5 seconds
   594  	if e.Operation == 1 {
   595  		s.log(LogInformational, "sending heartbeat in response to Op1")
   596  		s.wsMutex.Lock()
   597  		err = s.wsConn.WriteJSON(heartbeatOp{1, atomic.LoadInt64(s.sequence)})
   598  		s.wsMutex.Unlock()
   599  		if err != nil {
   600  			s.log(LogError, "error sending heartbeat in response to Op1")
   601  			return e, err
   602  		}
   603  
   604  		return e, nil
   605  	}
   606  
   607  	// Reconnect
   608  	// Must immediately disconnect from gateway and reconnect to new gateway.
   609  	if e.Operation == 7 {
   610  		s.log(LogInformational, "Closing and reconnecting in response to Op7")
   611  		s.CloseWithCode(websocket.CloseServiceRestart)
   612  		s.reconnect()
   613  		return e, nil
   614  	}
   615  
   616  	// Invalid Session
   617  	// Must respond with a Identify packet.
   618  	if e.Operation == 9 {
   619  
   620  		s.log(LogInformational, "sending identify packet to gateway in response to Op9")
   621  
   622  		err = s.identify()
   623  		if err != nil {
   624  			s.log(LogWarning, "error sending gateway identify packet, %s, %s", s.gateway, err)
   625  			return e, err
   626  		}
   627  
   628  		return e, nil
   629  	}
   630  
   631  	if e.Operation == 10 {
   632  		// Op10 is handled by Open()
   633  		return e, nil
   634  	}
   635  
   636  	if e.Operation == 11 {
   637  		s.Lock()
   638  		s.LastHeartbeatAck = time.Now().UTC()
   639  		s.Unlock()
   640  		s.log(LogDebug, "got heartbeat ACK")
   641  		return e, nil
   642  	}
   643  
   644  	// Do not try to Dispatch a non-Dispatch Message
   645  	if e.Operation != 0 {
   646  		// But we probably should be doing something with them.
   647  		// TEMP
   648  		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))
   649  		return e, nil
   650  	}
   651  
   652  	// Store the message sequence
   653  	atomic.StoreInt64(s.sequence, e.Sequence)
   654  
   655  	// Map event to registered event handlers and pass it along to any registered handlers.
   656  	if eh, ok := registeredInterfaceProviders[e.Type]; ok {
   657  		e.Struct = eh.New()
   658  
   659  		// Attempt to unmarshal our event.
   660  		if err = json.Unmarshal(e.RawData, e.Struct); err != nil {
   661  			s.log(LogError, "error unmarshalling %s event, %s", e.Type, err)
   662  		}
   663  
   664  		// Send event to any registered event handlers for it's type.
   665  		// Because the above doesn't cancel this, in case of an error
   666  		// the struct could be partially populated or at default values.
   667  		// However, most errors are due to a single field and I feel
   668  		// it's better to pass along what we received than nothing at all.
   669  		// TODO: Think about that decision :)
   670  		// Either way, READY events must fire, even with errors.
   671  		s.handleEvent(e.Type, e.Struct)
   672  	} else {
   673  		s.log(LogWarning, "unknown event: Op: %d, Seq: %d, Type: %s, Data: %s", e.Operation, e.Sequence, e.Type, string(e.RawData))
   674  	}
   675  
   676  	// For legacy reasons, we send the raw event also, this could be useful for handling unknown events.
   677  	s.handleEvent(eventEventType, e)
   678  
   679  	return e, nil
   680  }
   681  
   682  // ------------------------------------------------------------------------------------------------
   683  // Code related to voice connections that initiate over the data websocket
   684  // ------------------------------------------------------------------------------------------------
   685  
   686  type voiceChannelJoinData struct {
   687  	GuildID   *string `json:"guild_id"`
   688  	ChannelID *string `json:"channel_id"`
   689  	SelfMute  bool    `json:"self_mute"`
   690  	SelfDeaf  bool    `json:"self_deaf"`
   691  }
   692  
   693  type voiceChannelJoinOp struct {
   694  	Op   int                  `json:"op"`
   695  	Data voiceChannelJoinData `json:"d"`
   696  }
   697  
   698  // ChannelVoiceJoin joins the session user to a voice channel.
   699  //
   700  //    gID     : Guild ID of the channel to join.
   701  //    cID     : Channel ID of the channel to join.
   702  //    mute    : If true, you will be set to muted upon joining.
   703  //    deaf    : If true, you will be set to deafened upon joining.
   704  func (s *Session) ChannelVoiceJoin(gID, cID string, mute, deaf bool) (voice *VoiceConnection, err error) {
   705  
   706  	s.log(LogInformational, "called")
   707  
   708  	s.RLock()
   709  	voice, _ = s.VoiceConnections[gID]
   710  	s.RUnlock()
   711  
   712  	if voice == nil {
   713  		voice = &VoiceConnection{}
   714  		s.Lock()
   715  		s.VoiceConnections[gID] = voice
   716  		s.Unlock()
   717  	}
   718  
   719  	voice.Lock()
   720  	voice.GuildID = gID
   721  	voice.ChannelID = cID
   722  	voice.deaf = deaf
   723  	voice.mute = mute
   724  	voice.session = s
   725  	voice.Unlock()
   726  
   727  	err = s.ChannelVoiceJoinManual(gID, cID, mute, deaf)
   728  	if err != nil {
   729  		return
   730  	}
   731  
   732  	// doesn't exactly work perfect yet.. TODO
   733  	err = voice.waitUntilConnected()
   734  	if err != nil {
   735  		s.log(LogWarning, "error waiting for voice to connect, %s", err)
   736  		voice.Close()
   737  		return
   738  	}
   739  
   740  	return
   741  }
   742  
   743  // ChannelVoiceJoinManual initiates a voice session to a voice channel, but does not complete it.
   744  //
   745  // This should only be used when the VoiceServerUpdate will be intercepted and used elsewhere.
   746  //
   747  //    gID     : Guild ID of the channel to join.
   748  //    cID     : Channel ID of the channel to join, leave empty to disconnect.
   749  //    mute    : If true, you will be set to muted upon joining.
   750  //    deaf    : If true, you will be set to deafened upon joining.
   751  func (s *Session) ChannelVoiceJoinManual(gID, cID string, mute, deaf bool) (err error) {
   752  
   753  	s.log(LogInformational, "called")
   754  
   755  	var channelID *string
   756  	if cID == "" {
   757  		channelID = nil
   758  	} else {
   759  		channelID = &cID
   760  	}
   761  
   762  	// Send the request to Discord that we want to join the voice channel
   763  	data := voiceChannelJoinOp{4, voiceChannelJoinData{&gID, channelID, mute, deaf}}
   764  	s.wsMutex.Lock()
   765  	err = s.wsConn.WriteJSON(data)
   766  	s.wsMutex.Unlock()
   767  	return
   768  }
   769  
   770  // onVoiceStateUpdate handles Voice State Update events on the data websocket.
   771  func (s *Session) onVoiceStateUpdate(st *VoiceStateUpdate) {
   772  
   773  	// If we don't have a connection for the channel, don't bother
   774  	if st.ChannelID == "" {
   775  		return
   776  	}
   777  
   778  	// Check if we have a voice connection to update
   779  	s.RLock()
   780  	voice, exists := s.VoiceConnections[st.GuildID]
   781  	s.RUnlock()
   782  	if !exists {
   783  		return
   784  	}
   785  
   786  	// We only care about events that are about us.
   787  	if s.State.User.ID != st.UserID {
   788  		return
   789  	}
   790  
   791  	// Store the SessionID for later use.
   792  	voice.Lock()
   793  	voice.UserID = st.UserID
   794  	voice.sessionID = st.SessionID
   795  	voice.ChannelID = st.ChannelID
   796  	voice.Unlock()
   797  }
   798  
   799  // onVoiceServerUpdate handles the Voice Server Update data websocket event.
   800  //
   801  // This is also fired if the Guild's voice region changes while connected
   802  // to a voice channel.  In that case, need to re-establish connection to
   803  // the new region endpoint.
   804  func (s *Session) onVoiceServerUpdate(st *VoiceServerUpdate) {
   805  
   806  	s.log(LogInformational, "called")
   807  
   808  	s.RLock()
   809  	voice, exists := s.VoiceConnections[st.GuildID]
   810  	s.RUnlock()
   811  
   812  	// If no VoiceConnection exists, just skip this
   813  	if !exists {
   814  		return
   815  	}
   816  
   817  	// If currently connected to voice ws/udp, then disconnect.
   818  	// Has no effect if not connected.
   819  	voice.Close()
   820  
   821  	// Store values for later use
   822  	voice.Lock()
   823  	voice.token = st.Token
   824  	voice.endpoint = st.Endpoint
   825  	voice.GuildID = st.GuildID
   826  	voice.Unlock()
   827  
   828  	// Open a connection to the voice server
   829  	err := voice.open()
   830  	if err != nil {
   831  		s.log(LogError, "onVoiceServerUpdate voice.open, %s", err)
   832  	}
   833  }
   834  
   835  type identifyOp struct {
   836  	Op   int      `json:"op"`
   837  	Data Identify `json:"d"`
   838  }
   839  
   840  // identify sends the identify packet to the gateway
   841  func (s *Session) identify() error {
   842  	s.log(LogDebug, "called")
   843  
   844  	// TODO: This is a temporary block of code to help
   845  	// maintain backwards compatibility
   846  	if s.Compress == false {
   847  		s.Identify.Compress = false
   848  	}
   849  
   850  	// TODO: This is a temporary block of code to help
   851  	// maintain backwards compatibility
   852  	if s.Token != "" && s.Identify.Token == "" {
   853  		s.Identify.Token = s.Token
   854  	}
   855  
   856  	// TODO: Below block should be refactored so ShardID and ShardCount
   857  	// can be deprecated and their usage moved to the Session.Identify
   858  	// struct
   859  	if s.ShardCount > 1 {
   860  
   861  		if s.ShardID >= s.ShardCount {
   862  			return ErrWSShardBounds
   863  		}
   864  
   865  		s.Identify.Shard = &[2]int{s.ShardID, s.ShardCount}
   866  	}
   867  
   868  	// Send Identify packet to Discord
   869  	op := identifyOp{2, s.Identify}
   870  	s.log(LogDebug, "Identify Packet: \n%#v", op)
   871  	s.wsMutex.Lock()
   872  	err := s.wsConn.WriteJSON(op)
   873  	s.wsMutex.Unlock()
   874  
   875  	return err
   876  }
   877  
   878  func (s *Session) reconnect() {
   879  
   880  	s.log(LogInformational, "called")
   881  
   882  	var err error
   883  
   884  	if s.ShouldReconnectOnError {
   885  
   886  		wait := time.Duration(1)
   887  
   888  		for {
   889  			s.log(LogInformational, "trying to reconnect to gateway")
   890  
   891  			err = s.Open()
   892  			if err == nil {
   893  				s.log(LogInformational, "successfully reconnected to gateway")
   894  
   895  				// I'm not sure if this is actually needed.
   896  				// if the gw reconnect works properly, voice should stay alive
   897  				// However, there seems to be cases where something "weird"
   898  				// happens.  So we're doing this for now just to improve
   899  				// stability in those edge cases.
   900  				if s.ShouldReconnectVoiceOnSessionError {
   901  					s.RLock()
   902  					defer s.RUnlock()
   903  					for _, v := range s.VoiceConnections {
   904  
   905  						s.log(LogInformational, "reconnecting voice connection to guild %s", v.GuildID)
   906  						go v.reconnect()
   907  
   908  						// This is here just to prevent violently spamming the
   909  						// voice reconnects
   910  						time.Sleep(1 * time.Second)
   911  					}
   912  				}
   913  				return
   914  			}
   915  
   916  			// Certain race conditions can call reconnect() twice. If this happens, we
   917  			// just break out of the reconnect loop
   918  			if err == ErrWSAlreadyOpen {
   919  				s.log(LogInformational, "Websocket already exists, no need to reconnect")
   920  				return
   921  			}
   922  
   923  			s.log(LogError, "error reconnecting to gateway, %s", err)
   924  
   925  			<-time.After(wait * time.Second)
   926  			wait *= 2
   927  			if wait > 600 {
   928  				wait = 600
   929  			}
   930  		}
   931  	}
   932  }
   933  
   934  // Close closes a websocket and stops all listening/heartbeat goroutines.
   935  // TODO: Add support for Voice WS/UDP
   936  func (s *Session) Close() error {
   937  	return s.CloseWithCode(websocket.CloseNormalClosure)
   938  }
   939  
   940  // CloseWithCode closes a websocket using the provided closeCode and stops all
   941  // listening/heartbeat goroutines.
   942  // TODO: Add support for Voice WS/UDP connections
   943  func (s *Session) CloseWithCode(closeCode int) (err error) {
   944  
   945  	s.log(LogInformational, "called")
   946  	s.Lock()
   947  
   948  	s.DataReady = false
   949  
   950  	if s.listening != nil {
   951  		s.log(LogInformational, "closing listening channel")
   952  		close(s.listening)
   953  		s.listening = nil
   954  	}
   955  
   956  	// TODO: Close all active Voice Connections too
   957  	// this should force stop any reconnecting voice channels too
   958  
   959  	if s.wsConn != nil {
   960  
   961  		s.log(LogInformational, "sending close frame")
   962  		// To cleanly close a connection, a client should send a close
   963  		// frame and wait for the server to close the connection.
   964  		s.wsMutex.Lock()
   965  		err := s.wsConn.WriteMessage(websocket.CloseMessage, websocket.FormatCloseMessage(closeCode, ""))
   966  		s.wsMutex.Unlock()
   967  		if err != nil {
   968  			s.log(LogInformational, "error closing websocket, %s", err)
   969  		}
   970  
   971  		// TODO: Wait for Discord to actually close the connection.
   972  		time.Sleep(1 * time.Second)
   973  
   974  		s.log(LogInformational, "closing gateway websocket")
   975  		err = s.wsConn.Close()
   976  		if err != nil {
   977  			s.log(LogInformational, "error closing websocket, %s", err)
   978  		}
   979  
   980  		s.wsConn = nil
   981  	}
   982  
   983  	s.Unlock()
   984  
   985  	s.log(LogInformational, "emit disconnect event")
   986  	s.handleEvent(disconnectEventType, &Disconnect{})
   987  
   988  	return
   989  }