This repository has been archived by the owner on Jan 1, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 72
/
response.go
484 lines (418 loc) · 14.6 KB
/
response.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
package messenger
import (
"bytes"
"encoding/json"
"fmt"
"image"
"image/jpeg"
"io"
"io/ioutil"
"mime/multipart"
"net/http"
"net/textproto"
"strings"
"golang.org/x/xerrors"
)
// AttachmentType is attachment type.
type AttachmentType string
type MessagingType string
type TopElementStyle string
type ImageAspectRatio string
const (
// SendMessageURL is API endpoint for sending messages.
SendMessageURL = "https://graph.facebook.com/v2.11/me/messages"
// ThreadControlURL is the API endpoint for passing thread control.
ThreadControlURL = "https://graph.facebook.com/v2.6/me/pass_thread_control"
// InboxPageID is managed by facebook for secondary pass to inbox features: https://developers.facebook.com/docs/messenger-platform/handover-protocol/pass-thread-control
InboxPageID = 263902037430900
// ImageAttachment is image attachment type.
ImageAttachment AttachmentType = "image"
// AudioAttachment is audio attachment type.
AudioAttachment AttachmentType = "audio"
// VideoAttachment is video attachment type.
VideoAttachment AttachmentType = "video"
// FileAttachment is file attachment type.
FileAttachment AttachmentType = "file"
// ResponseType is response messaging type
ResponseType MessagingType = "RESPONSE"
// UpdateType is update messaging type
UpdateType MessagingType = "UPDATE"
// MessageTagType is message_tag messaging type
MessageTagType MessagingType = "MESSAGE_TAG"
// NonPromotionalSubscriptionType is NON_PROMOTIONAL_SUBSCRIPTION messaging type
NonPromotionalSubscriptionType MessagingType = "NON_PROMOTIONAL_SUBSCRIPTION"
// TopElementStyle is compact.
CompactTopElementStyle TopElementStyle = "compact"
// TopElementStyle is large.
LargeTopElementStyle TopElementStyle = "large"
// ImageAspectRatio is horizontal (1.91:1). Default.
HorizontalImageAspectRatio ImageAspectRatio = "horizontal"
// ImageAspectRatio is square.
SquareImageAspectRatio ImageAspectRatio = "square"
)
// QueryResponse is the response sent back by Facebook when setting up things
// like greetings or call-to-actions
type QueryResponse struct {
Error *QueryError `json:"error,omitempty"`
Result string `json:"result,omitempty"`
}
// QueryError is representing an error sent back by Facebook
type QueryError struct {
Message string `json:"message"`
Type string `json:"type"`
Code int `json:"code"`
ErrorSubcode int `json:"error_subcode"`
FBTraceID string `json:"fbtrace_id"`
}
// QueryError implements error
func (e QueryError) Error() string {
return e.Message
}
func checkFacebookError(r io.Reader) error {
var err error
qr := QueryResponse{}
err = json.NewDecoder(r).Decode(&qr)
if err != nil {
return xerrors.Errorf("json unmarshal error: %w", err)
}
if qr.Error != nil {
return xerrors.Errorf("facebook error: %w", qr.Error)
}
return nil
}
// Response is used for responding to events with messages.
type Response struct {
token string
to Recipient
}
// SetToken is for using DispatchMessage from outside.
func (r *Response) SetToken(token string) {
r.token = token
}
// Text sends a textual message.
func (r *Response) Text(message string, messagingType MessagingType, tags ...string) error {
return r.TextWithReplies(message, nil, messagingType, tags...)
}
// TextWithReplies sends a textual message with some replies
// messagingType should be one of the following: "RESPONSE","UPDATE","MESSAGE_TAG","NON_PROMOTIONAL_SUBSCRIPTION"
// only supply tags when messagingType == "MESSAGE_TAG" (see https://developers.facebook.com/docs/messenger-platform/send-messages#messaging_types for more)
func (r *Response) TextWithReplies(message string, replies []QuickReply, messagingType MessagingType, tags ...string) error {
var tag string
if len(tags) > 0 {
tag = tags[0]
}
m := SendMessage{
MessagingType: messagingType,
Recipient: r.to,
Message: MessageData{
Text: message,
Attachment: nil,
QuickReplies: replies,
},
Tag: tag,
}
return r.DispatchMessage(&m)
}
// AttachmentWithReplies sends a attachment message with some replies
func (r *Response) AttachmentWithReplies(attachment *StructuredMessageAttachment, replies []QuickReply, messagingType MessagingType, tags ...string) error {
var tag string
if len(tags) > 0 {
tag = tags[0]
}
m := SendMessage{
MessagingType: messagingType,
Recipient: r.to,
Message: MessageData{
Attachment: attachment,
QuickReplies: replies,
},
Tag: tag,
}
return r.DispatchMessage(&m)
}
// Image sends an image.
func (r *Response) Image(im image.Image) error {
imageBytes := new(bytes.Buffer)
err := jpeg.Encode(imageBytes, im, nil)
if err != nil {
return err
}
return r.AttachmentData(ImageAttachment, "meme.jpg", imageBytes)
}
// Attachment sends an image, sound, video or a regular file to a chat.
func (r *Response) Attachment(dataType AttachmentType, url string, messagingType MessagingType, tags ...string) error {
var tag string
if len(tags) > 0 {
tag = tags[0]
}
m := SendStructuredMessage{
MessagingType: messagingType,
Recipient: r.to,
Message: StructuredMessageData{
Attachment: StructuredMessageAttachment{
Type: dataType,
Payload: StructuredMessagePayload{
Url: url,
},
},
},
Tag: tag,
}
return r.DispatchMessage(&m)
}
// copied from multipart package
var quoteEscaper = strings.NewReplacer("\\", "\\\\", `"`, "\\\"")
// copied from multipart package
func escapeQuotes(s string) string {
return quoteEscaper.Replace(s)
}
// copied from multipart package with slight changes due to fixed content-type there
func createFormFile(filename string, w *multipart.Writer, contentType string) (io.Writer, error) {
h := make(textproto.MIMEHeader)
h.Set("Content-Disposition",
fmt.Sprintf(`form-data; name="filedata"; filename="%s"`,
escapeQuotes(filename)))
h.Set("Content-Type", contentType)
return w.CreatePart(h)
}
// AttachmentData sends an image, sound, video or a regular file to a chat via an io.Reader.
func (r *Response) AttachmentData(dataType AttachmentType, filename string, filedata io.Reader) error {
filedataBytes, err := ioutil.ReadAll(filedata)
if err != nil {
return err
}
contentType := http.DetectContentType(filedataBytes[:512])
fmt.Println("Content-type detected:", contentType)
var body bytes.Buffer
multipartWriter := multipart.NewWriter(&body)
data, err := createFormFile(filename, multipartWriter, contentType)
if err != nil {
return err
}
_, err = bytes.NewBuffer(filedataBytes).WriteTo(data)
if err != nil {
return err
}
multipartWriter.WriteField("recipient", fmt.Sprintf(`{"id":"%v"}`, r.to.ID))
multipartWriter.WriteField("message", fmt.Sprintf(`{"attachment":{"type":"%v", "payload":{}}}`, dataType))
req, err := http.NewRequest("POST", SendMessageURL, &body)
if err != nil {
return err
}
req.URL.RawQuery = "access_token=" + r.token
req.Header.Set("Content-Type", multipartWriter.FormDataContentType())
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
return checkFacebookError(resp.Body)
}
// ButtonTemplate sends a message with the main contents being button elements
func (r *Response) ButtonTemplate(text string, buttons *[]StructuredMessageButton, messagingType MessagingType, tags ...string) error {
var tag string
if len(tags) > 0 {
tag = tags[0]
}
m := SendStructuredMessage{
MessagingType: messagingType,
Recipient: r.to,
Message: StructuredMessageData{
Attachment: StructuredMessageAttachment{
Type: "template",
Payload: StructuredMessagePayload{
TemplateType: "button",
Text: text,
Buttons: buttons,
Elements: nil,
},
},
},
Tag: tag,
}
return r.DispatchMessage(&m)
}
// GenericTemplate is a message which allows for structural elements to be sent
func (r *Response) GenericTemplate(elements *[]StructuredMessageElement, messagingType MessagingType, tags ...string) error {
var tag string
if len(tags) > 0 {
tag = tags[0]
}
m := SendStructuredMessage{
MessagingType: messagingType,
Recipient: r.to,
Message: StructuredMessageData{
Attachment: StructuredMessageAttachment{
Type: "template",
Payload: StructuredMessagePayload{
TemplateType: "generic",
Buttons: nil,
Elements: elements,
},
},
},
Tag: tag,
}
return r.DispatchMessage(&m)
}
// ListTemplate sends a list of elements
func (r *Response) ListTemplate(elements *[]StructuredMessageElement, messagingType MessagingType, tags ...string) error {
var tag string
if len(tags) > 0 {
tag = tags[0]
}
m := SendStructuredMessage{
MessagingType: messagingType,
Recipient: r.to,
Message: StructuredMessageData{
Attachment: StructuredMessageAttachment{
Type: "template",
Payload: StructuredMessagePayload{
TopElementStyle: "compact",
TemplateType: "list",
Buttons: nil,
Elements: elements,
},
},
},
Tag: tag,
}
return r.DispatchMessage(&m)
}
// SenderAction sends a info about sender action
func (r *Response) SenderAction(action string) error {
m := SendSenderAction{
Recipient: r.to,
SenderAction: action,
}
return r.DispatchMessage(&m)
}
// DispatchMessage posts the message to messenger, return the error if there's any
func (r *Response) DispatchMessage(m interface{}) error {
data, err := json.Marshal(m)
if err != nil {
return err
}
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
resp, err := http.DefaultClient.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode == 200 {
return nil
}
return checkFacebookError(resp.Body)
}
// PassThreadToInbox Uses Messenger Handover Protocol for live inbox
// https://developers.facebook.com/docs/messenger-platform/handover-protocol/#inbox
func (r *Response) PassThreadToInbox() error {
p := passThreadControl{
Recipient: r.to,
TargetAppID: InboxPageID,
Metadata: "Passing to inbox secondary app",
}
data, err := json.Marshal(p)
if err != nil {
return err
}
req, err := http.NewRequest("POST", ThreadControlURL, bytes.NewBuffer(data))
if err != nil {
return err
}
req.Header.Set("Content-Type", "application/json")
req.URL.RawQuery = "access_token=" + r.token
resp, err := http.DefaultClient.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
return checkFacebookError(resp.Body)
}
// SendMessage is the information sent in an API request to Facebook.
type SendMessage struct {
MessagingType MessagingType `json:"messaging_type"`
Recipient Recipient `json:"recipient"`
Message MessageData `json:"message"`
Tag string `json:"tag,omitempty"`
}
// MessageData is a message consisting of text or an attachment, with an additional selection of optional quick replies.
type MessageData struct {
Text string `json:"text,omitempty"`
Attachment *StructuredMessageAttachment `json:"attachment,omitempty"`
QuickReplies []QuickReply `json:"quick_replies,omitempty"`
}
// SendStructuredMessage is a structured message template.
type SendStructuredMessage struct {
MessagingType MessagingType `json:"messaging_type"`
Recipient Recipient `json:"recipient"`
Message StructuredMessageData `json:"message"`
Tag string `json:"tag,omitempty"`
}
// StructuredMessageData is an attachment sent with a structured message.
type StructuredMessageData struct {
Attachment StructuredMessageAttachment `json:"attachment"`
}
// StructuredMessageAttachment is the attachment of a structured message.
type StructuredMessageAttachment struct {
// Type must be template
Title string `json:"title,omitempty"`
URL string `json:"url,omitempty"`
Type AttachmentType `json:"type"`
// Payload is the information for the file which was sent in the attachment.
Payload StructuredMessagePayload `json:"payload"`
}
// StructuredMessagePayload is the actual payload of an attachment
type StructuredMessagePayload struct {
// TemplateType must be button, generic or receipt
TemplateType string `json:"template_type,omitempty"`
TopElementStyle TopElementStyle `json:"top_element_style,omitempty"`
Text string `json:"text,omitempty"`
ImageAspectRatio ImageAspectRatio `json:"image_aspect_ratio,omitempty"`
Sharable bool `json:"sharable,omitempty"`
Elements *[]StructuredMessageElement `json:"elements,omitempty"`
Buttons *[]StructuredMessageButton `json:"buttons,omitempty"`
Url string `json:"url,omitempty"`
AttachmentID string `json:"attachment_id,omitempty"`
}
// StructuredMessageElement is a response containing structural elements
type StructuredMessageElement struct {
Title string `json:"title"`
ImageURL string `json:"image_url"`
ItemURL string `json:"item_url,omitempty"`
Subtitle string `json:"subtitle"`
DefaultAction *DefaultAction `json:"default_action,omitempty"`
Buttons []StructuredMessageButton `json:"buttons"`
}
// DefaultAction is a response containing default action properties
type DefaultAction struct {
Type string `json:"type"`
URL string `json:"url,omitempty"`
WebviewHeightRatio string `json:"webview_height_ratio,omitempty"`
MessengerExtensions bool `json:"messenger_extensions,omitempty"`
FallbackURL string `json:"fallback_url,omitempty"`
WebviewShareButton string `json:"webview_share_button,omitempty"`
}
// StructuredMessageButton is a response containing buttons
type StructuredMessageButton struct {
Type string `json:"type"`
URL string `json:"url,omitempty"`
Title string `json:"title,omitempty"`
Payload string `json:"payload,omitempty"`
WebviewHeightRatio string `json:"webview_height_ratio,omitempty"`
MessengerExtensions bool `json:"messenger_extensions,omitempty"`
FallbackURL string `json:"fallback_url,omitempty"`
WebviewShareButton string `json:"webview_share_button,omitempty"`
ShareContents *StructuredMessageData `json:"share_contents,omitempty"`
}
// SendSenderAction is the information about sender action
type SendSenderAction struct {
Recipient Recipient `json:"recipient"`
SenderAction string `json:"sender_action"`
}