Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

BootBot for existent express instances #195

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 25 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ BootBot is a simple but powerful JavaScript Framework to build Facebook Messenge
$ npm install bootbot --save
```

### Without express
```javascript
'use strict';
const BootBot = require('bootbot');
Expand All @@ -44,6 +45,30 @@ bot.on('message', (payload, chat) => {
bot.start();
```

### With an existent express instance
```javascript
'use strict';
const BootBot = require('bootbot');
const express = require('express');
const app = express();

const bot = new BootBot({
accessToken: 'FB_ACCESS_TOKEN',
verifyToken: 'FB_VERIFY_TOKEN',
appSecret: 'FB_APP_SECRET'
});

bot.on('message', (payload, chat) => {
const text = payload.message.text;
chat.say(`Echo: ${text}`);
});

app.use(bot.middleware());
app.listen(3000, ()=>{
console.log('listen on port 3000');
});
```

## Video Example

Creating a Giphy Chat Bot in 3 minutes:
Expand Down
21 changes: 21 additions & 0 deletions examples/echo-express-example.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
const BootBot = require('../');
const express = require('express');
const app = express();
const config = require('config');

const bot = new BootBot({
accessToken: config.get('access_token'),
verifyToken: config.get('verify_token'),
appSecret: config.get('app_secret')
});

bot.on('message', (payload, chat) => {
const text = payload.message.text;
chat.say(`Echo: ${text}`);
});

app.use(bot.middleware());

app.listen(3000, () => {
console.log(`Listen on port 3000`);
});
57 changes: 44 additions & 13 deletions lib/BootBot.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ const Chat = require('./Chat');
const Conversation = require('./Conversation');
const EventEmitter = require('eventemitter3');
const express = require('express');
const bodyParser = require('body-parser');
const crypto = require('crypto');
const fetch = require('node-fetch');
const normalizeString = require('./utils/normalize-string');
Expand All @@ -20,7 +19,7 @@ class BootBot extends EventEmitter {
* @param {Boolean} [options.broadcastEchoes=false]
* @param {String} [options.graphApiVersion=v2.12]
*/
constructor(options) {
constructor (options) {
super();
if (!options || (options && (!options.accessToken || !options.verifyToken || !options.appSecret))) {
throw new Error('You need to specify an accessToken, verifyToken and appSecret');
Expand All @@ -30,10 +29,8 @@ class BootBot extends EventEmitter {
this.appSecret = options.appSecret;
this.broadcastEchoes = options.broadcastEchoes || false;
this.graphApiVersion = options.graphApiVersion || 'v2.12';
this.app = express();
this.webhook = options.webhook || '/webhook';
this.webhook = this.webhook.charAt(0) !== '/' ? `/${this.webhook}` : this.webhook;
this.app.use(this.webhook, bodyParser.json({ verify: this._verifyRequestSignature.bind(this) }));
this._hearMap = [];
this._conversations = [];
}
Expand All @@ -43,6 +40,8 @@ class BootBot extends EventEmitter {
* @param {Number} [port=3000]
*/
start(port) {
this.app = express();
this.app.use(this.webhook, express.json({ verify: this._verifyRequestSignature.bind(this) }));
this._initWebhook();
this.app.set('port', port || 3000);
this.server = this.app.listen(this.app.get('port'), () => {
Expand All @@ -59,6 +58,38 @@ class BootBot extends EventEmitter {
this.server.close();
}

/**
* getting a middleware for existent express instance
*/
middleware() {
const router = express.Router();
router.use(express.json({ verify: this._verifyRequestSignature.bind(this) }));

router.get(this.webhook, (req, res) => {
if (req.query['hub.mode'] === 'subscribe' && req.query['hub.verify_token'] === this.verifyToken) {
console.log('Validation Succeded.')
res.status(200).send(req.query['hub.challenge']);
} else {
console.error('Failed validation. Make sure the validation tokens match.');
res.sendStatus(403);
}
});

router.post(this.webhook, (req, res) => {
var data = req.body;
if (data.object !== 'page') {
return;
}

this.handleFacebookData(data);

// Must send back a 200 within 20 seconds or the request will time out.
res.sendStatus(200);
}).bind(this);

return router;
}

/**
* See https://developers.facebook.com/docs/messenger-platform/reference/send-api/quick-replies/#quick_reply
* @typedef {Object} QuickReply
Expand Down Expand Up @@ -279,15 +310,15 @@ class BootBot extends EventEmitter {
},
body: JSON.stringify(body)
})
.then(res => res.json())
.then(res => {
if (res.error) {
console.log('Messenger Error received. For more information about error codes, see: https://goo.gl/d76uvB');
console.log(res.error);
}
return res;
})
.catch(err => console.log(`Error sending message: ${err}`));
.then(res => res.json())
.then(res => {
if (res.error) {
console.log('Messenger Error received. For more information about error codes, see: https://goo.gl/d76uvB');
console.log(res.error);
}
return res;
})
.catch(err => console.log(`Error sending message: ${err}`));
}

/**
Expand Down
Loading