【发布时间】:2025-12-12 01:30:01
【问题描述】:
这是我第一次尝试使用 Bot Framework (Nodejs)。我想测试延迟消息,例如,我的机器人必须在收到消息后 5 秒后回复。 所以我尝试了这段代码:
var builder = require('botbuilder');
var connector = new builder.consoleconnector().listen();
var bot = new builder.universalbot(connector);
bot.dialog('/', function (session) {
if (!session.userData.TimeoutStarted) {
session.send("I'll answer in 5 seconds");
session.userData.TimeoutStarted = true;
setTimeout(function() {
session.send("Answer after 5 seconds");
session.userData.TimeoutStarted = false;
}, 5000);
} else {
session.send("Bot is busy");
}
});
但这不起作用。 setTimeout 内的回调函数触发,但所有与 session 的操作根本不起作用。
所以,我在这里找到了可能的解决方案:How to send message later in bot framework 并重写我的代码:
var builder = require('botbuilder');
var connector = new builder.ConsoleConnector().listen();
var bot = new builder.UniversalBot(connector);
bot.dialog('/', function (session) {
if (session.userData.Timeout > 0 && Date.now() - session.userData.Timeout > 5000)
session.userData.Timeout = 0;
if (!session.userData.Timeout) {
session.send("I'll answer in 5 seconds");
var reply = session.message;
setTimeout(function() {
reply.text = "Answer after 5 seconds";
bot.send(reply);
}, 5000);
session.userData.Timeout = Date.now();
} else {
session.send("Bot is busy");
}
});
这段代码可以工作,但是有这么多检查看起来很糟糕。所以我有几个问题:
- 为什么第一个代码示例不起作用?我猜是会话生命周期的问题,那么什么是会话生命周期?
- 在这个例子中如何设置 session.userData?所以在第一个代码示例中,我想在 setTimeout 内的回调函数中设置它,但它也不起作用。
- 创建延迟答案的最佳方法是什么?
【问题讨论】:
标签: botframework