From 8042da15a9f84de400779ce6f5cc4e44fdb3bef0 Mon Sep 17 00:00:00 2001 From: ION606 Date: Mon, 7 Apr 2025 12:31:43 -0400 Subject: [PATCH] added perm check --- Bot/Commands/reactionrole.go | 57 ++++++++++++++++++++++++++++++++---- 1 file changed, 52 insertions(+), 5 deletions(-) diff --git a/Bot/Commands/reactionrole.go b/Bot/Commands/reactionrole.go index 683156c..bf93210 100644 --- a/Bot/Commands/reactionrole.go +++ b/Bot/Commands/reactionrole.go @@ -258,8 +258,59 @@ func HandleReactionRoleModalSubmit(s *discordgo.Session, i *discordgo.Interactio } } +// botHasManageRoles checks if the bot has the Manage Roles permission in the guild. +func botHasManageRoles(s *discordgo.Session, guildID string) (bool, error) { + botMember, err := s.GuildMember(guildID, s.State.User.ID) + if err != nil { + return false, err + } + + roles, err := s.GuildRoles(guildID) + if err != nil { + return false, err + } + + // Combine permissions from all roles the bot has. + var perms int64 = 0 + for _, botRoleID := range botMember.Roles { + for _, role := range roles { + if role.ID == botRoleID { + perms |= int64(role.Permissions) + } + } + } + + // discordgo.PermissionManageRoles is 0x10000000 (268435456) + if perms&discordgo.PermissionManageRoles != 0 { + return true, nil + } + return false, nil +} + // HandleReactionRoleButton processes button clicks for reaction roles. func HandleReactionRoleButton(s *discordgo.Session, i *discordgo.InteractionCreate) { + // Check if the bot has Manage Roles permission. + if i.GuildID == "" { + helpers.HandleError(s, i, fmt.Errorf("cannot assign roles in DMs")) + return + } + hasPerm, err := botHasManageRoles(s, i.GuildID) + if err != nil { + helpers.HandleError(s, i, fmt.Errorf("failed to check bot permissions: %w", err)) + return + } + + if !hasPerm { + s.InteractionRespond(i.Interaction, &discordgo.InteractionResponse{ + Type: discordgo.InteractionResponseChannelMessageWithSource, + Data: &discordgo.InteractionResponseData{ + Content: "*Bot does not have the Manage Roles permission!*", + Flags: discordgo.MessageFlagsEphemeral, + }, + }) + return + } + customID := i.MessageComponentData().CustomID // Expect customID in the format "rr:" roleID := strings.TrimPrefix(customID, "rr:") @@ -268,10 +319,6 @@ func HandleReactionRoleButton(s *discordgo.Session, i *discordgo.InteractionCrea return } - if i.GuildID == "" { - helpers.HandleError(s, i, fmt.Errorf("cannot assign roles in DMs")) - return - } member := i.Member if member == nil { helpers.HandleError(s, i, fmt.Errorf("member not found")) @@ -285,7 +332,7 @@ func HandleReactionRoleButton(s *discordgo.Session, i *discordgo.InteractionCrea } // Respond to acknowledge the action. - err := s.InteractionRespond(i.Interaction, &discordgo.InteractionResponse{ + err = s.InteractionRespond(i.Interaction, &discordgo.InteractionResponse{ Type: discordgo.InteractionResponseChannelMessageWithSource, Data: &discordgo.InteractionResponseData{ Content: "Role successfully assigned!",