Add image sending
This commit is contained in:
parent
f028054eeb
commit
f8da84d8c9
@ -56,5 +56,5 @@ type Attachment struct {
|
||||
// Payload is the information on where an attachment is.
|
||||
type Payload struct {
|
||||
// URL is where the attachment resides on the internet.
|
||||
URL string `json:"url"`
|
||||
URL string `json:"url,omitempty"`
|
||||
}
|
||||
|
50
response.go
50
response.go
@ -3,6 +3,11 @@ package messenger
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"image"
|
||||
"image/jpeg"
|
||||
"io"
|
||||
"mime/multipart"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
@ -47,6 +52,51 @@ func (r *Response) Text(message string) error {
|
||||
return err
|
||||
}
|
||||
|
||||
// Image sends an image.
|
||||
func (r *Response) Image(im image.Image) error {
|
||||
var b bytes.Buffer
|
||||
w := multipart.NewWriter(&b)
|
||||
|
||||
data, err := w.CreateFormFile("fielddata", "meme.jpg")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
imageBytes := new(bytes.Buffer)
|
||||
err = jpeg.Encode(imageBytes, im, nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
_, err = io.Copy(data, imageBytes)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
w.WriteField("recipient", fmt.Sprintf(`{"id":"%v"}`, r.to.ID))
|
||||
w.WriteField("message", `{"attachment":{"type":"image", "payload":{}}}`)
|
||||
|
||||
req, err := http.NewRequest("POST", SendMessageURL, &b)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
req.URL.RawQuery = "access_token=" + r.token
|
||||
|
||||
req.Header.Set("Content-Type", w.FormDataContentType())
|
||||
|
||||
client := &http.Client{}
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
var res bytes.Buffer
|
||||
res.ReadFrom(resp.Body)
|
||||
fmt.Println(res.String(), "DONE!")
|
||||
return nil
|
||||
}
|
||||
|
||||
// SendMessage is the information sent in an API request to Facebook.
|
||||
type SendMessage struct {
|
||||
Recipient Recipient `json:"recipient"`
|
||||
|
Loading…
Reference in New Issue
Block a user