Skip to content

Commit

Permalink
Merge pull request #66 from Cloudkibo/anisha_work
Browse files Browse the repository at this point in the history
getting started
  • Loading branch information
ImranBinShoukat authored Jan 15, 2019
2 parents 05f067c + 5abab48 commit 49507b0
Show file tree
Hide file tree
Showing 2 changed files with 213 additions and 1 deletion.
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
const TAG = 'webhook_subscriptions/messenger/getStartedWebhook.js'
const logger = require('../../../components/logger')
const callApi = require('../../../utility/api.caller.service')
const logicLayer = require('./logiclayer')
const request = require('request')

exports.getStartedWebhook = (payload) => {
if (payload.entry[0].messaging[0].postback.referral) {
Expand All @@ -27,6 +29,53 @@ exports.getStartedWebhook = (payload) => {
} else if (payload.entry[0].messaging[0].postback.payload === '<GET_STARTED_PAYLOAD>') {
logger.serverLog(TAG,
`in getStartedWebhook ${JSON.stringify(payload)}`)
callApi.callApi('messengerEvents/subscriber', 'post', payload, 'accounts')
sendWelcomeMessage(payload)
}
}

function sendWelcomeMessage (payload) {
const sender = payload.entry[0].messaging[0].sender.id
const pageId = payload.entry[0].messaging[0].recipient.id
callApi.callApi(`pages/query`, 'post', { pageId: pageId, connected: true }, 'accounts')
.then(page => {
page = page[0]
console.log('page Found', page)
callApi.callApi(`subscribers/query`, 'post', { pageId: page._id, senderId: sender }, 'accounts')
.then(subscriber => {
subscriber = subscriber[0]
console.log('page._id', page._id)
if (page.welcomeMessage) {
for (let i = 0; i < page.welcomeMessage.length; i++) {
let messageData = logicLayer.prepareSendAPIPayload(subscriber.senderId, page.welcomeMessage[i], subscriber.firstName, subscriber.lastName, true)
console.log('messageData', messageData)
request(
{
'method': 'POST',
'json': true,
'formData': messageData,
'uri': 'https://graph.facebook.com/v2.6/me/messages?access_token=' +
subscriber.pageId.accessToken
},
(err, res) => {
if (err) {
console.log(`At send message welcomeMessage ${JSON.stringify(err)}`)
} else {
console.log('res', res.body)
if (res.statusCode !== 200) {
logger.serverLog(TAG,
`At send message landingPage ${JSON.stringify(
res.body.error)}`)
}
}
})
}
}
})
.catch(err => {
logger.serverLog(TAG, `Failed to fetch subscriber ${JSON.stringify(err)}`)
})
})
.catch(err => {
logger.serverLog(TAG, `Failed to fetch page ${JSON.stringify(err)}`)
})
}
163 changes: 163 additions & 0 deletions server/webhook_subscriptions/messenger/getStarted/logiclayer.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,163 @@
const fs = require('fs')
const path = require('path')

function prepareSendAPIPayload (subscriberId, body, fname, lname, isResponse) {
let messageType = isResponse ? 'RESPONSE' : 'UPDATE'
let payload = {}
let text = body.text
if (body.componentType === 'text' && !body.buttons) {
if (body.text.includes('{{user_full_name}}') || body.text.includes('[Username]')) {
text = text.replace(
'{{user_full_name}}', fname + ' ' + lname)
}
if (body.text.includes('{{user_first_name}}')) {
text = text.replace(
'{{user_first_name}}', fname)
}
if (body.text.includes('{{user_last_name}}')) {
text = text.replace(
'{{user_last_name}}', lname)
}
payload = {
'messaging_type': messageType,
'recipient': JSON.stringify({
'id': subscriberId
}),
'message': JSON.stringify({
'text': text,
'metadata': 'This is a meta data'
})
}
return payload
} else if (body.componentType === 'text' && body.buttons) {
if (body.text.includes('{{user_full_name}}') || body.text.includes('[Username]')) {
text = text.replace(
'{{user_full_name}}', fname + ' ' + lname)
}
if (body.text.includes('{{user_first_name}}')) {
text = text.replace(
'{{user_first_name}}', fname)
}
if (body.text.includes('{{user_last_name}}')) {
text = text.replace(
'{{user_last_name}}', lname)
}
payload = {
'messaging_type': messageType,
'recipient': JSON.stringify({
'id': subscriberId
}),
'message': JSON.stringify({
'attachment': {
'type': 'template',
'payload': {
'template_type': 'button',
'text': text,
'buttons': body.buttons
}
}
})
}
} else if (['image', 'audio', 'file', 'video'].indexOf(
body.componentType) > -1) {
let dir = path.resolve(__dirname, '../../../../broadcastFiles/userfiles')
let fileReaderStream
if (body.componentType === 'file') {
fileReaderStream = fs.createReadStream(dir + '/' + body.fileurl.name)
} else {
fileReaderStream = fs.createReadStream(dir + '/' + body.fileurl.id)
}

payload = {
'messaging_type': messageType,
'recipient': JSON.stringify({
'id': subscriberId
}),
'message': JSON.stringify({
'attachment': {
'type': body.componentType,
'payload': {}
}
}),
'filedata': fileReaderStream
}
return payload
// todo test this one. we are not removing as we need to keep it for live chat
// if (!isForLiveChat) deleteFile(body.fileurl)
} else if (['gif', 'sticker', 'thumbsUp'].indexOf(
body.componentType) > -1) {
payload = {
'messaging_type': messageType,
'recipient': JSON.stringify({
'id': subscriberId
}),
'message': JSON.stringify({
'attachment': {
'type': 'image',
'payload': {
'url': body.fileurl
}
}
})
}
} else if (body.componentType === 'card') {
payload = {
'messaging_type': messageType,
'recipient': JSON.stringify({
'id': subscriberId
}),
'message': JSON.stringify({
'attachment': {
'type': 'template',
'payload': {
'template_type': 'generic',
'elements': [
{
'title': body.title,
'image_url': body.image_url,
'subtitle': body.description,
'buttons': body.buttons
}
]
}
}
})
}
} else if (body.componentType === 'gallery') {
payload = {
'messaging_type': messageType,
'recipient': JSON.stringify({
'id': subscriberId
}),
'message': JSON.stringify({
'attachment': {
'type': 'template',
'payload': {
'template_type': 'generic',
'elements': body.cards
}
}
})
}
} else if (body.componentType === 'list') {
payload = {
'messaging_type': messageType,
'recipient': JSON.stringify({
'id': subscriberId
}),
'message': JSON.stringify({
'attachment': {
'type': 'template',
'payload': {
'template_type': 'list',
'top_element_style': body.topElementStyle,
'elements': body.listItems,
'buttons': body.buttons
}
}
})
}
}
return payload
}
exports.prepareSendAPIPayload = prepareSendAPIPayload

0 comments on commit 49507b0

Please sign in to comment.