如何发送两条消息(第二条延迟消息,妙语)



我正在尝试在js中创建一个笑话机器人,它在延迟后发送妙语。

这是我正在使用的代码。它只向我发送妙语自动取款机。 我已经删除了一些代码,因为它对这个问题是重复的。

var delayInMilliseconds = 1500;
function poolJoke() {
const rand = Math.floor(Math.random() * 7) + 1;
if (rand === 1) {
bot.postMessageToChannel(
'bots',
'What does bread loaves say when they greet each other?',
setTimeout(function() {
bot.postMessageToChannel('bots',
'Gluten tag.')
}, delayInMilliseconds),
params
);
} 
}

嗨,您需要添加一个局部变量和清理时间,请尝试此代码

function poolJoke(val) {
var timer;
const rand = val;
if (rand == 1) {
window.clearTimeout(timer);
console.log('What does bread loaves say when they greet each other?');
timer = setTimeout(function () {
console.log('bots', 'Gluten tag.' + timer)
}, 5000);
} 
}

试试我测试过的这个解决方案,工作正常:

bot.on("start", function() {
bot.postMessageToChannel(channel, "Hello world!");
console.log("Hello world!");
setTimeout(() => {
bot.postMessageToChannel(channel,'after 5000 ms.')
}, 5000)
});

最新更新