2014-12-21 05:21:41 +01:00
|
|
|
package chat
|
|
|
|
|
|
|
|
import (
|
|
|
|
"errors"
|
|
|
|
"strings"
|
|
|
|
)
|
|
|
|
|
2014-12-26 01:25:02 +01:00
|
|
|
var ErrInvalidCommand = errors.New("invalid command")
|
|
|
|
var ErrNoOwner = errors.New("command without owner")
|
2014-12-21 05:21:41 +01:00
|
|
|
|
2014-12-26 21:11:03 +01:00
|
|
|
type CommandHandler func(*Channel, CommandMsg) error
|
2014-12-21 05:21:41 +01:00
|
|
|
|
2014-12-26 01:25:02 +01:00
|
|
|
type Commands map[string]CommandHandler
|
2014-12-21 05:21:41 +01:00
|
|
|
|
|
|
|
// Register command
|
2014-12-26 01:25:02 +01:00
|
|
|
func (c Commands) Add(command string, handler CommandHandler) {
|
|
|
|
c[command] = handler
|
2014-12-21 05:21:41 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
// Execute command message, assumes IsCommand was checked
|
2014-12-26 21:11:03 +01:00
|
|
|
func (c Commands) Run(channel *Channel, msg CommandMsg) error {
|
2014-12-21 05:21:41 +01:00
|
|
|
if msg.from == nil {
|
|
|
|
return ErrNoOwner
|
|
|
|
}
|
|
|
|
|
2014-12-26 01:25:02 +01:00
|
|
|
handler, ok := c[msg.Command()]
|
2014-12-21 05:21:41 +01:00
|
|
|
if !ok {
|
|
|
|
return ErrInvalidCommand
|
|
|
|
}
|
|
|
|
|
2014-12-26 21:11:03 +01:00
|
|
|
return handler(channel, msg)
|
2014-12-21 05:21:41 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
var defaultCmdHandlers Commands
|
|
|
|
|
|
|
|
func init() {
|
|
|
|
c := Commands{}
|
|
|
|
|
2014-12-26 21:11:03 +01:00
|
|
|
c.Add("/me", func(channel *Channel, msg CommandMsg) error {
|
2014-12-26 01:25:02 +01:00
|
|
|
me := strings.TrimLeft(msg.body, "/me")
|
2014-12-21 05:21:41 +01:00
|
|
|
if me == "" {
|
|
|
|
me = " is at a loss for words."
|
2014-12-26 21:26:53 +01:00
|
|
|
} else {
|
|
|
|
me = me[1:]
|
2014-12-21 05:21:41 +01:00
|
|
|
}
|
|
|
|
|
2014-12-26 21:11:03 +01:00
|
|
|
channel.Send(NewEmoteMsg(me, msg.From()))
|
2014-12-21 05:21:41 +01:00
|
|
|
return nil
|
|
|
|
})
|
|
|
|
|
|
|
|
defaultCmdHandlers = c
|
|
|
|
}
|