canopeas/discord/clear.go

70 lines
1.4 KiB
Go

package discord
import (
"errors"
"strconv"
"strings"
)
const clearMax = 20
func init() {
commands["clear"] = command{
validate: func(cmd commandInit) bool {
return isStaff(cmd.message.Member.Roles, cmd.config.StaffRoles)
},
run: func(cmd commandInit) 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 errors.New("this command takes needs two arguments with a mention")
}
} else if len(args) < 1 {
return errors.New("this command takes one argument without a mention")
}
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",
}
}