来自西班牙的下午好,我正在尝试在客户端和实际的bot之间设置一个中间的nodejs服务器,但是当我尝试与我的bot建立套接字连接时,它表示握手协议失败。
现在我的代码是
服务器app.js
require('dotenv').config();
const express = require('express');
const path = require('path');
const logger = require('morgan');
const cookieParser = require('cookie-parser');
const bodyParser = require('body-parser');
const session = require("express-session");
const SequelizeStore = require('connect-session-sequelize')(session.Store);
const Sequelize = require('sequelize');
const sequelize = new Sequelize(process.env.DBNAME, process.env.DBUSER, process.env.DBPASSWORD, {
dialect: 'mysql'
});
const sequelizeStoreSession = new SequelizeStore({ db: sequelize })
const app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'hbs');
// default value for title local
app.locals.title = 'Human Data Demo';
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
// SESSION PERSISTANCE USING COOKIES
sequelizeStoreSession.sync();
// Enable authentication using session + passport
app.use(session({
secret: 'secret',
resave: true,
saveUninitialized: true,
cookie: {
httpOnly: true,
maxAge: 2419200000
},
store: sequelizeStoreSession
}))
require('./passport/index')(app);
const index = require('./routes/index');
app.use('/', index);
// catch 404 and forward to error handler
app.use((req, res, next) => {
const err = new Error('Not Found');
err.status = 404;
next(err);
});
module.exports = app;
我用于将服务器连接到机器人的路由文件
router.post('/messages/', (req, res, next) => {
const client = new WebSocketClient();
console.log('cliente: ', client);
client.on('connectFailed', err => {
console.log(err);
next(err);
})
client.on('connect', connection => {
console.log('connected');
connection.on('error', function (error) {
console.log("Connection Error: " + error.toString());
});
connection.on('close', function () {
console.log('echo-protocol Connection Closed');
});
connection.on('message', function (message) {
if (message.type === 'utf8') {
console.log("Received: '" + message.utf8Data + "'");
}
});
connection.send(req.body.text);
})
client.connect('http://55dce78c.ngrok.io/api/messages', 'echo-protocol')
console.log('connectado ', client)
})
真正的机器人
var restify = require('restify');
var builder = require('botbuilder');
var http = require('http');
var server = restify.createServer();
server.listen(process.env.port || process.env.PORT || 3978, function () {
console.log('listening to %s', server.name, server.url);
});
const connector = new builder.ChatConnector({
appId: process.env.MICROSOFT_APP_ID,
appPassword: process.env.MICROSOFT_APP_PASSWORD
});
const bot = new builder.UniversalBot(connector);
server.post('/api/messages', connector.listen());
bot.dialog('/', function (session, args) {
session.send('Hello World');
});
能给我一些建议吗?
编辑:这是我现在遇到的错误
POST /api/project/messages - - ms - - Error: Server responded with a non-101 status: 502 Bad Gateway Response Headers Follow: cache-control: no-cache connection: close content-type: text/html at WebSocketClient.failHandshake (C:\Users\David\Desktop\HumanData\Proyecto Acceso API\API_FINAL\node_modules\websocket\lib\WebSocketClient.js:326:32) at ClientRequest.<anonymous> (C:\Users\David\Desktop\HumanData\Proyecto Acceso API\API_FINAL\node_modules\websocket\lib\WebSocketClient.js:265:18) at emitOne (events.js:116:13) at ClientRequest.emit (events.js:211:7) at HTTPParser.parserOnIncomingClient [as onIncoming] (_http_client.js:543:21) at HTTPParser.parserOnHeadersComplete (_http_common.js:112:17) at Socket.socketOnData (_http_client.js:440:20) at emitOne (events.js:116:13) at Socket.emit (events.js:211:7) at addChunk (_stream_readable.js:263:12) at readableAddChunk (_stream_readable.js:250:11) at Socket.Readable.push (_stream_readable.js:208:10) at TCP.onread (net.js:597:20)
答案 0 :(得分:1)
您的WebSocket请求失败,因为客户端期望WebSocket Handshake Response
。 /api/messages
端点不是用于启动WebSocket连接,而是用于向机器人发送消息,因此它为您提供了Bad Gateway
且握手协议失败。
如果您不想通过WebSocket连接到机器人,则需要使用DirectLine API
进行以下操作:
生成访问令牌:
POST /v3/directline/tokens/generate
与机器人进行对话:POST /v3/directline/conversations
这为您提供了一个带有conversationId
和streamUrl
的对话对象,所有机器人响应都将来自其中,您可以像这样使用它:
const WebSocket = require('ws');
const ws = new WebSocket(streamUrl);
ws.on('message', function incoming(data) {
// this is a bot response
console.log(data);
});
如果对话已经开始并且您已经有一个conversationId
,则可以为reconnecting to conversations设置端点。
如果您想手工完成所有这些工作,那还是不错的,但是我建议您使用DirectLine JS
,这样会让您更轻松。