1
0
mirror of synced 2024-11-25 14:26:09 +03:00

Add message sending

This commit is contained in:
Harrison Shoebridge 2016-04-13 17:01:42 +10:00
parent 5006304edf
commit 7fed4ecf28
3 changed files with 71 additions and 4 deletions

View File

@ -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")

View File

@ -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)
}
}
}

54
response.go Normal file
View File

@ -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"`
}