claptrap-go/discord/handlers.go
2024-07-08 18:09:43 +02:00

73 lines
2.5 KiB
Go

package discord
import (
"sebclem/claptrapbot-go/models"
"sebclem/claptrapbot-go/utils"
"github.com/bwmarrin/discordgo"
"gorm.io/gorm"
)
func guildCreateEvent(s *discordgo.Session, r *discordgo.GuildCreate) {
logger.Infow("New guild ready", "name", r.Name, "ID", r.ID)
}
func VoiceStateUpdateEvent(s *discordgo.Session, r *discordgo.VoiceStateUpdate, db *gorm.DB, status map[string]*GuildStatus) {
var guildPreference models.GuildPreference
result := db.Where(&models.GuildPreference{ID: r.GuildID}).FirstOrCreate(&guildPreference)
if result.Error != nil {
logger.Debugw("Can't retreve guild preference", result.Error)
return
}
if guildPreference.AutoVoiceEnabled {
thisStatus, ok := status[r.GuildID]
if !ok {
thisStatus = NewGuildStatus()
status[r.GuildID] = thisStatus
}
// Filter connect/disconned/move event
if r.BeforeUpdate == nil || r.BeforeUpdate.ChannelID != r.ChannelID {
// Connected or moved to new channel
if r.ChannelID != "" {
logger.Debugw("Someone joinded a channel", "GuildID", r.GuildID, "ChannelID", r.ChannelID)
if r.ChannelID == guildPreference.AutoVoiceSourceChannelId {
logger.Infow("Member join auto voice channel, creating new channel",
"user", r.Member.DisplayName(),
"channelID", r.ChannelID,
)
created, err := CreateAutoVoiceChannel(s, thisStatus, r.ChannelID, guildPreference.AutoVoiceCreatedChannelName)
if err == nil {
err = s.GuildMemberMove(created.GuildID, r.UserID, &created.ID)
if err != nil {
logger.Errorw("Fail to move user to created channel", err,
"GuildId", r.GuildID,
"SoucerChannelID", r.ChannelID,
"DestChannelID", created.ID)
}
channels, err := s.GuildChannels(r.GuildID)
if err != nil {
logger.Errorw("Fail retrevie channel list", err)
return
}
filtered := utils.Filter(channels, func(c *discordgo.Channel) bool { return c.ParentID == created.ParentID })
ReoderChannels(s, filtered, r.GuildID)
}
}
}
// Disconnected or moved to new channel
if r.BeforeUpdate != nil {
logger.Debugw("Someone leaved a channel", "GuildID", r.BeforeUpdate.GuildID, "ChannelID", r.BeforeUpdate.ChannelID)
_, ok := thisStatus.AutoVoiceStatus.CreatedChannel[r.BeforeUpdate.ChannelID]
if ok {
logger.Debugw("This is a auto created channel", "ChannelID", r.BeforeUpdate.ChannelID)
AutoVoiceChannelDisconect(s, thisStatus, r.BeforeUpdate.GuildID, r.BeforeUpdate.ChannelID)
}
}
}
}
}