繁体   English   中英

如何使用 discord.js 进行简单的全局冷却

[英]how to do a simple global cooldown using discord.js

所以我有一个新的 discord 机器人并且对编程很陌生,就像我有点理解但不能自己做一样。 但关于这个问题。 机器人都在 .js 中(我确实有 config.json),但我还没有让事件处理程序工作。 但我的代码是。

client.on("message", (message) => {
    if (message.author.bot) return;
 
    if (message.content.includes ("John")) {
      message.channel.send ("Oh yeah, that guy...");
    }
}

如何获得全局冷却时间? 我想要冷却时间,所以如果发生关于 John 的会议,机器人不会回复每条消息。

最简单的做法是在侦听器之外创建一个带有时间戳的变量,并将当前时间戳与 scope 之外的一组进行比较,就像这样

var lastReply = 0;
client.on("message", (message) => {
    if (Date.now() - lastReply < 10000) return; // don't respond within 10 seconds
    lastReply = Date.now();
    if (message.author.bot) return;
 
    if (message.content.includes ("John")) {
      message.channel.send ("Oh yeah, that guy...");
    }
}

我已将其设置为 10 秒,但您当然可以从配置中获取它,或者自己更改它。 为了清楚起见(易于阅读),您还可以设置这样的值(例如,5 分钟): lastReply < 5 * 60 * 1000

var cooldown = false;
client.on("message", (message) => {
      if (message.author.bot) return;

      if (message.content.includes("John")) {
        if (cooldown == true) {

          //Bot is on a cooldown
          return;

        } else {
          message.channel.send("Oh yeah, that guy...");

          cooldown = true;
          setTimeout(() => {
            cooldown = false
          }, 60000); //Timeout for a minute
        }
      }
    }

discord 自己编程有点新,但这与我使用的类似。

暂无
暂无

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

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