This repository has been archived by the owner on Apr 26, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3
/
bot.go
104 lines (93 loc) · 2.25 KB
/
bot.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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
/*
Package bot contains implementation of the Calories bot.
The bot's Message handlers and functions are described in this package.
*/
package bot
import (
"log"
"net/http"
"strings"
"github.com/bobheadxi/calories/facebook"
"github.com/bobheadxi/calories/server"
)
// Bot : The Calories bot of the app.
type Bot struct {
api facebook.APILayer
server server.ServerLayer
commands map[string]Handler
postbacks map[string]Handler
}
// Handler : A function that handles an event
type Handler func(*Context) error
// Context :
type Context struct {
facebookID string
timestamp int64
content string
}
// New : Sets up and returns a Bot
func New(api facebook.APILayer, sv server.ServerLayer) *Bot {
b := Bot{
api: api,
server: sv,
}
b.api.SetHandlers(b.MessageHandler, b.PostbackHandler)
// Add new command keywords here
commands := map[string]Handler{
"help": b.help,
"test": b.test,
"update": b.update,
}
b.commands = commands
// Add new postback events here
postbacks := map[string]Handler{
"INIT_NEW_USER": b.initUser,
"TEST_1": b.testOne,
"TEST_2": b.testTwo,
}
b.postbacks = postbacks
return &b
}
// Run : Spins up the Calories bot
func (b *Bot) Run(port string) {
log.Print("Spinning up the bot...")
http.HandleFunc("/webhook", b.api.Handler)
err := b.api.SetWelcomeScreen()
if err != nil {
log.Print(err)
}
go b.scheduler()
log.Fatal(http.ListenAndServe(":"+port, nil))
}
// MessageHandler : Handles messages
func (b *Bot) MessageHandler(event facebook.Event, sender facebook.Sender, msg facebook.ReceivedMessage) {
context := &Context{
facebookID: sender.ID,
timestamp: event.Time,
content: msg.Text,
}
// TODO : make command recognition smarter
handler, found := b.commands[strings.ToLower(context.content)]
if !found {
handler = b.help
}
err := handler(context)
if err != nil {
log.Print(err)
}
}
// PostbackHandler : Handles postbacks
func (b *Bot) PostbackHandler(event facebook.Event, sender facebook.Sender, postback facebook.Postback) {
context := &Context{
facebookID: sender.ID,
timestamp: event.Time,
content: postback.Payload,
}
handler, found := b.postbacks[postback.Payload]
if found {
err := handler(context)
if err != nil {
log.Print(err)
}
}
}