创建控制器时可以设置内置快速服务器的主机名:
var controller = Botkit.facebookbot({
hostname: 'YOUR_HOST_NAME',
verify_token: '',
access_token: ''
})
controller.setupWebserver
并且controller.createWebhookEndpoints
是 botkit 中的辅助函数,用于执行它们所描述的操作,分别创建一个 express webserver 和 webhook 端点。
要实现您自己的网络服务器,您只需为 botkit 控制器设置一个 webhook 端点,以接收消息 POST 数据并执行身份验证握手。
按照 botkit 约定/{platform}/receive
,对于 facebook 来说是这样,/facebook/receive
但你可以使用任何你喜欢的东西。
要将自定义 express 服务器与 Botkit 一起使用,首先创建一个基本的 Web 服务器。
// components/express_webserver.js
var express = require('express');
var bodyParser = require('body-parser');
var querystring = require('querystring');
var debug = require('debug')('botkit:webserver');
module.exports = function(controller, bot) {
var webserver = express();
webserver.use(bodyParser.json());
webserver.use(bodyParser.urlencoded({ extended: true }));
webserver.use(express.static('public'));
// You can pass in whatever hostname you want as the second argument
// of the express listen function, it defaults to 0.0.0.0 aka localhost
webserver.listen(process.env.PORT || 3000, null, function() {
console.log('Express webserver configured and listening at ',
process.env.HOSTNAME || 'http://localhost/' + ':' + process.env.PORT || 3000);
});
// Register our routes, in this case we're just using one route
// for all incoming requests from FB
// We are passing in the webserver we created, and the botkit
// controller into our routes file so we can extend both of them
require('./routes/incoming-webhook')(webserver, controller)
controller.webserver = webserver;
return webserver;
}
接下来,您需要为 webhook 端点创建路由,我们在一个单独的文件中执行此操作,这与 express 很常见
// components/routes/webhook.js
module.exports = function(webserver, controller) {
// Receive post data from fb, this will be the messages you receive
webserver.post('/facebook/receive', function(req, res) {
// respond to FB that the webhook has been received.
res.status(200);
res.send('ok');
var bot = controller.spawn({});
// Now, pass the webhook into be processed
controller.handleWebhookPayload(req, res, bot);
});
// Perform the FB webhook verification handshake with your verify token
webserver.get('/facebook/receive', function(req, res) {
if (req.query['hub.mode'] == 'subscribe') {
if (req.query['hub.verify_token'] == controller.config.verify_token) {
res.send(req.query['hub.challenge']);
} else {
res.send('OK');
}
}
});
}
创建这两个文件后,您将使用 require 并将控制器传递给 express 模块。您的主要 bot 文件应如下所示
// bot.js
var Botkit = require('botkit');
// Create the Botkit controller, which controls all instances of the bot.
var controller = Botkit.facebookbot({
debug: true,
verify_token: process.env.verify_token,
access_token: process.env.page_token,
});
// Set up an Express-powered webserver to expose oauth and webhook endpoints
// We are passing the controller object into our express server module
// so we can extend it and process incoming message payloads
var webserver = require(__dirname + '/components/express_webserver.js')(controller);