Skip to content

Commit

Permalink
Send configured welcome message on converssation started for Viber
Browse files Browse the repository at this point in the history
  • Loading branch information
norkans7 committed Mar 7, 2019
1 parent c6e4c0a commit 348c62c
Show file tree
Hide file tree
Showing 3 changed files with 76 additions and 7 deletions.
1 change: 1 addition & 0 deletions channel_event.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ const (
NewConversation ChannelEventType = "new_conversation"
Referral ChannelEventType = "referral"
StopContact ChannelEventType = "stop_contact"
WelcomeMessage ChannelEventType = "welcome_message"
)

//-----------------------------------------------------------------------------
Expand Down
62 changes: 56 additions & 6 deletions handlers/viber/viber.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,11 +22,12 @@ import (
)

var (
viberSignatureHeader = "X-Viber-Content-Signature"
sendURL = "https://chatapi.viber.com/pa/send_message"
maxMsgLength = 7000
quickReplyTextSize = 36
descriptionMaxLength = 120
viberSignatureHeader = "X-Viber-Content-Signature"
sendURL = "https://chatapi.viber.com/pa/send_message"
maxMsgLength = 7000
quickReplyTextSize = 36
descriptionMaxLength = 120
configViberWelcomeMessage = "viber_welcome_message"
)

func init() {
Expand Down Expand Up @@ -77,6 +78,14 @@ type eventPayload struct {
} `json:"message"`
}

type welcomeMessagePayload struct {
AuthToken string `json:"auth_token"`
Text string `json:"text"`
Type string `json:"type"`
TrackingData string `json:"tracking_data"`
Sender map[string]string `json:"sender,omitempty"`
}

// receiveEvent is our HTTP handler function for incoming messages
func (h *handler) receiveEvent(ctx context.Context, channel courier.Channel, w http.ResponseWriter, r *http.Request) ([]courier.Event, error) {
err := h.validateSignature(channel, r)
Expand All @@ -96,7 +105,42 @@ func (h *handler) receiveEvent(ctx context.Context, channel courier.Channel, w h
return nil, handlers.WriteAndLogRequestIgnored(ctx, h, channel, w, r, "webhook valid")

case "conversation_started":
return nil, handlers.WriteAndLogRequestIgnored(ctx, h, channel, w, r, "ignored conversation start")

msgText := channel.StringConfigForKey(configViberWelcomeMessage, "")
if msgText == "" {
return nil, handlers.WriteAndLogRequestIgnored(ctx, h, channel, w, r, "ignored conversation start")
}

authToken := channel.StringConfigForKey(courier.ConfigAuthToken, "")

viberID := payload.User.ID
ContactName := payload.User.Name

// build the URN
urn, err := urns.NewURNFromParts(urns.ViberScheme, viberID, "", "")
if err != nil {
return nil, handlers.WriteAndLogRequestIgnored(ctx, h, channel, w, r, "ignored conversation start")
}
// build the channel event
channelEvent := h.Backend().NewChannelEvent(channel, courier.WelcomeMessage, urn).WithContactName(ContactName)

err = h.Backend().WriteChannelEvent(ctx, channelEvent)
if err != nil {
return nil, err
}
payload := welcomeMessagePayload{
AuthToken: authToken,
Text: msgText,
Type: "text",
TrackingData: string(channelEvent.EventID()),
}

responseBody := &bytes.Buffer{}
err = json.NewEncoder(responseBody).Encode(payload)
if err != nil {
return nil, handlers.WriteAndLogRequestIgnored(ctx, h, channel, w, r, "ignored conversation start")
}
return []courier.Event{channelEvent}, writeViberWelcomeMessageResponse(w, responseBody.String())

case "subscribed":
viberID := payload.User.ID
Expand Down Expand Up @@ -205,6 +249,12 @@ func (h *handler) receiveEvent(ctx context.Context, channel courier.Channel, w h
return nil, courier.WriteError(ctx, w, r, fmt.Errorf("not handled, unknown event: %s", event))
}

func writeViberWelcomeMessageResponse(w http.ResponseWriter, messageText string) error {
w.WriteHeader(200)
_, err := fmt.Fprint(w, messageText)
return err
}

// see https://developers.viber.com/docs/api/rest-bot-api/#callbacks
func (h *handler) validateSignature(channel courier.Channel, r *http.Request) error {
actual := r.Header.Get(viberSignatureHeader)
Expand Down
20 changes: 19 additions & 1 deletion handlers/viber/viber_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -180,7 +180,16 @@ func TestSending(t *testing.T) {
}

var testChannels = []courier.Channel{
courier.NewMockChannel("8eb23e93-5ecb-45ba-b726-3b064e0c56ab", "VP", "2020", "", map[string]interface{}{"auth_token": "Token"}),
courier.NewMockChannel("8eb23e93-5ecb-45ba-b726-3b064e0c56ab", "VP", "2020", "", map[string]interface{}{
courier.ConfigAuthToken: "Token",
}),
}

var testChannelsWithWelcomeMessage = []courier.Channel{
courier.NewMockChannel("8eb23e93-5ecb-45ba-b726-3b064e0c56ab", "VP", "2020", "", map[string]interface{}{
courier.ConfigAuthToken: "Token",
configViberWelcomeMessage: "Welcome to VP, Please subscribe here for more.",
}),
}

var (
Expand Down Expand Up @@ -454,6 +463,13 @@ var testCases = []ChannelHandleTestCase{
Attachment: Sp("geo:1.200000,-1.300000"), PrepRequest: addValidSignature},
}

var testWelcomeMessageCases = []ChannelHandleTestCase{
{Label: "Receive Valid", URL: receiveURL, Data: validMsg, Status: 200, Response: "Accepted",
Text: Sp("incoming msg"), URN: Sp("viber:xy5/5y6O81+/kbWHpLhBoA=="), ExternalID: Sp("4987381189870374000"),
PrepRequest: addValidSignature},
{Label: "Conversation Started", URL: receiveURL, Data: validConversationStarted, Status: 200, Response: `{"auth_token":"Token","text":"Welcome to VP, Please subscribe here for more.","type":"text","tracking_data":"\u0000"}`, PrepRequest: addValidSignature},
}

func addValidSignature(r *http.Request) {
body, _ := ioutil.ReadAll(r.Body)
r.Body = ioutil.NopCloser(bytes.NewBuffer(body))
Expand All @@ -478,8 +494,10 @@ func addInvalidSignature(r *http.Request) {

func TestHandler(t *testing.T) {
RunChannelTestCases(t, testChannels, newHandler(), testCases)
RunChannelTestCases(t, testChannelsWithWelcomeMessage, newHandler(), testWelcomeMessageCases)
}

func BenchmarkHandler(b *testing.B) {
RunChannelBenchmarks(b, testChannels, newHandler(), testCases)
RunChannelBenchmarks(b, testChannelsWithWelcomeMessage, newHandler(), testWelcomeMessageCases)
}

0 comments on commit 348c62c

Please sign in to comment.