Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- const bodyParser = require("body-parser");
- const express = require("express");
- const FBBotFramework = require("fb-bot-framework");
- const apiai = require("apiai");
- const FB = require("fb");
- //const request = require("request");
- const request = require("request-promise");
- const fetch = require('node-fetch');
- // Initialization
- const app = express();
- const bot = new FBBotFramework({
- page_token: "EAAbm8DBtqvsBADOZBFscxGZBmjkCxmwRuAbcUzGnTjZCIPmZBduAFVx35KBmJ7MLbiKxacDGS5jgjGEKzi6eXXJ63nmv1Txa9h4lSZBe0m3hJ8l2Vi9bt6MKMC2PZBrLkdJ3tZCBuMXWFzsCzQMTFhTwrDowZAY9i2BMWxGdmG9DPPqrnondAGF0ZBUptSajuIxEZD",
- verify_token: "punchcard"
- });
- const agent = apiai("1657993115694d0b9b44f7f5a11040e5");
- //Variables
- var url = "https://punch-card-bot.herokuapp.com";
- var userJson = {};
- var config = {};
- // For the tests only
- var countPostback1 = 0;
- var countPayload1 = 0;
- var initConfig = {
- "number1": 0,
- "number2": 0,
- "accessToken": "",
- "reply": "",
- "text": "",
- "imageUrl": "",
- "buttons": [],
- "timestamp": 0,
- "body": {},
- "postbackLoopGetStarted": true,
- "postbackLoopTerms": false,
- "postbackLoopQ4": false,
- "payloadLoopCard": false,
- "payloadLoopFreq": false,
- "payloadLoopPunchcards": false,
- "payloadLoopBasket": false,
- //"answerQuestionsButton": false,
- "webviewQ1Count": 0,
- "webviewQ4Count": 0
- };
- // Setup Express middleware for /webhook
- app.use("/webhook", bot.middleware());
- app.use(bodyParser.json());
- // Set the right port
- app.set("port", (process.env.PORT || 5000));
- console.log("port:",process.env.PORT);
- app.use(express.static(__dirname));
- // Welcome page
- app.get("/", (req, res) => {
- res.send("Welcome");
- });
- app.set("views", __dirname + "/views");
- app.set("view engine", "pug");
- bot.setGetStartedButton("get_started");
- // Setup listener for incoming messages
- bot.on("message", (userId, message) => {
- console.log("user id:", userId);
- console.log("User text:", message);
- /*
- config[userid].timestamp = Date.now();
- console.log("timetamp:", config[userid].timestamp);
- */
- // For the tests only
- if (message === "Delete" || message === "delete") {
- reset(userId);
- resetLoop(userId);
- config[userId].webviewQ1Count = 0;
- config[userId].webviewQ4Count = 0;
- userJson = {};
- }
- else {
- apiAgent(userId, message);
- }
- });
- // Every quickreply event
- bot.on("quickreply", (userId, payload) => {
- console.log("payload1:", payload);
- console.log("countPayload1:", countPayload1);
- countPayload1++;
- switch(payload) {
- case "payload_yes":
- if (config[userId].payloadLoopCard) {
- apiAgent(userId, "Yes");
- config[userId].payloadLoopCard = false;
- }
- break;
- case "payload_no":
- if (config[userId].payloadLoopCard) {
- apiAgent(userId, "No");
- config[userId].payloadLoopCard = false;
- }
- break;
- // TODO: delete useless var
- case "daily":
- case "weekly":
- case "monthly":
- if (config[userId].payloadLoopFreq) {
- apiAgent(userId, payload);
- config[userId].payloadLoopFreq = false;
- }
- break;
- case "basket_choice1":
- case "basket_choice2":
- case "basket_choice3":
- case "basket_choice4":
- if (config[userId].payloadLoopBasket) {
- apiAgent(userId, payload);
- userJson[userId].onboardingQuestions.basketSize = payload;
- config[userId].payloadLoopBasket = false;
- }
- break;
- case "all":
- case "redeemable":
- case "collecting":
- selectPunchcards(userId, payload);
- break;
- }
- });
- // Every postback event
- bot.on("postback", (userId, payload) => {
- console.log("postback1:", payload);
- console.log("countPostback1:", countPostback1);
- countPostback1++;
- if ((Object.keys(config).length === 0) && (config.constructor === Object)) {
- console.log("create json config");
- config[userId] = initConfig;
- }
- if ((Object.keys(userJson).length === 0) && (userJson.constructor === Object)) {
- console.log("create userJson[userId]");
- userJson[userId] = {};
- }
- switch (payload) {
- case "get_started":
- if (config[userId].postbackLoopGetStarted) {
- config[userId].postbackLoopGetStarted = false;
- getStarted(userId);
- setTimeout( () => {
- acceptTerms(userId);
- }, 3500);
- }
- else {
- config[userId].reply = "You've already done that :)";
- bot.sendTextMessage(userId, config[userId].reply);
- }
- break;
- case "how_it_works":
- config[userId].reply = "TODO";
- bot.sendTextMessage(userId, config[userId].reply);
- break;
- case "contact_supermarket":
- config[userId].reply = "TODO";
- bot.sendTextMessage(userId, config[userId].reply);
- break;
- case "logout":
- config[userId].reply = "TODO";
- bot.sendTextMessage(userId, config[userId].reply);
- break;
- // For the tests only
- case "start_menu":
- getStarted(userId);
- setTimeout( () => {
- acceptTerms(userId);
- }, 3500);
- break;
- case "reset_json":
- reset(userId);
- resetLoop(userId);
- config[userId].webviewQ1Count = 0;
- config[userId].webviewQ4Count = 0;
- userJson = {};
- config[userId].reply = "The user json was reset :)";
- bot.sendTextMessage(userId, config[userId].reply);
- break;
- case "questions_menu":
- if ((Object.keys(userJson[userId]).length !== 0) && (userJson[userId].terms === "accepted") && (userJson[userId].cardNumber != undefined)) {
- // Commented only for the test
- //if ((userJson[userId].onboardingQuestions == undefined) || (Object.keys(userJson[userId].onboardingQuestions).length === 0) || ((userJson[userId].onboardingQuestions.dietPreferences == undefined) || (userJson[userId].onboardingQuestions.dietPreferences.length === 0))) {
- //TODO: maybe put reset context here
- resetLoop(userId);
- config[userId].reply = "Now we have only 4 questions for you in order to personnalize your cards.";
- bot.sendTextMessage(userId, config[userId].reply);
- config[userId].webviewQ1Count = 0;
- config[userId].webviewQ4Count = 0;
- setTimeout( () => {
- config[userId].text = "answer-questions";
- apiAgent(userId, config[userId].text);
- }, 2000);
- //}
- /*
- else {
- config[userId].reply = "You have already answered the onboarding questions.";
- bot.sendTextMessage(userId, config[userId].reply);
- }
- */
- }
- else {
- config[userId].reply = "You can't use this button now.";
- bot.sendTextMessage(userId, config[userId].reply);
- }
- break;
- case "punchcards":
- // Commented only for the test
- //if ((Object.keys(userJson[userId]).length !== 0) && (userJson[userId].terms === "accepted") && (userJson[userId].cardNumber != undefined)) {
- reset(userId);
- resetLoop(userId);
- //webviewPunchcards(userId);
- displayPunchcards(userId, true);
- //}
- /*
- else {
- config[userId].reply = "You can't use this button now.";
- bot.sendTextMessage(userId, config[userId].reply);
- }
- */
- break;
- case "reset_menu":
- reset(userId);
- resetLoop(userId);
- // For the tests only
- config[userId].webviewQ1Count = 0;
- config[userId].webviewQ4Count = 0;
- config[userId].reply = "All the contexts and the variables were reset.";
- bot.sendTextMessage(userId, config[userId].reply);
- break;
- case "payload_decline":
- if (config[userId].postbackLoopTerms) {
- config[userId].postbackLoopTerms = false;
- userJson[userId].terms = "declined";
- config[userId].reply = "Too bad.";
- bot.sendTextMessage(userId, config[userId].reply);
- setTimeout( () => {
- config[userId].reply = "Only by accepting the T&C will you be able to participate through Facebook Messenger.";
- bot.sendTextMessage(userId, config[userId].reply);
- }, 1500);
- setTimeout( () => {
- config[userId].reply = "Do you accept these T&C?";
- config[userId].buttons = [
- {
- "type": "postback",
- "title": "Decline",
- "payload": "payload_decline"
- },
- {
- "type": "postback",
- "title": "Accept",
- "payload": "payload_accept"
- }
- ];
- bot.sendButtonMessage(userId, config[userId].reply, config[userId].buttons);
- config[userId].postbackLoopTerms = true;
- }, 3000);
- config[userId].postbackLoopTerms = false;
- }
- break;
- case "payload_accept":
- if (config[userId].postbackLoopTerms) {
- config[userId].postbackLoopTerms = false;
- userJson[userId].terms = "accepted";
- config[userId].reply = "Marvelous :)";
- bot.sendTextMessage(userId, config[userId].reply);
- setTimeout( () => {
- config[userId].reply = "Now please enter your loyalty card number so we can retrieve your account details."
- bot.sendTextMessage(userId, config[userId].reply);
- }, 1500);
- setTimeout( () => {
- config[userId].text = "loyalty-card-number";
- apiAgent(userId, config[userId].text);
- }, 3500);
- config[userId].postbackLoopTerms = false;
- }
- break;
- case "question4":
- if (config[userId].postbackLoopQ4) {
- console.log("end onboarding");
- endOnboarding(userId);
- config[userId].postbackLoopQ4 = false;
- config[userId].webviewQ4Count = 1;
- }
- break;
- }
- });
- bot.on('attachment', function(userId, attachment){
- console.log("attachment:", attachment);
- /*
- Type image: GIF (.gif in payload.url), image, stickers (payload.sticker_id)
- Type audio: recorder, song file
- Type video: video attached
- Type file: pdf..
- Type location: send the location (with mobile)
- */
- switch (attachment[0].type) {
- case "location":
- var latitude = attachment[0].payload.coordinates.lat;
- var longitude = attachment[0].payload.coordinates.long;
- json = "http://api.openweathermap.org/data/2.5/weather?lat=" + latitude + "&lon=" + longitude + "&appid=9393e4c87b6070958c8611b9f5211c48"
- // Retrieve the weather JSON file from the url
- fetch(json)
- .then((res) => {
- return res.json();
- }).then((json) => {
- var city = json.name;
- config[userId].reply = city + " is a beautiful city :)"
- bot.sendTextMessage(userId, config[userId].reply);
- })
- break;
- case "image":
- if (attachment[0].payload.sticker_id != undefined){
- config[userId].reply = "Nice sticker 👍"
- bot.sendTextMessage(userId, config[userId].reply);
- }
- else if (attachment[0].payload.url.search(".gif")) {
- console.log("gif!");
- config[userId].imageUrl = "https://media.giphy.com/media/l3HBbltOYjoNq/giphy.gif";
- bot.sendImageMessage(userId, config[userId].imageUrl);
- }
- else {
- config[userId].reply = "Nice image!"
- bot.sendTextMessage(userId, config[userId].reply);
- }
- break;
- case "audio":
- config[userId].reply = "Great sound :D"
- bot.sendTextMessage(userId, config[userId].reply);
- break;
- case "video":
- config[userId].reply = "Thanks for the video ;)"
- bot.sendTextMessage(userId, config[userId].reply);
- break;
- case "file":
- config[userId].reply = "Thanks for sending a file but I can't do anything with that :p"
- bot.sendTextMessage(userId, config[userId].reply);
- break;
- case "template":
- config[userId].reply = "I love this webview!"
- bot.sendTextMessage(userId, config[userId].reply);
- break;
- }
- setTimeout( () => {
- config[userId].text = "no-context";
- apiAgent(userId, config[userId].text);
- }, 1500);
- });
- // Make Express listening
- app.listen(app.get("port"), () => {
- console.log("Started on port", app.get("port"));
- })
- // Main function: user message event
- function apiAgent(userId, message) {
- console.log("Message sent to apiai:", message);
- // Send text content to the right Api.ai agent
- var requestApiai = agent.textRequest(message, {
- sessionId: userId
- });
- /*
- var context = agent.getContextsRequest({sessionId: "2fa6a5073f444164886980acb2e3d15a"})
- console.log("context:", context);
- */
- // Reset the count each new message from the bot (in the case the bot sends several answers)
- var count = 0;
- // Api.ai agent answers
- requestApiai.on("response", (response) => {
- //console.log("ARGS:", arguments)
- console.log("apiai answer:", response.result.fulfillment);
- while (count < response.result.fulfillment.messages.length) {
- botAnswer = response.result.fulfillment.messages[count];
- console.log("platform:", botAnswer.platform);
- if (botAnswer.platform == "facebook" || botAnswer.platform == undefined) {
- // If the answer is a custom payload (type = 4)
- if ((botAnswer.type == 4)) {
- console.log("answer type 4:", botAnswer.payload);
- var apiaiContext = botAnswer.payload.facebook.attachment.type;
- console.log("apiaiContext", apiaiContext);
- switch (apiaiContext) {
- // For car number yes/no quick replies
- case "yes-no":
- var payloadApi = botAnswer.payload.facebook.attachment.payload;
- if (payloadApi.number1 !== undefined) {
- config[userId].number1 = payloadApi.number1;
- }
- console.log("number1:", config[userId].number1);
- bot.sendQuickReplies(userId, payloadApi.text, payloadApi.quick_reply);
- config[userId].payloadLoopCard = true;
- //payloadEvent(userId);
- break;
- // To confirm the right loyalty card number
- case "number-confirmation":
- config[userId].number2 = botAnswer.payload.facebook.attachment.payload.number2;
- console.log("number2:", config[userId].number2);
- if (config[userId].number1 === config[userId].number2) {
- userJson[userId].cardNumber = config[userId].number2;
- //console.log("Json file:", userJson);
- config[userId].imageUrl = "https://media.tenor.com/images/183267efd48bc2a9f176420ab0b9c373/tenor.gif";
- bot.sendImageMessage(userId, config[userId].imageUrl);
- setTimeout( () => {
- config[userId].reply = "Now we have only 4 questions for you in order to personnalize your cards.";
- bot.sendTextMessage(userId, config[userId].reply);
- }, 3000);
- setTimeout( () => {
- config[userId].text = "answer-questions";
- apiAgent(userId, config[userId].text);
- }, 5000);
- }
- else {
- config[userId].reply = "Oops... You made a mistake, do it again please.";
- bot.sendTextMessage(userId, config[userId].reply);
- setTimeout( () => {
- reset(userId);
- }, 100);
- setTimeout( () => {
- config[userId].text = "loyalty-card-number";
- apiAgent(userId, config[userId].text);
- }, 2000);
- }
- userJson[userId].onboardingQuestions = {};
- break;
- // For punch cards display
- case "punch-card-display":
- resetLoop(userId);
- displayPunchcards(userId, false);
- break;
- // Onbording questions: question 1
- case "products-category":
- resetLoop(userId);
- if (userJson[userId].onboardingQuestions == undefined) {
- userJson[userId].onboardingQuestions = {};
- }
- userJson[userId].onboardingQuestions.productsCategory = [];
- productsCategory = [
- {
- "title": "Question 1: Usually, what do you buy at our stores?",
- //"image_url": url + "/public/images/supermarket.jpg",
- //"image_url": "http://images.mid-day.com/2013/mar/supermarket.jpg",
- "image_url": "https://image.freepik.com/free-vector/supermarket-shelves_23-2147495480.jpg",
- "buttons": [
- {
- "type":"web_url",
- "title":"Choose",
- "url": url + "/views/question1.html",
- "messenger_extensions": true,
- "webview_height_ratio": "tall",
- "fallback_url": url + "/views/question1.html"
- }
- ]
- }
- ];
- config[userId].reply = "Ok, let's do it! 👍";
- bot.sendTextMessage(userId, config[userId].reply);
- //Json page to retrieve food data (question 1)
- app.post("/question1", (req, res) => {
- res.send({});
- console.log("req:", req.body);
- if (config[userId].webviewQ1Count === 0) {
- if (Object.keys(req.body).length === 0 && req.body.constructor === Object) {
- config[userId].reply = "Please, select at least one product.";
- bot.sendTextMessage(userId, config[userId].reply);
- }
- else {
- userJson[userId].onboardingQuestions.productsCategory = [];
- for (property in req.body) {
- //console.log("property:", property);
- if (req.body[property]%2 != 0) {
- userJson[userId].onboardingQuestions.productsCategory.push(property);
- }
- }
- if (userJson[userId].onboardingQuestions.productsCategory.length === 0) {
- config[userId].reply = "Please, select some products.";
- bot.sendTextMessage(userId, config[userId].reply);
- }
- else {
- if (config[userId].webviewQ1Count === 0 ) {
- config[userId].webviewQ1Count = 1;
- config[userId].text = "question-answered";
- apiAgent(userId, config[userId].text);
- }
- /*
- else {
- config[userId].reply = "You already answered the first question...";
- bot.sendTextMessage(userId, config[userId].reply);
- }
- */
- }
- }
- }
- });
- setTimeout( () => {
- bot.sendGenericMessage(userId, productsCategory);
- }, 1500);
- break;
- // Onbording questions: question 2
- case "frequency":
- resetLoop(userId);
- userJson[userId].onboardingQuestions.frequency = {};
- var payloadApi = botAnswer.payload.facebook.attachment.payload;
- setTimeout( () => {
- bot.sendQuickReplies(userId, payloadApi.text, payloadApi.quick_reply);
- config[userId].payloadLoopFreq = true;
- //payloadEvent(userId);
- }, 3000);
- break;
- case "frequency-answer":
- var payloadApi = botAnswer.payload.facebook.attachment.payload;
- var answer = payloadApi.text;
- console.log("answer:", answer);
- userJson[userId].onboardingQuestions.frequency.unity = answer.toLowerCase();
- console.log("json here:", userJson);
- break;
- // Onbording questions: question 3
- case "basket-size":
- resetLoop(userId);
- var payloadApi = botAnswer.payload.facebook.attachment.payload;
- // Last question result
- userJson[userId].onboardingQuestions.frequency.times = payloadApi.result;
- setTimeout( () => {
- config[userId].payloadLoopBasket = true;
- bot.sendQuickReplies(userId, payloadApi.text, payloadApi.quick_reply);
- //payloadEvent(userId);
- }, 2000);
- break;
- case "diet-preferences":
- resetLoop(userId);
- config[userId].postbackLoopQ4 = true;
- userJson[userId].onboardingQuestions.dietPreferences = []
- dietsPreferences = [
- {
- "title": "Question 4: Do you have any diet preferences or allergies?",
- "image_url": "http://21406-presscdn.pagely.netdna-cdn.com/wp-content/uploads/2017/01/healthy-foods.jpg",
- "buttons": [
- {
- "type":"web_url",
- "title":"Yes",
- "url": url + "/views/question4.html",
- "messenger_extensions": true,
- "webview_height_ratio": "tall",
- "fallback_url": url + "/views/question4.html"
- },
- {
- "type": "postback",
- "title": "No",
- "payload": "question4"
- }
- ]
- }
- ];
- //Json page to retrieve food data (question 1)
- app.post("/question4", (req, res) => {
- res.send({});
- console.log("req:", req.body);
- if (config[userId].webviewQ4Count === 0) {
- userJson[userId].onboardingQuestions.dietPreferences = [];
- for (property in req.body) {
- if (property === "preferences") {
- userJson[userId].onboardingQuestions.dietPreferences.push(req.body[property]);
- }
- else if (property === "allergies") {
- userJson[userId].onboardingQuestions.allergies = req.body[property];
- }
- else if (req.body[property]%2 != 0) {
- userJson[userId].onboardingQuestions.dietPreferences.push(property);
- }
- }
- config[userId].webviewQ4Count = 1;
- endOnboarding(userId);
- console.log("final json:", userJson[userId]);
- }
- //console.log("test json:", userJson[userId]);
- });
- setTimeout( () => {
- bot.sendGenericMessage(userId, dietsPreferences);
- }, 2000);
- break;
- case "no-context":
- resetLoop(userId);
- console.log("json nocontext:", userJson[userId]);
- if (((Object.keys(userJson).length === 0) && (userJson.constructor === Object))
- || ((Object.keys(userJson[userId]).length === 0) && (userJson[userId].constructor === Object))
- || (userJson[userId].terms !== "accepted")) {
- config[userId].text = "push-button-fallback";
- apiAgent(userId, config[userId].text);
- acceptTerms(userId);
- }
- else if (userJson[userId].cardNumber == undefined) {
- //config[userId].reply = "You didn't confirm your card number :/ We need it to log you in the right account.";
- config[userId].reply = "Now please enter your loyalty card number so we can retrieve your account details."
- bot.sendTextMessage(userId, config[userId].reply);
- setTimeout( () => {
- config[userId].text = "loyalty-card-number";
- apiAgent(userId, config[userId].text);
- }, 2000);
- }
- else if (((Object.keys(userJson[userId].onboardingQuestions).length !== 0) && (userJson[userId].onboardingQuestions.constructor === Object))
- && ((userJson[userId].onboardingQuestions.dietPreferences == undefined) || (userJson[userId].onboardingQuestions.dietPreferences.length === 0))) {
- //config[userId].reply = "You didn't finish answering the questions last time :/";
- config[userId].reply = "Now we have only 4 questions for you in order to personnalize your cards.";
- bot.sendTextMessage(userId, config[userId].reply);
- config[userId].webviewQ1Count = 0;
- config[userId].webviewQ4Count = 0;
- setTimeout( () => {
- config[userId].text = "answer-questions";
- apiAgent(userId, config[userId].text);
- }, 2000);
- }
- else {
- config[userId].reply = "There isn't any context, use the menu :p";
- bot.sendTextMessage(userId, config[userId].reply);
- }
- /*
- // TODO: startQuestions(userId)
- else if () {
- if ( (config[userId].timestamp - Date.now() > 600000) ) {
- config[userId].reply = "Welcome back!"
- }
- else {
- //reply
- }
- }
- */
- break;
- }
- }
- // If the answer is a text response (type = 0)
- else if (botAnswer.type == 0) {
- console.log("answer type 0:", response.result.fulfillment);
- config[userId].reply = botAnswer.speech;
- bot.sendTextMessage(userId, config[userId].reply);
- }
- }
- count++;
- }
- })
- requestApiai.on("error", (error) => {
- console.log("errooor:", error);
- });
- requestApiai.end();
- }
- // For request catch error
- function catchError(userId, error) {
- console.log("error:", error);
- config[userId].reply = "There was a problem with the request, we apologize for the inconvenience.";
- bot.sendTextMessage(userId, config[userId].reply);
- }
- // To display right text (singular/plurial)
- function dayDisplay(number) {
- var day;
- if (number === 0 || number === 1 || number === -1) {
- day = "day";
- }
- else {
- day = "days";
- }
- return day;
- }
- // Reset apiai contexts
- function reset(userId) {
- if ((Object.keys(config).length === 0) && (config.constructor === Object)) {
- console.log("create json config1");
- config[userId] = initConfig;
- }
- config[userId].text = "reset";
- apiAgent(userId, config[userId].text);
- }
- function resetLoop(userId) {
- if ((Object.keys(config).length === 0) && (config.constructor === Object)) {
- console.log("create json config2");
- config[userId] = initConfig;
- }
- else {
- // TODO: for loop
- //config[userId].postbackLoopGetStarted = false;
- config[userId].postbackLoopReset = false;
- config[userId].postbackLoopTerms = false;
- config[userId].postbackLoopQ4 = false;
- config[userId].payloadLoopCard = false;
- config[userId].payloadLoopFreq = false;
- config[userId].payloadLoopPunchcards = false;
- config[userId].payloadLoopBasket = false;
- }
- }
- function displayPunchcards(userId, quickreply) {
- // Retrieve token from the user
- var options = {
- method: "GET",
- url: "https://alfamart-poa-dev.bright-shopper.nl/v1/loyalties/punchcards/tenants/alfamart/programs/punch1/poa/oauth2/token",
- qs: {
- username: "dennis",
- password: "123",
- grant_type: "password"
- }
- };
- request(options)
- .then( (body) => {
- config[userId].accessToken = JSON.parse(body).access_token
- // Get punch card thanks to the user token
- var options = {
- method: "GET",
- url: "https://punch-mock.bright-shopper.nl/v1/loyalties/punchcards/tenants/alfamart/programs/punch1/mock/my/punchcards"
- /*url: "https://alfamart-poa-dev.bright-shopper.nl/v1/loyalties/punchcards/tenants/alfamart/programs/punch1/poa/participations/596c6e9333cd6616a9d86e0a/punchcards",
- qs: {
- listAll: "true"
- },
- headers: {
- authorization: "Bearer " + config[userId].accessToken
- }*/
- };
- request(options)
- .then( (body) => {
- //console.log("body punchcard", body);
- config[userId].body = JSON.parse(body);
- if (config[userId].body.code == "invalid_token") {
- config[userId].reply = "Invalid Token";
- bot.sendTextMessage(userId, config[userId].reply);
- }
- else {
- if (quickreply) {
- config[userId].reply = "Which cards do you want to display?";
- config[userId].buttons = [
- {
- "content_type": "text",
- "title": "All",
- "payload": "all"
- },
- {
- "content_type": "text",
- "title": "Complete",
- "payload": "redeemable"
- },
- {
- "content_type": "text",
- "title": "In progress",
- "payload": "collecting"
- }
- ]
- bot.sendQuickReplies(userId, config[userId].reply, config[userId].buttons);
- }
- else {
- selectPunchcards(userId, "all")
- }
- }
- })
- .catch( (error) => catchError(userId, error))
- })
- .catch( (error) => catchError(userId, error))
- }
- function selectPunchcards(userId, payload) {
- var b = config[userId].body;
- var punchCards = [];
- var cardNumber = b.punchcards.length;
- //console.log("punchcards number:", cardNumber);
- var sayDay = "day";
- for (i=0; i<cardNumber; i++) {
- var num = i.toString();
- if (b.punchcards[i].collect != undefined) {
- var dayNumber = b.punchcards[i].collect.daysRemaining;
- }
- if (b.punchcards[i].redeem != undefined) {
- var dayNumber = b.punchcards[i].redeem.daysRemaining;
- }
- if (payload === "all" || payload === b.punchcards[i].status) {
- // Send punchcards data to pug file
- if (b.punchcards[i].status === "redeemable") {
- app.get("/views/punchcards/redeemable/:userId/:num" , function (req, res) {
- console.log("complete card");
- console.log("req:", req.params);
- res.render("punchcards_complete", {});
- });
- punchCards.push(
- {
- "image_url": "https://punch-mock.bright-shopper.nl/" + b.punchcards[i].imageUrl,
- //"image_url": "https://s3-eu-west-1.amazonaws.com/punchcards-images-dev/" + b.punchcards[i].image,
- "title": b.punchcards[i].localizedContent["en-us"].title,
- "subtitle": "Days left to redeem: " + dayNumber + dayDisplay(dayNumber) + ".\nBALANCE: " + b.punchcards[i].punches + "/" + b.punchcards[i].requiredPunches,
- "buttons": [
- {
- "title": "Open",
- "type": "web_url",
- "url": url + "/views/punchcards/redeemable/" + userId + "/" + num,
- "messenger_extensions": true,
- "webview_height_ratio": "tall",
- "fallback_url": url + "/views/punchcards/redeemable/" + userId + "/" + num
- }
- ]
- }
- );
- }
- else if (b.punchcards[i].collectMechanism === "products") {
- app.get("/views/punchcards/products/:userId/:num" , function (req, res) {
- console.log("products");
- console.log("req:", req.params);
- var products = b.punchcards[req.params.num].eligibleProducts.previewProducts;
- for (j=0; j<b.punchcards[req.params.num].eligibleProducts.total; j++) {
- if (products[j].price.toString().length > 2) {
- products[j].euros = products[j].price.toString().substr(0, products[j].price.toString().length-2);
- products[j].cents = products[j].price.toString().substr(-2, products[j].price.toString().length);
- }
- else {
- products[j].euros = "0";
- products[j].cents = products[j].price.toString().substr(0, products[j].price.toString().length);
- }
- }
- res.render("punchcards_products",
- {
- title: b.punchcards[req.params.num].localizedContent["en-us"].title,
- productsList: products
- });
- });
- punchCards.push(
- {
- "image_url": "https://punch-mock.bright-shopper.nl/" + b.punchcards[i].imageUrl,
- //"image_url": "https://s3-eu-west-1.amazonaws.com/punchcards-images-dev/" + b.punchcards[i].image,
- "title": b.punchcards[i].localizedContent["en-us"].title,
- "subtitle": "Days left to redeem: " + dayNumber + dayDisplay(dayNumber) + ".\nBALANCE: " + b.punchcards[i].punches + "/" + b.punchcards[i].requiredPunches,
- "buttons": [
- {
- "title": "Open",
- "type": "web_url",
- "url": url + "/views/punchcards/products/" + userId + "/" + num,
- "messenger_extensions": true,
- "webview_height_ratio": "tall",
- "fallback_url": url + "/views/punchcards/products/" + userId + "/" + num
- }
- ]
- }
- );
- }
- else if (b.punchcards[i].collectMechanism === "money") {
- app.get("/views/punchcards/money/:userId/:num" , function (req, res) {
- console.log("money");
- console.log("req:", req.params);
- res.render("punchcards_money",
- {
- title: b.punchcards[req.params.num].localizedContent["en-us"].title,
- subtitle: b.punchcards[req.params.num].moneyBooster.localizedContent["en-us"].title,
- body: b.punchcards[req.params.num].moneyBooster.localizedContent["en-us"].body.split("\n\n"),
- url: b.punchcards[req.params.num].imageUrl
- });
- });
- punchCards.push(
- {
- "image_url": "https://punch-mock.bright-shopper.nl/" + b.punchcards[i].imageUrl,
- //"image_url": "https://s3-eu-west-1.amazonaws.com/punchcards-images-dev/" + b.punchcards[i].image,
- "title": b.punchcards[i].localizedContent["en-us"].title,
- "subtitle": "Days left to redeem: " + dayNumber + dayDisplay(dayNumber) + ".\nBALANCE: " + b.punchcards[i].punches + "/" + b.punchcards[i].requiredPunches,
- "buttons": [
- {
- "title": "Open",
- "type": "web_url",
- "url": url + "/views/punchcards/money/" + userId + "/" + num,
- "messenger_extensions": true,
- "webview_height_ratio": "tall",
- "fallback_url": url + "/views/punchcards/money/" + userId + "/" + num
- }
- ]
- }
- );
- }
- }
- }
- if (punchCards.length > 4) {
- bot.sendGenericMessage(userId, punchCards);
- console.log("Punchcards end:", punchCards);
- }
- else if (punchCards.length <= 4) {
- bot.sendListMessage(userId, punchCards);
- console.log("Punchcards end:", punchCards);
- }
- else {
- config[userId].reply = "You don't have this kind of cards.";
- bot.sendTextMessage(userId, config[userId].reply);
- }
- }
- function webviewPunchcards(userId) {
- // Retrieve token from the user
- var options = {
- method: "GET",
- url: "https://alfamart-poa-dev.bright-shopper.nl/v1/loyalties/punchcards/tenants/alfamart/programs/punch1/poa/oauth2/token",
- qs: {
- username: "dennis",
- password: "123",
- grant_type: "password"
- }
- };
- request(options)
- .then( (body) => {
- config[userId].accessToken = JSON.parse(body).access_token
- // Get punch card thanks to the user token
- var options = {
- method: "GET",
- //url: "https://alfamart-poa-dev.bright-shopper.nl/v1/loyalties/punchcards/tenants/alfamart/programs/punch1/mock/my/punchcards",
- url: "https://punch-mock.bright-shopper.nl/v1/loyalties/punchcards/tenants/alfamart/programs/punch1/mock/my/punchcards"
- };
- request(options)
- .then( (body) => {
- //console.log("body punchcard", body);
- if (b.code == "invalid_token") {
- config[userId].reply = "Invalid Token";
- bot.sendTextMessage(userId, config[userId].reply);
- }
- else {
- }
- })
- .catch( (error) => catchError(userId, error))
- })
- .catch( (error) => catchError(userId, error))
- }
- function acceptTerms(userId) {
- userJson[userId] = {};
- //Send message to Apiai to push the user pushing one button
- config[userId].reply = "Before we continue, you must first accept the T&C";
- config[userId].buttons = [
- {
- "type": "web_url",
- "url": "https://alfamart-punchportalnginx-dev.bright-shopper.nl/index.html?#/",
- "title": "Terms & Conditions"
- }
- ];
- bot.sendButtonMessage(userId, config[userId].reply, config[userId].buttons);
- setTimeout( () => {
- config[userId].reply = "Do you accept these T&C?";
- config[userId].buttons = [
- {
- "type": "postback",
- "title": "Accept",
- "payload": "payload_accept"
- },
- {
- "type": "postback",
- "title": "Decline",
- "payload": "payload_decline"
- }
- ];
- //bot.sendQuickReplies(userId, config[userId].reply, config[userId].buttons);
- bot.sendButtonMessage(userId, config[userId].reply, config[userId].buttons);
- }, 1500);
- config[userId].postbackLoopTerms = true;
- }
- function endOnboarding(userId) {
- config[userId].imageUrl = "https://media.giphy.com/media/3oz9ZE2Oo9zRC/giphy.gif";
- bot.sendImageMessage(userId, config[userId].imageUrl);
- setTimeout( () => {
- config[userId].reply = "You finished the onboarding questions! Now here are your punchards.";
- bot.sendTextMessage(userId, config[userId].reply);
- }, 2000);
- setTimeout( () => {
- displayPunchcards(userId, false);
- }, 4000);
- console.log("json:", userJson[userId]);
- reset(userId);
- resetLoop(userId);
- }
- function getStarted(userId) {
- userJson[userId] = {};
- config[userId] = initConfig;
- config[userId].text = "push-button-fallback";
- apiAgent(userId, config[userId].text);
- FB.setAccessToken("EAAbm8DBtqvsBADOZBFscxGZBmjkCxmwRuAbcUzGnTjZCIPmZBduAFVx35KBmJ7MLbiKxacDGS5jgjGEKzi6eXXJ63nmv1Txa9h4lSZBe0m3hJ8l2Vi9bt6MKMC2PZBrLkdJ3tZCBuMXWFzsCzQMTFhTwrDowZAY9i2BMWxGdmG9DPPqrnondAGF0ZBUptSajuIxEZD");
- var urlUserId = "/" + userId;
- FB.api(urlUserId, (res) => {
- if (!res || res.error) {
- console.log(!res ? "error occurred" : res.error);
- return;
- }
- //console.log("res:",res);
- config[userId].reply = "Hi " + res.first_name + "! " + "Welcome to the Punch Card bot :)";
- bot.sendTextMessage(userId, config[userId].reply);
- });
- setTimeout( () => {
- config[userId].imageUrl = "https://media.giphy.com/media/glEsn20jvC7iE/giphy.gif";
- bot.sendImageMessage(userId, config[userId].imageUrl);
- }, 300);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement