diff --git a/cmd/bot/main.go b/cmd/bot/main.go index 4535ed0..fec281d 100644 --- a/cmd/bot/main.go +++ b/cmd/bot/main.go @@ -13,6 +13,7 @@ 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") + pageToken = conf.String("page-token", "not skrilla", "The token that is used to verify the page on facebook") ) func main() { @@ -25,10 +26,12 @@ func main() { m := messenger.New(messenger.MessengerOptions{ Verify: *verify, VerifyToken: *verifyToken, + Token: *pageToken, }) - m.Handle(messenger.TextAction, func(m messenger.Message) { + m.Handle(messenger.TextAction, func(m messenger.Message, r *messenger.Response) { fmt.Printf("%v (Sent, %v)\n", m.Text, m.Time.Format(time.UnixDate)) + fmt.Println(r.Text("Hello, World!")) }) fmt.Println("Serving messenger bot on localhost:8080") diff --git a/messenger.go b/messenger.go index 88ca5ae..1cd4e47 100644 --- a/messenger.go +++ b/messenger.go @@ -14,19 +14,22 @@ const ( type MessengerOptions struct { Verify bool VerifyToken string + Token string } -type MessageHandler func(Message) +type MessageHandler func(Message, *Response) type Messenger struct { mux *http.ServeMux handlers map[Action]MessageHandler + token string } func New(mo MessengerOptions) *Messenger { m := &Messenger{ mux: http.NewServeMux(), handlers: make(map[Action]MessageHandler), + token: mo.Token, } if mo.Verify { @@ -76,12 +79,19 @@ func (m *Messenger) dispatch(r Receive) { } if f := m.handlers[a]; f != nil { - f(Message{ + message := Message{ Sender: info.Sender.ID, Recipient: info.Recipient.ID, Time: time.Unix(info.Timestamp, 0), Text: info.Message.Text, - }) + } + + response := &Response{ + to: Recipient{info.Sender.ID}, + token: m.token, + } + + f(message, response) } } } diff --git a/response.go b/response.go new file mode 100644 index 0000000..247d5df --- /dev/null +++ b/response.go @@ -0,0 +1,54 @@ +package messenger + +import ( + "bytes" + "encoding/json" + "net/http" +) + +const ( + SendMessageURL = "https://graph.facebook.com/v2.6/me/messages" +) + +type Response struct { + token string + to Recipient +} + +func (r *Response) Text(message string) error { + m := SendMessage{ + Recipient: r.to, + Message: MessageData{ + Text: message, + }, + } + + data, err := json.Marshal(m) + if err != nil { + return nil + } + + req, err := http.NewRequest("POST", SendMessageURL, bytes.NewBuffer(data)) + if err != nil { + return err + } + + req.Header.Set("Content-Type", "application/json") + req.URL.RawQuery = "access_token=" + r.token + + client := &http.Client{} + + resp, err := client.Do(req) + defer resp.Body.Close() + + return err +} + +type SendMessage struct { + Recipient Recipient `json:"recipient"` + Message MessageData `json:"message"` +} + +type MessageData struct { + Text string `json:"text,omitempty"` +}