forked from shomali11/slacker
/
main.go
85 lines (74 loc) · 2.08 KB
/
main.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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
package main
import (
"context"
"fmt"
"log"
"os"
"github.com/shomali11/slacker/v2"
)
func main() {
bot := slacker.NewClient(os.Getenv("SLACK_BOT_TOKEN"), os.Getenv("SLACK_APP_TOKEN"))
bot.AddCommand(&slacker.CommandDefinition{
Command: "ping",
Handler: func(ctx *slacker.CommandContext) {
ctx.Response().Reply("pong")
},
})
bot.AddCommandMiddleware(LoggingCommandMiddleware())
bot.AddCommandMiddleware(func(next slacker.CommandHandler) slacker.CommandHandler {
return func(ctx *slacker.CommandContext) {
ctx.Response().Reply("Root Middleware!")
next(ctx)
}
})
group := bot.AddCommandGroup("cool")
group.AddMiddleware(func(next slacker.CommandHandler) slacker.CommandHandler {
return func(ctx *slacker.CommandContext) {
ctx.Response().Reply("Group Middleware!")
next(ctx)
}
})
commandMiddleware := func(next slacker.CommandHandler) slacker.CommandHandler {
return func(ctx *slacker.CommandContext) {
ctx.Response().Reply("Command Middleware!")
next(ctx)
}
}
group.AddCommand(&slacker.CommandDefinition{
Command: "weather",
Description: "Find me a cool weather",
Examples: []string{"cool weather"},
Middlewares: []slacker.CommandMiddlewareHandler{commandMiddleware},
Handler: func(ctx *slacker.CommandContext) {
ctx.Response().Reply("San Francisco")
},
})
group.AddCommand(&slacker.CommandDefinition{
Command: "person",
Description: "Find me a cool person",
Examples: []string{"cool person"},
Handler: func(ctx *slacker.CommandContext) {
ctx.Response().Reply("Dwayne Johnson")
},
})
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
err := bot.Listen(ctx)
if err != nil {
log.Fatal(err)
}
}
func LoggingCommandMiddleware() slacker.CommandMiddlewareHandler {
return func(next slacker.CommandHandler) slacker.CommandHandler {
return func(ctx *slacker.CommandContext) {
fmt.Printf(
"%s executed \"%s\" with parameters %v in channel %s\n",
ctx.Event().UserID,
ctx.Definition().Command,
ctx.Request().Properties(),
ctx.Event().Channel.ID,
)
next(ctx)
}
}
}