From 0f1d9e7f391e793d33270d36171a3483d6a32b2f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Marko=20Markovi=C4=87?= Date: Sun, 22 Apr 2018 20:57:24 +0200 Subject: [PATCH] Add simple intents --- bot/facebook/conversation.js | 53 ++++++++++++++++++++++++++++++++++++ bot/facebook/index.js | 15 +++++----- 2 files changed, 61 insertions(+), 7 deletions(-) create mode 100644 bot/facebook/conversation.js diff --git a/bot/facebook/conversation.js b/bot/facebook/conversation.js new file mode 100644 index 0000000..1fede93 --- /dev/null +++ b/bot/facebook/conversation.js @@ -0,0 +1,53 @@ +const fbTemplate = require('claudia-bot-builder/lib/facebook/format-message') +const fbReply = require('claudia-bot-builder/lib/facebook/reply') + +const normalize = str => str.toLowerCase() + +const send = (recipientId, message) => + fbReply(recipientId, message, process.env.FB_ACCESS_TOKEN) + +const intents = { + default: { + keywords: [], + run(msg, recipient) { + const reply = new fbTemplate.Text( + `Sorry, ${ + recipient.first_name + }. I am a young Bot and still learning. Type "Start" to show the start over.` + ).get() + send(recipient.id, reply) + }, + }, + start: { + keywords: ['start', 'menu', 'help'], + run(msg, recipient) { + const reply = new fbTemplate.Text(` + This is your menu. You can reach it by writing Menu, or Help, or Start + `).get() + send(recipient.id, reply) + }, + }, + drink: { + keywords: ['dring', 'water', 'gimmme'], + run(msg, recipient) { + const reply = new fbTemplate.Text(` + So, you'd like to drink? + `).get() + send(recipient.id, reply) + }, + }, +} + +const getIntent = msg => + Object.keys(intents).find(k => intents[k].keywords.indexOf(msg) !== -1) + +module.exports = async (message, recipient) => { + const intent = getIntent(normalize(message.text)) + + // Fallthrough + if (!intent) { + return intents.default.run(message, recipient) + } + + intents[intent].run(message, recipient) +} diff --git a/bot/facebook/index.js b/bot/facebook/index.js index 0a7c2c0..d4c48e4 100644 --- a/bot/facebook/index.js +++ b/bot/facebook/index.js @@ -5,9 +5,9 @@ const FB = require('fb') FB.setAccessToken(process.env.FB_ACCESS_TOKEN) const fbParser = require('claudia-bot-builder/lib/facebook/parse') -const fbReply = require('claudia-bot-builder/lib/facebook/reply') const fbValidate = require('claudia-bot-builder/lib/facebook/validate-integrity') -const fbTemplate = require('claudia-bot-builder/lib/facebook/format-message') + +const conversation = require('./conversation') /** * In-Memory cache for FB graph results @@ -62,11 +62,12 @@ const respond = async (req, res) => { // Cache recipients recipients[message.sender] = recipient - const replyMessage = new fbTemplate.Text( - `${recipient.first_name} said: "${message.text}"` - ).get() - - fbReply(recipient.id, replyMessage, process.env.FB_ACCESS_TOKEN) + try { + await conversation(message, recipient) + } catch (err) { + console.error(err) + res.end(err.message) + } res.end() } else {