2016-04-13 10:01:42 +03:00
|
|
|
package messenger
|
|
|
|
|
|
|
|
import (
|
|
|
|
"bytes"
|
|
|
|
"encoding/json"
|
|
|
|
"net/http"
|
|
|
|
)
|
|
|
|
|
|
|
|
const (
|
2016-04-14 03:23:45 +03:00
|
|
|
// SendMessageURL is API endpoint for sending messages.
|
2016-04-13 10:01:42 +03:00
|
|
|
SendMessageURL = "https://graph.facebook.com/v2.6/me/messages"
|
|
|
|
)
|
|
|
|
|
2016-04-14 03:23:45 +03:00
|
|
|
// Response is used for responding to events with messages.
|
2016-04-13 10:01:42 +03:00
|
|
|
type Response struct {
|
|
|
|
token string
|
|
|
|
to Recipient
|
|
|
|
}
|
|
|
|
|
2016-04-14 03:23:45 +03:00
|
|
|
// Text sends a textual message.
|
2016-04-13 10:01:42 +03:00
|
|
|
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
|
|
|
|
}
|
|
|
|
|
2016-04-14 03:23:45 +03:00
|
|
|
// SendMessage is the information sent in an API request to Facebook.
|
2016-04-13 10:01:42 +03:00
|
|
|
type SendMessage struct {
|
|
|
|
Recipient Recipient `json:"recipient"`
|
|
|
|
Message MessageData `json:"message"`
|
|
|
|
}
|
|
|
|
|
2016-04-14 03:23:45 +03:00
|
|
|
// MessageData is a text message to be sent.
|
2016-04-13 10:01:42 +03:00
|
|
|
type MessageData struct {
|
|
|
|
Text string `json:"text,omitempty"`
|
|
|
|
}
|