2017-02-03 112 views
1

这是针对Twitch.tv聊天机器人,当有人输入!random时,它会回复一个在1 - 100之间的随机数字。我试过var p1 = Math.floor(Math.random() * 100);,但我不确定如何将它集成到client.say("");部分中的以下代码中。欢迎任何能够帮助我的人。Node.js随机数发生器?

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

只是传递'p1'到'client.say'代替' “”'。例如:'client.say(p1)'。 –

+0

当我这样做时,它给了我这个错误。 /Users/Billy/node_modules/tmi.js/lib/utils.js:64 \t \t return channel.charAt(0)===“#”? channel.toLowerCase():“#”+ channel.toLowerCase(); – Billy

+0

看起来您需要先将其转换为字符串。 'p1.toString()'。 –

回答

0

client.say()随机数后,将它转换为字符串:

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

注意Math.floor(Math.random() * 100)会产生0到99之间的随机数,而不是和100

之间1

您可能想要添加一个结果:

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

或乘以101. –

+0

@ibrahimmahrir更改我的答案。我的原始答案和你的建议是不正确的,因为'Math.random()'给出了一个0到1之间的一个随机数,包含0,一个排他。 Math.ceil(0 * 100)和Math.floor(0 * 101)都等于零,小于1。 – Timo

+0

'Math.random'永远不会是'1'。我和我自己一样,但事实并非如此。 –

0

如果消息可以包含其他的东西,如果它可以包含比只是一个occurence多个!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); 
    } 
});