Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add messaging feedback receive event to facebookapp handler #82

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
110 changes: 110 additions & 0 deletions handlers/facebookapp/facebookapp.go
Original file line number Diff line number Diff line change
Expand Up @@ -156,10 +156,26 @@ type moPayload struct {
MIDs []string `json:"mids"`
Watermark int64 `json:"watermark"`
} `json:"delivery"`

MessagingFeedback *struct {
FeedbackScreens []struct {
ScreenID int `json:"screen_id"`
Questions map[string]FeedbackQuestion `json:"questions"`
} `json:"feedback_screens"`
} `json:"messaging_feedback"`
} `json:"messaging"`
} `json:"entry"`
}

type FeedbackQuestion struct {
Type string `json:"type"`
Payload string `json:"payload"`
FollowUp *struct {
Type string `json:"type"`
Payload string `json:"payload"`
} `json:"follow_up"`
}

// GetChannel returns the channel
func (h *handler) GetChannel(ctx context.Context, r *http.Request) (courier.Channel, error) {
if r.Method == http.MethodGet {
Expand Down Expand Up @@ -425,6 +441,26 @@ func (h *handler) receiveEvent(ctx context.Context, channel courier.Channel, w h
data = append(data, courier.NewStatusData(event))
}

} else if msg.MessagingFeedback != nil {

payloads := []string{}
for _, v := range msg.MessagingFeedback.FeedbackScreens[0].Questions {
payloads = append(payloads, v.Payload)
}
text := strings.Join(payloads[:], ", ")

ev := h.Backend().NewIncomingMsg(channel, urn, text).WithReceivedOn(date)
event := h.Backend().CheckExternalIDSeen(ev)

err := h.Backend().WriteMsg(ctx, event)
if err != nil {
return nil, err
}

h.Backend().WriteExternalIDSeen(event)
events = append(events, event)
data = append(data, courier.NewMsgReceiveData(event))

} else {
data = append(data, courier.NewInfoData("ignoring unknown entry type"))
}
Expand Down Expand Up @@ -511,6 +547,80 @@ func (h *handler) SendMsg(ctx context.Context, msg courier.Msg) (courier.MsgStat

status := h.Backend().NewMsgStatusForID(msg.Channel(), msg.ID(), courier.MsgErrored)

isCustomerFeedbackTemplateMsg := strings.Contains(msg.Text(), "{customer_feedback_template}")

if isCustomerFeedbackTemplateMsg {
if msg.Text() != "" {
text := strings.ReplaceAll(strings.ReplaceAll(msg.Text(), "\n", ""), "\t", "")

splited := strings.Split(text, "|")
templateMap := make(map[string]string)
for i := 1; i < len(splited); i++ {
field := strings.Split(splited[i], ":")
templateMap[strings.TrimSpace(field[0])] = strings.TrimSpace(field[1])
}

payloadMap := map[string]interface{}{
"recipient": map[string]string{
"id": msg.URN().Path(),
},
"message": map[string]interface{}{
"attachment": map[string]interface{}{
"type": "template",
"payload": map[string]interface{}{
"template_type": "customer_feedback",
"title": templateMap["title"],
"subtitle": templateMap["subtitle"],
"button_title": templateMap["button_title"],
"feedback_screens": []map[string]interface{}{
{
"questions": []map[string]interface{}{
{
"id": templateMap["question_id"],
"type": templateMap["type"],
"title": templateMap["question_title"],
"score_label": templateMap["score_label"],
"score_option": templateMap["score_option"],
},
},
},
},
"business_privacy": map[string]string{
"url": templateMap["business_privacy"],
},
},
},
},
}

jsonBody, err := json.Marshal(payloadMap)
if err != nil {
return status, err
}

msgURL, _ := url.Parse("https://graph.facebook.com/v12.0/me/messages")
query := url.Values{}
query.Set("access_token", accessToken)
msgURL.RawQuery = query.Encode()

req, err := http.NewRequest(http.MethodPost, msgURL.String(), bytes.NewReader(jsonBody))
if err != nil {
return nil, err
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Accept", "application/json")
rr, err := utils.MakeHTTPRequest(req)

log := courier.NewChannelLogFromRR("Message Sent", msg.Channel(), msg.ID(), rr).WithError("Message Send Error", err)
status.AddLog(log)
if err != nil {
return status, nil
}
status.SetStatus(courier.MsgWired)
}
return status, nil
}

msgParts := make([]string, 0)
if msg.Text() != "" {
msgParts = handlers.SplitMsgByChannel(msg.Channel(), msg.Text(), maxMsgLength)
Expand Down
39 changes: 39 additions & 0 deletions handlers/facebookapp/facebookapp_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -415,6 +415,41 @@ var unkownMessagingEntry = `{
}]
}`

var customerFeedbackResponse = `{
"object": "page",
"entry": [
{
"id": "1234",
"time": 1459991487970,
"messaging": [
{
"recipient": {
"id": "1234"
},
"timestamp": 1459991487970,
"sender": {
"id": "5678"
},
"messaging_feedback": {
"feedback_screens": [
{
"screen_id": 0,
"questions": {
"test_question": {
"type": "CSAT",
"payload": "4"
}
}
}
]
}
}
]
}
]
}
`

var notJSON = `blargh`

var testCases = []ChannelHandleTestCase{
Expand Down Expand Up @@ -477,6 +512,10 @@ var testCases = []ChannelHandleTestCase{
{Label: "Unknown Messaging Entry", URL: "/c/fba/receive", Data: unkownMessagingEntry, Status: 200, Response: "Handled", PrepRequest: addValidSignature},
{Label: "Not JSON", URL: "/c/fba/receive", Data: notJSON, Status: 400, Response: "Error", PrepRequest: addValidSignature},
{Label: "Invalid URN", URL: "/c/fba/receive", Data: invalidURN, Status: 400, Response: "invalid facebook id", PrepRequest: addValidSignature},

{Label: "Receive Customer Feedback Message", URL: "/c/fba/receive", Data: customerFeedbackResponse, Status: 200, Response: "Handled", NoQueueErrorCheck: true, NoInvalidChannelCheck: true,
Text: Sp("4"), URN: Sp("facebook:5678"), Date: Tp(time.Date(2016, 4, 7, 1, 11, 27, 970000000, time.UTC)),
PrepRequest: addValidSignature},
}

func addValidSignature(r *http.Request) {
Expand Down