Repository navigation
Expand file tree
/
Copy pathcommand_handler.go
More file actions
74 lines (61 loc) · 1.83 KB
/
Copy pathcommand_handler.go
File metadata and controls
74 lines (61 loc) · 1.83 KB
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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
package commandworks
import (
"fmt"
"log"
cytonats "github.com/cytobot/messaging/nats"
pbs "github.com/cytobot/messaging/transport/shared"
"github.com/lampjaw/discordclient"
)
type command interface {
// GetCommandID returns the unique command identifier
getCommandID() string
// Process executes the command
process(client *discordclient.DiscordClient, req *pbs.DiscordWorkRequest) error
}
type CommandHandler struct {
commands []command
managerClient *managerClient
discordResolver *discordResolver
}
func NewCommandHandler(managerEndpoint string, natsClient *cytonats.NatsClient) *CommandHandler {
handler := &CommandHandler{
managerClient: getManagerClient(managerEndpoint),
discordResolver: newDiscordResolver(natsClient),
}
handler.commands = handler.getCommandTypes()
return handler
}
func (h *CommandHandler) ProcessCommand(client *discordclient.DiscordClient, req *pbs.DiscordWorkRequest) error {
cmd := h.findCommand(req.Command)
if cmd == nil {
return fmt.Errorf("[CommandHandler] Command with identifier '%s' was not found", req.Command)
}
err := cmd.process(client, req)
if err != nil {
return fmt.Errorf("[CommandHandler] Command '%s' failed: %v", req.Command, err)
}
return nil
}
func getManagerClient(managerEndpoint string) *managerClient {
client, err := newManagerClient(managerEndpoint)
if err != nil {
panic(fmt.Sprintf("[Manager client error] %s", err))
}
log.Println("Connected to manager client")
return client
}
func (h *CommandHandler) findCommand(commandID string) command {
for _, cmd := range h.commands {
if cmd.getCommandID() == commandID {
return cmd
}
}
return nil
}
func (h *CommandHandler) getCommandTypes() []command {
return []command{
newInviteCommandProcessor(),
newTwanswateCommandProcessor(h.discordResolver),
newStatsCommandProcessor(h.managerClient),
}
}