From a6d7b88762d621aa0dd4b2f1e721cc4158e33cd2 Mon Sep 17 00:00:00 2001 From: Nicholas McCurry Date: Thu, 5 Nov 2020 16:43:55 -0700 Subject: [PATCH] Add previous state to VoiceStateUpdate event (#823) --- events.go | 2 ++ state.go | 27 +++++++++++++++++++++++++++ 2 files changed, 29 insertions(+) diff --git a/events.go b/events.go index 99099c9..dd0e3d8 100644 --- a/events.go +++ b/events.go @@ -252,6 +252,8 @@ type VoiceServerUpdate struct { // VoiceStateUpdate is the data for a VoiceStateUpdate event. type VoiceStateUpdate struct { *VoiceState + // BeforeUpdate will be nil if the VoiceState was not previously cached in the state cache. + BeforeUpdate *VoiceState `json:"-"` } // MessageDeleteBulk is the data for a MessageDeleteBulk event diff --git a/state.go b/state.go index f2d461a..c89f8bb 100644 --- a/state.go +++ b/state.go @@ -732,6 +732,26 @@ func (s *State) voiceStateUpdate(update *VoiceStateUpdate) error { return nil } +// VoiceState gets a VoiceState by guild and user ID. +func (s *State) VoiceState(guildID, userID string) (*VoiceState, error) { + if s == nil { + return nil, ErrNilState + } + + guild, err := s.Guild(guildID) + if err != nil { + return nil, err + } + + for _, state := range guild.VoiceStates { + if state.UserID == userID { + return state, nil + } + } + + return nil, ErrStateNotFound +} + // Message gets a message by channel and message ID. func (s *State) Message(channelID, messageID string) (*Message, error) { if s == nil { @@ -921,6 +941,13 @@ func (s *State) OnInterface(se *Session, i interface{}) (err error) { } case *VoiceStateUpdate: if s.TrackVoice { + var old *VoiceState + old, err = s.VoiceState(t.GuildID, t.UserID) + if err == nil { + oldCopy := *old + t.BeforeUpdate = &oldCopy + } + err = s.voiceStateUpdate(t) } case *PresenceUpdate: