Search code examples
javascriptbotsdelay

How to send two messages (second message with delay, punchline)


I'm trying to create a jokebot in js that sends a punchline after a delay.

Here's the code that I'm working with. It only sends me the punchline atm. I've cut some code out as it's repetetive for the issue.

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
    );
  } 
}

Solution

  • Hi you need to add a local variable and clean time, try this code

    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);
        } 
    }
    

    Try this solution i tested and work fine:

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