This is my first try with Bot Framework (Nodejs). I want to test delayed messages, for example, my bot must answer after a 5 seconds after receiving the message. So I tried with this code:
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");
}
});
But this doesn't work. Callback function inside setTimeout fires, but all operations with session doesn't work at all.
So, I find possible solution here: How to send message later in bot framework and rewrite my code:
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");
}
});
This code works, but looks terrible with so many checks. So I have a few questions:
- Why first code example doesn't work? I guess problem in the session lifetime and then what is session lifetime?
- How to set session.userData in this examples? So In first code example I want to set it inside callback function inside setTimeout but it doesn't work too.
- What is the best way to create delayed answers?