John Doe
John Doe

Reputation: 41

Generate a random string every time

I want to generate a different string each time it sends the message. This works but the string doesn't change.

var crypto = require('crypto');

function randomValueHex (len) {
return crypto.randomBytes(Math.ceil(len/2))
    .toString('hex')
    .slice(0,len).toUpperCase(); 
}

var string = randomValueHex(4)+"-"+randomValueHex(4)+"-"+randomValueHex(4);

bot.on('message', function(user, userID, channelID, message, event) {
if (message === "!test") {
  var interval = setInterval (function (){
    bot.sendMessage({
      to: channelID,
      message: string
    });
  }, 1000);
}
});

Upvotes: 2

Views: 254

Answers (1)

user3151675
user3151675

Reputation: 58029

You should move the string variable into the function. That way it will be different each time the function runs.

bot.on('message', function(user, userID, channelID, message, event) {
if (message === "!test") {
  const interval = setInterval (function (){
    const string = randomValueHex(4)+"-"+randomValueHex(4)+"-"+randomValueHex(4);
    bot.sendMessage({
      to: channelID,
      message: string
    });
  }, 1000);
}
});

Upvotes: 3

Related Questions