user7509866
user7509866

Reputation:

Node.js random number generator?

This is for a Twitch.tv chat bot when someone types !random, it would reply with a random number between 1-100. I've tried var p1 = Math.floor(Math.random() * 100); but i'm not sure how to integrate that into the code below in the client.say(""); section. Cheers to anyone that can help me with this.

client.on('chat', function(channel, user, message, self) {
      if (message === "!random" && canSendMessage) {
        canSendMessage = false;
        client.say("");
        setTimeout(function() {
          canSendMessage = true
        }, 2000);

Upvotes: 3

Views: 11679

Answers (2)

ibrahim mahrir
ibrahim mahrir

Reputation: 31692

If the message could contain other things and if it can contain more than just one occurence of !random (like "Howdy! Here is a random number !random. Here is another !random."), then use this:

client.on('chat', function(channel, user, message, self) {
    if (canSendMessage) { // don't check if message is equal to '!random'
        canSendMessage = false;

        message = message.replace(/!random/g, function() {
            return Math.floor(Math.random() * 100)) + 1;
        });

        client.say(message);

        setTimeout(function() {
            canSendMessage = true
        }, 2000);
    }
});

Upvotes: 1

TimoStaudinger
TimoStaudinger

Reputation: 42460

client.say() the random number after you converted it to a string:

var rand = Math.floor(Math.random() * 100);
client.say(rand.toString());

Note that Math.floor(Math.random() * 100) will generate a random number between 0 and 99, not between 1 and 100.

You may want to add one to the result:

var rand = Math.floor(Math.random() * 100) + 1;

Upvotes: 3

Related Questions