From 8f272bbf3047db398ebb3afdfc5869677b09d7bb Mon Sep 17 00:00:00 2001 From: Harrison Shoebridge Date: Wed, 13 Apr 2016 12:03:26 +1000 Subject: [PATCH] Add Messenger bot capable of verification The only ability of this current bot is to verify the webhook on the Facebook developer panel. --- cmd/bot/main.go | 31 +++++++++++++++++++++++++++++++ messenger.go | 46 ++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 77 insertions(+) create mode 100644 cmd/bot/main.go create mode 100644 messenger.go diff --git a/cmd/bot/main.go b/cmd/bot/main.go new file mode 100644 index 0000000..4a17639 --- /dev/null +++ b/cmd/bot/main.go @@ -0,0 +1,31 @@ +package main + +import ( + "fmt" + "net/http" + + "github.com/paked/configure" + "github.com/paked/messenger" +) + +var ( + conf = configure.New() + verifyToken = conf.String("verify-token", "mad-skrilla", "The token used to verify facebook") + verify = conf.Bool("should-verify", false, "Whether or not the app should verify itself") +) + +func main() { + conf.Use(configure.NewFlag()) + conf.Use(configure.NewEnvironment()) + conf.Use(configure.NewJSONFromFile("config.json")) + + conf.Parse() + + m := messenger.New(messenger.MessengerOptions{ + Verify: *verify, + VerifyToken: *verifyToken, + }) + + fmt.Println("Serving messenger bot on localhost:8080") + http.ListenAndServe("localhost:8080", m.Handler()) +} diff --git a/messenger.go b/messenger.go new file mode 100644 index 0000000..0bca0ea --- /dev/null +++ b/messenger.go @@ -0,0 +1,46 @@ +package messenger + +import ( + "fmt" + "net/http" +) + +const ( + WebhookURL = "/webhook" +) + +type MessengerOptions struct { + Verify bool + VerifyToken string +} + +type Messenger struct { + mux *http.ServeMux +} + +func New(mo MessengerOptions) *Messenger { + m := &Messenger{ + mux: http.NewServeMux(), + } + + if mo.Verify { + m.mux.HandleFunc(WebhookURL, newVerifyHandler(mo.VerifyToken)) + } + + return m +} + +func (m *Messenger) Handler() http.Handler { + return m.mux +} + +func newVerifyHandler(token string) func(w http.ResponseWriter, r *http.Request) { + return func(w http.ResponseWriter, r *http.Request) { + if r.FormValue("hub.verify_token") == token { + fmt.Fprintln(w, r.FormValue("hub.challenge")) + return + } + + fmt.Fprintln(w, "Incorrect verify token.") + } +}