diff --git a/session/session.go b/session/session.go index b52bd63..18bc0f6 100644 --- a/session/session.go +++ b/session/session.go @@ -365,6 +365,18 @@ func (s *Session) AddInteractionHandlerFunc(f webhook.InteractionHandlerFunc) { s.AddInteractionHandler(f) } +// SendGateway is a helper to send messages over the gateway. It will check +// if the gateway is open and available, then send the message. +func (s *Session) SendGateway(ctx context.Context, m ws.Event) error { + // The only necessary check here is checking if gateway is nil, however + // this will save us a bit of work in serialization. + if !s.GatewayIsAlive() { + return ErrClosed + } + + return s.Gateway().Send(ctx, m) +} + // Close closes the underlying Websocket connection, invalidating the session // ID. It will send a closing frame before ending the connection, closing it // gracefully. This will cause the bot to appear as offline instantly. To diff --git a/voice/session.go b/voice/session.go index d68b45b..e9e961a 100644 --- a/voice/session.go +++ b/voice/session.go @@ -52,12 +52,12 @@ func (e ReconnectError) Unwrap() error { return e.Err } type MainSession interface { // AddHandler describes the method in handler.Handler. AddHandler(handler interface{}) (rm func()) - // Gateway returns the session's main Discord gateway. - Gateway() *gateway.Gateway // Me returns the current user. Me() (*discord.User, error) // Channel queries for the channel with the given ID. Channel(discord.ChannelID) (*discord.Channel, error) + // SendGateway is a helper to send messages over the gateway. + SendGateway(ctx context.Context, m ws.Event) error } var ( @@ -327,7 +327,7 @@ func (s *Session) askDiscord( // https://discord.com/developers/docs/topics/voice-connections#retrieving-voice-server-information // Send a Voice State Update event to the gateway. - if err := s.session.Gateway().Send(ctx, data); err != nil { + if err := s.session.SendGateway(ctx, data); err != nil { return errors.Wrap(err, "failed to send Voice State Update event") } @@ -531,7 +531,7 @@ func (s *Session) Leave(ctx context.Context) error { } // Notify Discord that we're leaving. - sendErr := s.session.Gateway().Send(ctx, &gateway.UpdateVoiceStateCommand{ + sendErr := s.session.SendGateway(ctx, &gateway.UpdateVoiceStateCommand{ GuildID: s.state.GuildID, ChannelID: discord.ChannelID(discord.NullSnowflake), SelfMute: true,