-
Notifications
You must be signed in to change notification settings - Fork 14
/
commands.go
50 lines (42 loc) · 1.29 KB
/
commands.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
package irckit
import (
"errors"
"github.com/sorcix/irc"
)
// The error returned when an invalid command is issued.
var ErrUnknownCommand = errors.New("unknown command")
// Handler is a container for an irc.Message handler.
type Handler struct {
// Command is the IRC command that Call handles.
Command string
// Handler is a function that takes the server, user who sent the message, and a message to perform some command.
Call func(s Server, u *User, msg *irc.Message) error
// MinParams is the minimum number of params required on the message.
MinParams int
// TODO: Add mode constraints?
}
type Commands interface {
Add(Handler)
Run(Server, *User, *irc.Message) error
}
// Commands is a registry for command handlers
type commands map[string]Handler
// Add registers a Handler. Will replace any existing handlers for the given Command.
func (cmds commands) Add(h Handler) {
cmds[h.Command] = h
}
// Run executes an Handler to the irc.Message's Command.
func (cmds commands) Run(s Server, u *User, msg *irc.Message) error {
cmd, ok := cmds[msg.Command]
if !ok {
return ErrUnknownCommand
}
if len(msg.Params) < cmd.MinParams {
return u.Encode(&irc.Message{
Prefix: s.Prefix(),
Command: irc.ERR_NEEDMOREPARAMS,
Params: []string{msg.Command},
})
}
return cmd.Call(s, u, msg)
}