session: Introduce SendGateway (#356)

* Support SendGateway to help with voice usage

* Remove unnecessary Gateway interface function

* Add clarification comment

Co-authored-by: Tyler <admin@meow.tf>
This commit is contained in:
Tyler Stuyfzand 2022-11-25 14:16:13 -05:00 committed by GitHub
parent 91c86f02ec
commit 769215970e
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 16 additions and 4 deletions

View File

@ -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

View File

@ -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,