Created
June 29, 2017 08:51
-
-
Save edlvj/ab457d2a9bb9473ce563fb3cc4343fee to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'use strict' | |
var express = require('express'), | |
http = require('http'), | |
Bot = require('messenger-bot'); | |
var Lafka = require('./node_modules/node_lafka/server.js'); | |
const Wit = require('node-wit').Wit; | |
let bot = new Bot({ | |
token: '', | |
verify: '', | |
page_id: '' | |
}) | |
const firstEntityValue = (entities, entity) => { | |
const val = entities && entities[entity] && | |
Array.isArray(entities[entity]) && | |
entities[entity].length > 0 && | |
entities[entity][0].value; | |
if (!val) { | |
return null; | |
} | |
return typeof val === 'object' ? val.value : val; | |
}; | |
const sessions = {}; | |
const findOrCreateSession = (fbid) => { | |
let sessionId; | |
Object.keys(sessions).forEach(k => { | |
if (sessions[k].fbid === fbid) { | |
sessionId = k; | |
} | |
}); | |
if (!sessionId) { | |
sessionId = new Date().toISOString(); | |
sessions[sessionId] = {fbid: fbid, context: {}}; | |
} | |
return sessionId; | |
}; | |
bot.on('error', (err) => { | |
console.log(err.message) | |
}) | |
global.address; | |
global.chat_in_load; | |
global.chat_last_message_date = 0; | |
var product_page; | |
bot.on('postback', (payload, reply) => { | |
global.goods.push(payload.postback.payload); | |
global.LafkaLib.put('/order/0', { 'products_ids': global.goods, 'address': 'Пока что не установлен', 'device_type': 4 } , function(data) { | |
if (data.status == true) { | |
reply({ text: 'Я добавил товар в корзину.\nКогда закончите поиск товаров. Укажите пожалуйста адрес.\n Например "Мой Адрес Гагарина 77".' }) | |
} else { | |
reply({ text: 'Я не смог добавить товар. Попробуй снова.' }) | |
} | |
} ); | |
}) | |
bot.on('message', (payload, reply) => { | |
let text = payload.message.text | |
var sessionId = findOrCreateSession(payload.sender.id); | |
const actions = { | |
say(sessionId, context, message, cb) { | |
const recipientId = sessions[sessionId].fbid; | |
if (recipientId) { | |
reply ({ text: message}); | |
} else { | |
console.log('Oops! Couldn\'t find user for session:', sessionId); | |
cb(); | |
} | |
}, | |
merge(sessionId, context, entities, message, cb) { | |
const tovar = firstEntityValue(entities, 'tovar'); | |
if(context.address) { | |
delete context.address; | |
} | |
if (tovar) { | |
context.tovar = tovar; | |
} | |
const address = firstEntityValue(entities, 'address'); | |
if (address) { | |
if(context.tovar) { | |
delete context.tovar; | |
} | |
context.address = address; | |
} | |
cb(context); | |
}, | |
error(sessionId, context, error) { | |
console.log(error.message); | |
}, | |
['auth'](sessionId, context, cb) { | |
global.goods = []; | |
global.LafkaLib = new Lafka(); | |
reply({ text: 'Напиши название продукта и я попробую тебе его найти. Например "Огурцы"' }) | |
cb(context); | |
}, | |
['search'](sessionId, context, cb) { | |
global.resp = context.tovar; | |
if(global.LafkaLib == undefined) { | |
reply({text:'Что бы создать новый заказ. Напиши мне "Привет"'}) | |
} | |
global.LafkaLib.search(context.tovar , product_page = 1, 3, function(feed) { | |
if (feed.status == true) { | |
if(feed.data.items.length != 0) { | |
var element = []; | |
for( var i = 0; i < feed.data.items.length; i++){ | |
element.push({title: feed.data.items[i].title, image_url:feed.data.items[i].fullimage_url, subtitle: feed.data.items[i].price, buttons: [{ type: 'postback', title: 'Добавить', payload : feed.data.items[i].id }] }); | |
} | |
reply ({ | |
attachment: { | |
type: "template", | |
payload: { | |
template_type: "generic", | |
elements: element } } | |
}) | |
} else { reply({ text:'Я ничего не нашел, попробуй снова. Например "Молоко"' }) } | |
} else { | |
reply({text:'Произошла ошибка. Попробуй создать новый заказ. Напиши мне "Привет"'}) | |
} | |
}); | |
cb(context); | |
}, | |
['setAdress'](sessionId, context, cb) { | |
global.address = context.address; | |
reply({ text: 'Теперь я знаю куда доставить твой заказ. Хочешь просмотреть Корзину.\nВведи слово "Корзина".' }) | |
cb(context); | |
}, | |
['orders'](sessionId, context, cb) { | |
global.LafkaLib.get('/order/0', function(feed) { | |
if (global.address) { | |
if (feed.status == true) { | |
var products = global.LafkaLib.getProducts(feed.data.id); | |
if (products.status == false) { | |
reply ({ text:'Произошла ошибка. Попробуй создать новый заказ. Напиши мне "Привет"' }) | |
} | |
reply ({ | |
attachment: { | |
type: "template", | |
payload: { | |
template_type: "receipt", | |
recipient_name: global.address, | |
order_number: feed.data.id, | |
currency: 'RUB', | |
payment_method: 'VISA', | |
elements: products, | |
summary:{ | |
total_cost: feed.data.price.toFixed(2) | |
} | |
} | |
} | |
}) | |
reply({text:'Подвердите заказ? Напишите "Да" или "Оформить"'}) | |
} else { reply({ text: 'Нет заказов. Начни поиск товаров.' }) } | |
} else { | |
reply({ text: 'Укажи пожалуйста Адрес Доставки.\n Введи фразу "Мой Адрес ... "' }) | |
} | |
}); | |
cb(context); | |
}, | |
['oformit'](sessionId, context, cb) { | |
console.log(global.goods); | |
global.LafkaLib.post('/order', { 'address': global.address , 'products_ids': global.goods , 'device_type': 4 }, function(data) { | |
if (data.status == true) { | |
CheckNewMsg(); | |
reply({text: 'Спасибо. Заказ оформлен.'}) | |
} else { | |
reply({text: 'Произошла ошибка. Попробуй создать новый заказ. Напиши мне "Привет"'}) | |
} | |
}) | |
cb(context); | |
}, | |
}; | |
const wit = new Wit('token', actions); | |
wit.runActions( | |
sessionId, | |
text, | |
sessions[sessionId].context, | |
(error, context) => { | |
if (error) { | |
console.log('Oops! Got an error from Wit:', error); | |
} else { | |
console.log(context); | |
if (context['done']) { | |
delete sessions[sessionId]; | |
} | |
sessions[sessionId].context = context; | |
} | |
} | |
); | |
function CheckNewMsg() { | |
var timerId = setInterval(function() { | |
ConChat(); | |
}, 10000); | |
} | |
function ConChat() { | |
if(global.chat_in_load) | |
return false; | |
global.chat_in_load = true; | |
var feed = global.LafkaLib.chatRoom(); | |
var i; | |
global.chat_in_load = false; | |
for(i in feed.data.items) | |
{ | |
if (global.chat_last_message_date < Date.parse(feed.data.items[i].date) && feed.data.items[i].is_current_user == false) | |
{ | |
reply({ text: feed.data.items[i].text }) | |
global.chat_last_message_date = Date.parse(feed.data.items[i].date); | |
} | |
} | |
} | |
}); | |
var app = express(); | |
http.createServer(bot.middleware()).listen(process.env.PORT); | |
app.get('/', function (req, res) { | |
res.end('Bot working'); | |
}); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment