【问题标题】:Sending random messages every 1 minute with Discord.js使用 Discord.js 每 1 分钟发送一次随机消息
【发布时间】:2020-02-23 20:23:28
【问题描述】:

我正在尝试使用setInterval() 每分钟发送一次随机消息,但它不起作用。这是我的代码:

var facts = ["1", "2", "3", "4", "5", "6"];
var fact = Math.floor(Math.random() * facts.length);
client.on("ready", () => {
    let channel = client.channels.get("id");
    setInterval(function() {
        channel.send(facts[fact])
    }, 60000)
})

【问题讨论】:

  • “它不起作用”从来都不是解释问题的好方法,即使在运行代码时也很明显 - 所以请解释发生了什么或不希望发生什么。跨度>

标签: javascript node.js discord discord.js


【解决方案1】:

不确定不和谐部分 - 我将假设该部分工作正常。

通过在 setInterval 函数outside 生成随机事实,您将始终得到相同的随机事实。这应该可以解决这个问题:

var facts = ['1', '2', '3', '4', '5', '6']
client.on('ready', () => {
  let channel = client.channels.get('id')
  setInterval(function() {
    var fact = Math.floor(Math.random() * facts.length)
    channel.send(facts[fact])
  }, 60000)
})

一些解释:

在此示例中,您将看到每秒产生一个随机事实。除了随机生成器是在 setInterval 函数之外声明的,你会看到同样的事实。

var facts = ['1', '2', '3', '4', '5', '6']
var fact = Math.floor(Math.random() * facts.length)
setInterval(function() {
  console.log(facts[fact]) // Every second, this will return _the same_ fact.
}, 1000) // Changed to 1s for testing

但是,如果将var fact 声明移动到 setInterval 函数中,则会每秒生成一个随机事实:

var facts = ['1', '2', '3', '4', '5', '6']
setInterval(function() {
  var fact = Math.floor(Math.random() * facts.length)
  console.log(facts[fact]) // Every second, this will return a _new random_ fact
}, 1000) // Changed to 1s for testing

【讨论】:

    猜你喜欢
    • 2017-10-17
    • 1970-01-01
    • 2020-10-15
    • 2021-03-26
    • 2021-10-04
    • 1970-01-01
    • 2020-12-15
    • 1970-01-01
    • 2021-04-19
    相关资源
    最近更新 更多