我在this example之后使用Node.js上的swagger和directline开发聊天机器人: (https://github.com/Microsoft/BotBuilder-Samples/tree/master/Node/core-DirectLineWebSockets)
每次我向机器人发送消息时,我都会收到多个已发送消息的响应。
示例:
消息已发送1
回应1
消息发送2
回应2
回应2
消息已发送3
回应3
回应3
回应3
用例类似于this question,但是使用websocket。
(DirectLineJS receiving copies of Bot replies)
发送消息:
// send message to bot
function sendMessages(client, conversationId, utterance) {
logger.debug("*** SEND A MESSAGE ");
client.Conversations.Conversations_PostActivity(
{
conversationId: conversationId,
activity: {
textFormat: config.activity.textFrormat,
text: utterance,
type: config.activity.type,
from: {
id: callSid
}
}
}).catch(function (err) {
logger.error('Error sending message:', err.statusText);
callback(null,err);
});
}
接收活动:
function startReceivingWebSocketClient(streamUrl, conversationId) {
logger.debug('Starting WebSocket Client for message streaming on conversationId: ' + conversationId+ ' , watermark: '+waterMark);
var ws = new (webSocket.client)();
ws.on('connectFailed', function (error) {
logger.debug('Connect Error: ' + error.toString() );
});
ws.on('close', function(){
logger.debug('Connect Close: ' + error.toString());
});
ws.on('connect', function (connection) {
logger.debug('WebSocket Client Connected');
connection.on('error', function (error) {
logger.debug("Connection Error: " + error.toString());
});
connection.on('close', function () {
logger.debug('WebSocket Client Disconnected');
});
connection.on('message', function (message) {
// Occasionally, the Direct Line service sends an empty message as a liveness ping
// Ignore these messages
if (message.type === 'utf8' && message.utf8Data.length > 0) {
var responseMessage = JSON.parse(message.utf8Data);
if(responseMessage.watermark > waterMark)
{
logger.debug("responseMessage.watermark > waterMark "+responseMessage.watermark +">"+ waterMark);
var activities = responseMessage.activities;
activities = activities.filter(function (m) { return m.from.id == config.directLine.from.id });
activities = activities.filter(function (m) { return m.conversation.id == conversationId });
if(activities.length>0)
{
waterMark = responseMessage.watermark;
logger.debug("************** attività: "+JSON.stringify(responseMessage));
sendResponse(activities);
}
}
}
});
});
ws.connect(streamUrl);
}