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

Add image sending

This commit is contained in:
Harrison Shoebridge 2016-04-16 18:01:32 +10:00
parent f028054eeb
commit f8da84d8c9
2 changed files with 51 additions and 1 deletions

View File

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

View File

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