简体   繁体   English

Node.js 随机数生成器?

[英]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 .这是一个Twitch.tv聊天机器人,当有人类型的!random ,它将与之间的随机数回复1 - 100 I've tried var p1 = Math.floor(Math.random() * 100);我试过var p1 = Math.floor(Math.random() * 100); but i'm not sure how to integrate that into the code below in the client.say("");但我不确定如何将其集成到client.say("");中的以下代码中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);

client.say() the random number after you converted it to a string: client.say()转换为字符串后的随机数:

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.请注意Math.floor(Math.random() * 100)将生成一个介于 0 和 99 之间的随机数,而不是介于 1 和 100 之间。

You may want to add one to the result:您可能希望在结果中添加一个:

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

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:如果消息可以包含其他内容,并且它可以包含不止一次出现的!random (比如"Howdy! Here is a random number !random. Here is another !random." ),然后使用这个:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM