logmania/bot/command.go

47 lines
911 B
Go
Raw Normal View History

package bot
import (
"fmt"
)
2018-09-11 22:57:09 +02:00
type commandFunc func(from string, params []string) string
2018-09-11 22:57:09 +02:00
type Command struct {
Name string
Description string
Commands []*Command
Action commandFunc
}
2018-09-11 22:57:09 +02:00
func (c Command) Run(from string, args []string) string {
if len(args) > 0 {
cmdName := args[0]
if cmdName == "help" {
return c.Help()
}
2018-09-11 22:57:09 +02:00
if len(c.Commands) > 0 {
for _, cmd := range c.Commands {
if cmd.Name == cmdName {
return cmd.Run(from, args[1:])
}
}
2018-09-11 22:57:09 +02:00
return fmt.Sprintf("command %s not found\n%s", cmdName, c.Help())
}
}
2018-09-11 22:57:09 +02:00
if c.Action != nil {
return c.Action(from, args)
2018-05-18 11:28:01 +02:00
}
2018-09-11 22:57:09 +02:00
return c.Help()
2018-05-18 11:28:01 +02:00
}
2018-09-11 22:57:09 +02:00
func (c Command) Help() string {
if len(c.Commands) > 0 {
msg := fmt.Sprintf("%s\n-------------------", c.Description)
for _, cmd := range c.Commands {
msg = fmt.Sprintf("%s\n%s: %s", msg, cmd.Name, cmd.Description)
2018-05-18 11:28:01 +02:00
}
2018-09-11 22:57:09 +02:00
return msg
2018-05-18 11:28:01 +02:00
}
2018-09-11 22:57:09 +02:00
return c.Description
}