2022-09-05 21:55:07 +00:00
|
|
|
package bot
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
|
|
|
|
|
|
|
"git.kill0.net/chill9/beepboop/lib"
|
|
|
|
"github.com/bwmarrin/discordgo"
|
|
|
|
log "github.com/sirupsen/logrus"
|
|
|
|
)
|
|
|
|
|
|
|
|
var (
|
|
|
|
DefaultCommander *Commander
|
|
|
|
)
|
|
|
|
|
|
|
|
type (
|
|
|
|
Commander struct {
|
|
|
|
commands map[string]*Command
|
|
|
|
}
|
|
|
|
|
|
|
|
Command struct {
|
2022-09-07 02:33:59 +00:00
|
|
|
Name string
|
|
|
|
Config Config
|
|
|
|
Func CommandFunc
|
|
|
|
NArgs int
|
2022-09-05 21:55:07 +00:00
|
|
|
}
|
2022-09-07 02:33:59 +00:00
|
|
|
|
|
|
|
CommandFunc func(args []string, m *discordgo.MessageCreate) error
|
2022-09-05 21:55:07 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
func init() {
|
|
|
|
DefaultCommander = NewCommander()
|
|
|
|
}
|
|
|
|
|
|
|
|
func NewCommander() *Commander {
|
|
|
|
cmdr := new(Commander)
|
|
|
|
cmdr.commands = make(map[string]*Command)
|
|
|
|
return cmdr
|
|
|
|
}
|
|
|
|
|
|
|
|
func (cmdr *Commander) AddCommand(cmd *Command) {
|
|
|
|
cmdr.commands[cmd.Name] = cmd
|
|
|
|
}
|
|
|
|
|
|
|
|
func (cmdr *Commander) GetCommand(name string) (*Command, bool) {
|
|
|
|
cmd, ok := cmdr.commands[name]
|
|
|
|
return cmd, ok
|
|
|
|
}
|
|
|
|
|
|
|
|
func AddCommand(cmd *Command) {
|
|
|
|
DefaultCommander.AddCommand(cmd)
|
|
|
|
}
|
|
|
|
|
|
|
|
func GetCommand(name string) (*Command, bool) {
|
|
|
|
cmd, ok := DefaultCommander.GetCommand(name)
|
|
|
|
return cmd, ok
|
|
|
|
}
|
|
|
|
|
2022-09-07 02:33:59 +00:00
|
|
|
func NewCommandHandler(bot *Bot) func(s *discordgo.Session, m *discordgo.MessageCreate) {
|
2022-09-05 21:55:07 +00:00
|
|
|
return func(s *discordgo.Session, m *discordgo.MessageCreate) {
|
|
|
|
var cmd *Command
|
|
|
|
|
|
|
|
if m.Author.ID == s.State.User.ID {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2022-09-07 02:33:59 +00:00
|
|
|
if !lib.HasCommand(m.Content, bot.Config.Prefix) {
|
2022-09-05 21:55:07 +00:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2022-09-07 02:33:59 +00:00
|
|
|
cmdName, arg := lib.SplitCommandAndArg(m.Content, bot.Config.Prefix)
|
2022-09-05 21:55:07 +00:00
|
|
|
|
|
|
|
cmd, ok := GetCommand(cmdName)
|
2022-09-06 15:43:30 +00:00
|
|
|
|
|
|
|
args := lib.SplitArgs(arg, cmd.NArgs)
|
|
|
|
|
2022-09-05 21:55:07 +00:00
|
|
|
if ok {
|
2022-09-07 02:33:59 +00:00
|
|
|
cmd.Config = bot.Config
|
2022-09-05 21:55:07 +00:00
|
|
|
|
2022-09-06 15:43:30 +00:00
|
|
|
log.Debugf("command: %v, args: %v, nargs: %d", cmd.Name, args, len(args))
|
2022-09-07 02:33:59 +00:00
|
|
|
cmd.Func(args, m)
|
2022-09-05 21:55:07 +00:00
|
|
|
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2022-09-06 15:43:30 +00:00
|
|
|
log.Warnf("unknown command: %v, args: %v, nargs: %d", cmdName, args, len(args))
|
2022-09-05 21:55:07 +00:00
|
|
|
s.ChannelMessageSend(m.ChannelID, fmt.Sprintf("unknown command: %s", cmdName))
|
|
|
|
}
|
|
|
|
}
|