botpress-hitl
Advanced tools
Comparing version 0.0.1 to 1.0.0
@@ -65,7 +65,7 @@ module.exports = | ||
var _path = __webpack_require__(6); | ||
var _path = __webpack_require__(7); | ||
var _path2 = _interopRequireDefault(_path); | ||
var _fs = __webpack_require__(7); | ||
var _fs = __webpack_require__(8); | ||
@@ -76,2 +76,4 @@ var _fs2 = _interopRequireDefault(_fs); | ||
function _asyncToGenerator(fn) { return function () { var gen = fn.apply(this, arguments); return new Promise(function (resolve, reject) { function step(key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { return Promise.resolve(value).then(function (value) { step("next", value); }, function (err) { step("throw", err); }); } } return step("next"); }); }; } | ||
// TODO: Cleanup old sessions | ||
@@ -81,18 +83,4 @@ // TODO: If messages count > X, delete some | ||
var db = null; | ||
var configFile = null; | ||
var config = {}; | ||
var config = null; | ||
var saveConfig = function saveConfig(config) { | ||
_fs2.default.writeFileSync(configFile, JSON.stringify(config)); | ||
}; | ||
var loadConfig = function loadConfig() { | ||
if (!_fs2.default.existsSync(configFile)) { | ||
var _config = { sessionExpiry: '3 days', paused: false }; | ||
saveConfig(_config, configFile); | ||
} | ||
return Object.assign(JSON.parse(_fs2.default.readFileSync(configFile, 'utf-8'))); | ||
}; | ||
var incomingMiddleware = function incomingMiddleware(event, next) { | ||
@@ -108,3 +96,2 @@ if (!db) { | ||
return db.getUserSession(event).then(function (session) { | ||
if (session.is_new_session) { | ||
@@ -115,5 +102,3 @@ event.bp.events.emit('hitl.session', session); | ||
return db.appendMessageToSession(event, session.id, 'in').then(function (message) { | ||
event.bp.events.emit('hitl.message', message); | ||
if ((!!session.paused || config.paused) && _lodash2.default.includes(['text', 'message'], event.type)) { | ||
@@ -149,30 +134,58 @@ event.bp.logger.debug('[hitl] Session paused, message swallowed:', event.text); | ||
module.exports = { | ||
init: function init(bp) { | ||
configFile = _path2.default.join(bp.projectLocation, bp.botfile.modulesConfigDir, 'botpress-hitl.json'); | ||
config = loadConfig(); | ||
bp.middlewares.register({ | ||
name: 'hitl.captureInMessages', | ||
type: 'incoming', | ||
order: 2, | ||
handler: incomingMiddleware, | ||
module: 'botpress-hitl', | ||
description: 'Captures incoming messages and if the session if paused, swallow the event.' | ||
}); | ||
config: { | ||
sessionExpiry: { type: 'string', default: '3 days' }, | ||
paused: { type: 'bool', default: false, env: 'BOTPRESS_HITL_PAUSED' } | ||
}, | ||
bp.middlewares.register({ | ||
name: 'hitl.captureOutMessages', | ||
type: 'outgoing', | ||
order: 50, | ||
handler: outgoingMiddleware, | ||
module: 'botpress-hitl', | ||
description: 'Captures outgoing messages to show inside HITL.' | ||
}); | ||
init: function () { | ||
var _ref = _asyncToGenerator(regeneratorRuntime.mark(function _callee(bp, configurator) { | ||
return regeneratorRuntime.wrap(function _callee$(_context) { | ||
while (1) { | ||
switch (_context.prev = _context.next) { | ||
case 0: | ||
_context.next = 2; | ||
return configurator.loadAll(); | ||
bp.db.get().then(function (knex) { | ||
return db = (0, _db2.default)(knex); | ||
}).then(function () { | ||
return db.initialize(); | ||
}); | ||
}, | ||
case 2: | ||
config = _context.sent; | ||
bp.middlewares.register({ | ||
name: 'hitl.captureInMessages', | ||
type: 'incoming', | ||
order: 2, | ||
handler: incomingMiddleware, | ||
module: 'botpress-hitl', | ||
description: 'Captures incoming messages and if the session if paused, swallow the event.' | ||
}); | ||
bp.middlewares.register({ | ||
name: 'hitl.captureOutMessages', | ||
type: 'outgoing', | ||
order: 50, | ||
handler: outgoingMiddleware, | ||
module: 'botpress-hitl', | ||
description: 'Captures outgoing messages to show inside HITL.' | ||
}); | ||
bp.db.get().then(function (knex) { | ||
return db = (0, _db2.default)(knex); | ||
}).then(function () { | ||
return db.initialize(); | ||
}); | ||
case 6: | ||
case 'end': | ||
return _context.stop(); | ||
} | ||
} | ||
}, _callee, undefined); | ||
})); | ||
return function init(_x, _x2) { | ||
return _ref.apply(this, arguments); | ||
}; | ||
}(), | ||
ready: function ready(bp) { | ||
@@ -263,2 +276,4 @@ | ||
var _botpress = __webpack_require__(6); | ||
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } | ||
@@ -273,3 +288,3 @@ | ||
return knex.schema.createTableIfNotExists('hitl_sessions', function (table) { | ||
return (0, _botpress.DatabaseHelpers)(knex).createTableIfNotExists('hitl_sessions', function (table) { | ||
table.increments('id').primary(); | ||
@@ -285,3 +300,3 @@ table.string('platform'); | ||
}).then(function () { | ||
return knex.schema.createTableIfNotExists('hitl_messages', function (table) { | ||
return (0, _botpress.DatabaseHelpers)(knex).createTableIfNotExists('hitl_messages', function (table) { | ||
table.increments('id').primary(); | ||
@@ -300,3 +315,3 @@ table.integer('session_id').references('hitl_sessions.id').onDelete('CASCADE'); | ||
var profileUrl = null; | ||
var full_name = event.user.id; | ||
var full_name = '#' + Math.random().toString().substr(2); | ||
@@ -312,4 +327,4 @@ if (event.platform === 'facebook') { | ||
user_image_url: profileUrl, | ||
last_event_on: (0, _moment2.default)().format('x'), | ||
last_heard_on: (0, _moment2.default)().format('x'), | ||
last_event_on: (0, _botpress.DatabaseHelpers)(knex).date.now().sql, | ||
last_heard_on: (0, _botpress.DatabaseHelpers)(knex).date.now().sql, | ||
paused: 0, | ||
@@ -351,3 +366,3 @@ full_name: full_name, | ||
var message = { | ||
ts: (0, _moment2.default)().format('x'), | ||
ts: (0, _botpress.DatabaseHelpers)(knex).date.now().sql, | ||
session_id: sessionId, | ||
@@ -360,9 +375,9 @@ type: event.type, | ||
var update = { last_event_on: (0, _moment2.default)().format('x') }; | ||
var update = { last_event_on: (0, _botpress.DatabaseHelpers)(knex).date.now() }; | ||
if (direction === 'in') { | ||
update.last_heard_on = (0, _moment2.default)().format('x'); | ||
update.last_heard_on = (0, _botpress.DatabaseHelpers)(knex).date.now(); | ||
} | ||
return knex('hitl_messages').insert(message).then(function () { | ||
return knex('hitl_messages').insert(_lodash2.default.cloneDeep(message)).then(function () { | ||
return knex('hitl_sessions').where({ id: sessionId }).update(update).then(function () { | ||
@@ -394,12 +409,12 @@ return message; | ||
if (onlyPaused === true) { | ||
condition = 'where hitl_sessions.paused = 1'; | ||
condition = 'hitl_sessions.paused = ' + (0, _botpress.DatabaseHelpers)(knex).bool.true(); | ||
} | ||
return knex('hitl_sessions').select(knex.raw('count(*) as count')).then(function (results) { | ||
return knex.raw('\n select hitl_sessions.*, count(*) as count, hitl_messages.type, hitl_messages.text, hitl_messages.direction\n from hitl_messages\n join hitl_sessions on hitl_sessions.id = hitl_messages.session_id\n ' + condition + '\n group by hitl_sessions.id\n order by hitl_messages.id desc\n limit 100').then(function (sessions) { | ||
return { | ||
total: results[0].count, | ||
sessions: sessions | ||
}; | ||
}); | ||
return knex.select('*').from(function () { | ||
this.select([knex.raw('max(id) as mId'), 'session_id', knex.raw('count(*) as count')]).from('hitl_messages').groupBy('session_id').as('q1'); | ||
}).join('hitl_messages', knex.raw('q1.mId'), 'hitl_messages.id').join('hitl_sessions', knex.raw('q1.session_id'), 'hitl_sessions.id').whereRaw(condition).orderBy('hitl_sessions.last_event_on', 'desc').limit(100).then(function (results) { | ||
return { | ||
total: 0, | ||
sessions: results | ||
}; | ||
}); | ||
@@ -410,3 +425,3 @@ } | ||
return knex('hitl_sessions').where({ 'session_id': sessionId }).join('hitl_messages', 'hitl_messages.session_id', 'hitl_sessions.id').orderBy('hitl_messages.id', 'desc').limit(100).select('*').then(function (messages) { | ||
return _lodash2.default.orderBy(messages, ['ts'], ['asc']); | ||
return _lodash2.default.orderBy(messages, ['id'], ['asc']); | ||
}); | ||
@@ -451,3 +466,3 @@ } | ||
module.exports = require("path"); | ||
module.exports = require("botpress"); | ||
@@ -458,2 +473,8 @@ /***/ }, | ||
module.exports = require("path"); | ||
/***/ }, | ||
/* 8 */ | ||
/***/ function(module, exports) { | ||
module.exports = require("fs"); | ||
@@ -460,0 +481,0 @@ |
{ | ||
"name": "botpress-hitl", | ||
"version": "0.0.1", | ||
"version": "1.0.0", | ||
"description": "Official HITL (Human In The Loop) module for Botpress", | ||
@@ -5,0 +5,0 @@ "main": "bin/node.bundle.js", |
@@ -5,6 +5,4 @@ # botpress-hitl | ||
## Contribution | ||
**Support connectors: ** [botpress-messenger](https://github.com/botpress/botpress-messenger) | ||
Botpress Team would really appreciate to have some help from the community to work on this important module. By helping us, you will contribute to the core and by the way, you will become one of our **Botpress Leaders**! | ||
## Installation | ||
@@ -15,11 +13,92 @@ | ||
```js | ||
botpress install hitl // Not publish yet on NPM | ||
botpress install hitl | ||
``` | ||
The HITL module should now be available in your bot UI, and the APIs exposed. | ||
## Features | ||
### Viewing conversations | ||
By using this module, you can look to all your conversations at the same place. You don't have to use external connectors interface to follow your conversations. | ||
<img src='/assets/hitl-screenshot.png' height='300px'> | ||
### Filtering by status | ||
You can filter conversations based on their status (paused/active) by using filtering button in the UI. | ||
### Pausing/resuming conversations | ||
You can pause or resume any conversations from the UI. | ||
## API | ||
### `POST /api/botpress-hitl/sessions/{$id}/pause` | ||
Pause a specific conversation by using his `id`. | ||
### `POST /api/botpress-hitl/sessions/{$id}/unpause` | ||
Resume a conversation for a specific user. | ||
## Example | ||
A basic implementation example that shows how easy it is to implement a help request in Messenger. | ||
```js | ||
const _ = require('lodash') | ||
module.exports = function(bp) { | ||
bp.middlewares.load() | ||
bp.hear(/HITL_START/, (event, next) => { | ||
bp.messenger.sendTemplate(event.user.id, { | ||
template_type: 'button', | ||
text: 'Bot paused, a human will get in touch very soon.', | ||
buttons: [{ | ||
type: 'postback', | ||
title: 'Cancel request', | ||
payload: 'HITL_STOP' | ||
}] | ||
}) | ||
bp.notifications.send({ | ||
message: event.user.first_name + ' wants to talk to a human', | ||
level: 'info', | ||
url: '/modules/botpress-hitl' | ||
}) | ||
bp.hitl.pause(event.platform, event.user.id) | ||
}) | ||
bp.hear(/HITL_STOP/, (event, next) => { | ||
bp.messenger.sendText(event.user.id, 'Human in the loop disabled. Bot resumed.') | ||
bp.hitl.unpause(event.platform, event.user.id) | ||
}) | ||
bp.hear({ type: 'message', text: /.+/i }, (event, next) => { | ||
bp.messenger.sendText(event.user.id, 'You said: ' + event.text) | ||
}) | ||
} | ||
``` | ||
**Note**: This is the only code you need to add to your bot in your `index.js` file. | ||
## Roadmap | ||
- Add pause bot in the UI | ||
- Implement other types of message to view them in UI (template, buttons, etc.) | ||
## Contribution | ||
Botpress Team would really like to have some help from the community to work on this important module. By helping us, you will contribute to the core and by the way, you will become one of our **Botpress Leaders**! | ||
## Community | ||
There's a [public chatroom](https://gitter.im/botpress/core) where you are welcome to join and ask any question and even help others. | ||
There's a [Slack community](https://slack.botpress.io) where you are welcome to join us, ask any question and even help others. | ||
Get an invite and join us now! 👉[https://slack.botpress.io](https://slack.botpress.io) | ||
## License | ||
botpress-hitl is licensed under AGPLv3. |
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is not supported yet
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
No v1
QualityPackage is not semver >=1. This means it is not stable and does not support ^ ranges.
Found 1 instance in 1 package
4713387
9
45481
2
103