canopeas/discord/clear.go

71 lines
1.4 KiB
Go
Raw Permalink Normal View History

package discord
import (
"strconv"
"strings"
)
const clearMax = 20
func init() {
commands = append(commands, &command{
name: "clear",
staffOnly: true,
validate: func(cmd commandInit) bool {
return isStaff(cmd.message.Member.Roles, cmd.config.StaffRoles)
},
run: func(cmd commandInit) (string, error) {
args := strings.Fields(cmd.message.Content)
var userID string
if len(cmd.message.Mentions) > 0 {
userID = cmd.message.Mentions[0].ID
}
limitArg := 1
if userID != "" {
limitArg = 2
if len(args) < 2 {
return "This command takes two arguments with a mention", nil
}
} else if len(args) < 1 {
return "This command takes one argument without a mention", nil
}
limit, err := strconv.Atoi(args[limitArg])
if err != nil {
return "", err
}
if limit < 0 {
limit = 0
} else if limit > clearMax {
limit = 20
}
batch := []string{cmd.message.ID}
var deleted int
messages, err := cmd.session.ChannelMessages(cmd.message.ChannelID, 100, cmd.message.ID, "", "")
for _, msg := range messages {
if deleted == limit {
break
}
deleteMessage := true
if userID != "" {
deleteMessage = msg.Author.ID == userID
}
if deleteMessage {
batch = append(batch, msg.ID)
deleted++
}
}
return "", cmd.session.ChannelMessagesBulkDelete(cmd.message.ChannelID, batch)
},
help: "Clear messages",
})
}