Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add prune command #33

Merged
merged 4 commits into from
Nov 16, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 4 additions & 4 deletions .github/workflows/lint.yml
Original file line number Diff line number Diff line change
Expand Up @@ -14,12 +14,12 @@ jobs:
- uses: actions/checkout@v4
- uses: actions/setup-go@v5
with:
go-version: "1.22"
go-version: "1.23"
cache: false
- name: GolangCi-Lint
uses: golangci/golangci-lint-action@v6.1.1
with:
version: v1.59.1
version: v1.62.0
args: --timeout=5m
test:
name: Test
Expand All @@ -31,7 +31,7 @@ jobs:
- name: Set up Go
uses: actions/setup-go@v5
with:
go-version: "1.22"
go-version: "1.23"

- name: Test
run: go test -v ./...
Expand All @@ -45,7 +45,7 @@ jobs:
- name: Set up Go
uses: actions/setup-go@v5
with:
go-version: "1.22"
go-version: "1.23"

- name: Build
run: go build -v ./...
258 changes: 258 additions & 0 deletions commands/prune.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,258 @@
package commands

import (
"fmt"
"log/slog"
"time"

"github.com/disgoorg/disgo/discord"
"github.com/disgoorg/disgo/handler"
"github.com/disgoorg/disgo/rest"
"github.com/disgoorg/json"

"github.com/myrkvi/heimdallr/globals"
"github.com/myrkvi/heimdallr/model"
"github.com/myrkvi/heimdallr/utils"
)

var PruneDryRunCommand = discord.SlashCommandCreate{
Name: "prune-pending-members-dry-run",
NameLocalizations: map[discord.Locale]string{
discord.LocaleNorwegian: "fjern-ventende-medlemmer-dry-run",
},
Description: "Prune members.",
DescriptionLocalizations: map[discord.Locale]string{
discord.LocaleNorwegian: "Fjern medlemmer.",
},

Contexts: []discord.InteractionContextType{
discord.InteractionContextTypeGuild,
},
IntegrationTypes: []discord.ApplicationIntegrationType{
discord.ApplicationIntegrationTypeGuildInstall,
},

DefaultMemberPermissions: json.NewNullablePtr(discord.PermissionManageGuild),

Options: []discord.ApplicationCommandOption{
discord.ApplicationCommandOptionInt{
Name: "days",
NameLocalizations: map[discord.Locale]string{
discord.LocaleNorwegian: "dager",
},
Description: "The number of days to prune members for.",
DescriptionLocalizations: map[discord.Locale]string{
discord.LocaleNorwegian: "Antall dager å fjerne medlemmer for.",
},
Required: true,

MinValue: utils.Ref(0),
MaxValue: utils.Ref(90),
},
},
}

func PruneDryRunHandler(e *handler.CommandEvent) error {
if e.GuildID() == nil {
return ErrEventNoGuildID
}
days := e.SlashCommandInteractionData().Int("days")

guildSettings, err := model.GetGuildSettings(*e.GuildID())
if err != nil {
_ = e.CreateMessage(discord.NewMessageCreateBuilder().
SetEphemeral(true).
SetContent("Failed to prune members: could not get guild settings.").
Build())
return err
}

if guildSettings.GatekeepPendingRole == 0 {
return e.CreateMessage(discord.NewMessageCreateBuilder().
SetEphemeral(true).
SetContent("Failed to prune members: no pending role set. This command will only prune pending members.").
Build())
}

_ = e.DeferCreateMessage(true)

prunableMembers, err := getPrunableMembers(e, days, guildSettings)
if err != nil {
_, err = e.CreateFollowupMessage(discord.NewMessageCreateBuilder().
SetEphemeral(true).
SetContent("Failed to prune members: could not get member list.").
Build())
return err
}

numKicked := len(prunableMembers)

adminMessage := fmt.Sprintf("Dry run: pruned %d members.\n\nMembers:\n", numKicked)

for _, member := range prunableMembers {
if member == nil {
continue
}

adminMessage += fmt.Sprintf("-# %s (%s)\n", member.User.Username, member.User.ID)
}

_, err = e.CreateFollowupMessage(discord.NewMessageCreateBuilder().
SetEphemeral(true).
SetContent(adminMessage).
Build())
return err
}

var PruneCommand = discord.SlashCommandCreate{
Name: "prune-pending-members",
NameLocalizations: map[discord.Locale]string{
discord.LocaleNorwegian: "fjern-ventende-medlemmer",
},
Description: "Prune members.",
DescriptionLocalizations: map[discord.Locale]string{
discord.LocaleNorwegian: "Fjern medlemmer.",
},

Contexts: []discord.InteractionContextType{
discord.InteractionContextTypeGuild,
},
IntegrationTypes: []discord.ApplicationIntegrationType{
discord.ApplicationIntegrationTypeGuildInstall,
},

DefaultMemberPermissions: json.NewNullablePtr(discord.PermissionManageGuild),

Options: []discord.ApplicationCommandOption{
discord.ApplicationCommandOptionInt{
Name: "days",
NameLocalizations: map[discord.Locale]string{
discord.LocaleNorwegian: "dager",
},
Description: "The number of days to prune members for.",
DescriptionLocalizations: map[discord.Locale]string{
discord.LocaleNorwegian: "Antall dager å fjerne medlemmer for.",
},
Required: true,

MinValue: utils.Ref(3),
MaxValue: utils.Ref(90),
},
},
}

func PruneHandler(e *handler.CommandEvent) error {
if e.GuildID() == nil {
return ErrEventNoGuildID
}
days := e.SlashCommandInteractionData().Int("days")

guildSettings, err := model.GetGuildSettings(*e.GuildID())
if err != nil {
_ = e.CreateMessage(discord.NewMessageCreateBuilder().
SetEphemeral(true).
SetContent("Failed to prune members: could not get guild settings.").
Build())
return err
}

if guildSettings.GatekeepPendingRole == 0 {
return e.CreateMessage(discord.NewMessageCreateBuilder().
SetEphemeral(true).
SetContent("Failed to prune members: no pending role set. This command will only prune pending members.").
Build())
}

_ = e.DeferCreateMessage(true)

var kickedMembers []*discord.Member

prunableMembers, err := getPrunableMembers(e, days, guildSettings)
if err != nil {
_, err = e.CreateFollowupMessage(discord.NewMessageCreateBuilder().
SetEphemeral(true).
SetContent("Failed to prune members: could not get member list.").
Build())
return err
}

for _, member := range prunableMembers {

globals.ExcludedFromModKickLog[member.User.ID] = struct{}{}
kickedMembers = append(kickedMembers, member)

err = e.Client().Rest().RemoveMember(*e.GuildID(), member.User.ID,
rest.WithReason(
fmt.Sprintf("User pruned with command. Pruned by: %s (%s)",
e.User().Username, e.User().ID)))
if err != nil {
slog.Error("Failed to prune member.", "err", err, "user_id", member.User.ID)
_, err = e.CreateFollowupMessage(discord.NewMessageCreateBuilder().
SetEphemeral(true).
SetContent("Failed to prune members: failed to remove member.").
Build())
return err
}
}

numKicked := len(kickedMembers)

adminMessage := fmt.Sprintf("Pruned %d members.\n\nMembers:\n", numKicked)

for _, member := range kickedMembers {
if member == nil {
continue
}

adminMessage += fmt.Sprintf("-# %s (%s)\n", member.User.Username, member.User.ID)
}

if numKicked > 0 && guildSettings.ModeratorChannel != 0 {
_, err = e.Client().Rest().CreateMessage(guildSettings.ModeratorChannel, discord.NewMessageCreateBuilder().
SetContent(adminMessage).
SetEphemeral(true).
Build())
if err != nil {
slog.Error("Failed to send prune message to moderator channel.",
"err", err,
"guild_id", *e.GuildID(),
"channel_id", guildSettings.ModeratorChannel,
"user_id", e.User().ID)
}
}

_ = days

_, err = e.CreateFollowupMessage(discord.NewMessageCreateBuilder().
SetEphemeral(true).
SetContentf("Pruned %d users.", numKicked).
Build())
return err
}

func getPrunableMembers(e *handler.CommandEvent, days int, guildSettings *model.GuildSettings) (members []*discord.Member, err error) {
maxTimeDiff := time.Duration(days) * time.Hour * 24

for member := range utils.GetMembersIter(e.Client().Rest(), *e.GuildID()) {
if member.Error != nil {
return nil, member.Error
}
member := member.Value

if !utils.HasRole(member, guildSettings.GatekeepPendingRole) {
continue
}

if utils.HasRole(member, guildSettings.GatekeepApprovedRole) {
continue
}

if time.Since(member.JoinedAt) < maxTimeDiff {
continue
}

members = append(members, &member)
}

return
}
5 changes: 5 additions & 0 deletions globals/globals.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
package globals

import "github.com/disgoorg/snowflake/v2"

var ExcludedFromModKickLog = make(map[snowflake.ID]struct{})
2 changes: 1 addition & 1 deletion go.mod
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
module github.com/myrkvi/heimdallr

go 1.22.0
go 1.23.0

require (
github.com/cbroglie/mustache v1.4.0
Expand Down
9 changes: 9 additions & 0 deletions listeners/audit_log.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ import (

"github.com/disgoorg/disgo/discord"
"github.com/disgoorg/disgo/events"

"github.com/myrkvi/heimdallr/globals"
"github.com/myrkvi/heimdallr/model"
"github.com/myrkvi/heimdallr/utils"
)
Expand All @@ -26,6 +28,13 @@ func OnAuditLog(e *events.GuildAuditLogEntryCreate) {
return
}

if _, ok := globals.ExcludedFromModKickLog[targetUser.ID]; ok {
// User is excluded from mod kick log, likely because they were pruned.
// Remove from excluded list and don't log.
delete(globals.ExcludedFromModKickLog, targetUser.ID)
return
}

msg = fmt.Sprintf("User %s (`%d`) was kicked by %s.%s", targetUser.Username, targetUser.ID,
user.Mention(),
utils.Iif(entry.Reason != nil, fmt.Sprintf("\n\n>>> %s", *entry.Reason), ""))
Expand Down
5 changes: 5 additions & 0 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -115,6 +115,9 @@ func main() {
r.Command("/create-role-button", commands.CreateRoleButtonHandler)
r.Component("/role/assign/{roleID}", components.RoleAssignButtonHandler)

r.Command("/prune-pending-members", commands.PruneHandler)
r.Command("/prune-pending-members-dry-run", commands.PruneDryRunHandler)

commandCreates := []discord.ApplicationCommandCreate{
commands.PingCommand,
commands.QuoteCommand,
Expand All @@ -127,6 +130,8 @@ func main() {
commands.ApproveSlashCommand,
commands.ApproveUserCommand,
commands.CreateRoleButtonCommand,
commands.PruneCommand,
commands.PruneDryRunCommand,
}

client, err := disgo.New(token,
Expand Down
50 changes: 50 additions & 0 deletions utils/users.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
package utils

import (
"github.com/disgoorg/disgo/discord"
"github.com/disgoorg/snowflake/v2"
)

func HasRole(member discord.Member, roleID snowflake.ID) bool {
for _, role := range member.RoleIDs {
if role == roleID {
return true
}
}

return false
}

func HasRolesAll(member discord.Member, roleIDs ...snowflake.ID) bool {
hasRole := make(map[snowflake.ID]bool)
for _, role := range member.RoleIDs {
hasRole[role] = false
}
for _, role := range member.RoleIDs {
for _, roleID := range roleIDs {
if role == roleID {
hasRole[role] = true
}
}
}

for _, hasRole := range hasRole {
if !hasRole {
return false
}
}

return true
}

func HasRolesAny(member discord.Member, roleIDs ...snowflake.ID) bool {
for _, role := range member.RoleIDs {
for _, roleID := range roleIDs {
if role == roleID {
return true
}
}
}

return false
}
Loading