diff --git a/receiving.go b/receiving.go index 3b1ed1c..9d16119 100644 --- a/receiving.go +++ b/receiving.go @@ -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"` } diff --git a/response.go b/response.go index ecf4eb1..8c6340a 100644 --- a/response.go +++ b/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"`