【问题标题】:Javascript discord bot cooldown not workingJavascript不和谐机器人冷却不起作用
【发布时间】:2020-11-18 00:44:17
【问题描述】:

除了冷却时间外,这个机器人运行良好。如果有人键入命令,它会以随机句子之一响应。我想为机器人添加一个用户冷却时间,所以每个用户都必须等到他们可以再次使用它。问题是,机器人的冷却部分是无用的,它根本不起作用。有人可以帮帮我吗?非常感谢详细的回答。

const Discord = require('discord.js');

const client = new Discord.Client();

const prefix = '!';

const used = new Map();

const talkedRecently = new Set();

client.once('ready', () => {
    console.log('Ready!');
});


  client.on("message", (message) => {
    if (message.content.startsWith("!random") && talkedRecently.has(msg.author.id)) {
    msg.channel.send("Wait 1 minute before getting typing this again. - " + msg.author);}
    else {
        let tomb=["something1","something2", "something3",];
  
  let i = tomb[Math.floor(Math.random()*tomb.length)];
      message.channel.send(i);
    }
            talkedRecently.add(msg.author.id);
        setTimeout(() => {
          // Removes the user from the set after a minute
          talkedRecently.delete(msg.author.id);
        }, 60000);
    )};
 

client.login(process.env.token);

【问题讨论】:

    标签: javascript discord bots


    【解决方案1】:

    我已对您的代码进行了整理并对其进行了修改以使其更易于扩展。我还调整了Discord.js cooldown tutorial,让冷却时间自动添加到每个命令中。

    如果您想让代码变得更好,我强烈建议您通读Discord.js guide

    完整的解释可以在这个答案的底部找到。

    示范操场: discord.gg/2duzjPT.

    演示

    代码

    const Discord = require('discord.js');
    const client = new Discord.Client();
    
    const prefix = '!';
    
    const cooldowns = new Discord.Collection();
    
    client.once('ready', () => {
      console.log('Ready!');
    });
    
    client.on('message', (message) => {
      if (message.author.bot || !message.content.startsWith(prefix)) return;
    
      const [ command, ...args ] = message.content.slice(prefix.length).split(/\s+/g);
    
      if (!cooldowns.has(command)) {
        cooldowns.set(command, new Discord.Collection());
      }
    
      const now = Date.now();
      const timestamps = cooldowns.get(command);
      const cooldownAmount = 1 * 60 * 1000;
    
      if (timestamps.has(message.author.id)) {
        const expirationTime = timestamps.get(message.author.id) + cooldownAmount;
    
        if (now < expirationTime) {
          const timeLeft = (expirationTime - now) / 1000;
          return message.reply(`Please wait ${timeLeft.toFixed(1)} more second(s) before reusing the \`${command}\` command.`);
        }
      }
    
      timestamps.set(message.author.id, now);
      setTimeout(() => timestamps.delete(message.author.id), cooldownAmount);
    
      switch (command) {
        case 'random':
          let tomb = ['something1', 'something2', 'something3'];
      
          let i = tomb[Math.floor(Math.random() * tomb.length)];
          message.channel.send(i);
          break;
        default:
          message.reply(`The command \`${command}\` was not recognized.`);
      }
    });
    
    client.login(process.env.token);
    

    说明

    创建一个集合来存储有冷却时间的命令:

    const cooldowns = new Discord.Collection();
    

    如果消息是由机器人发送的,或者消息不是以前缀 (!) 开头,则消息处理程序退出:

    if (message.author.bot || !message.content.startsWith(prefix)) return;
    

    消息被分成一个命令和参数数组;这是通过删除以 .slice(prefix.length) 开头的前缀,然后在每个空白间隙处使用 .split(/\s+/g) 拆分消息来完成的:

    const [ command, ...args ] = message.content.slice(prefix.length).split(/\s+/g);
    

    如果请求的命令不在冷却集合中,则将其添加并将其值设置为新集合:

    if (!cooldowns.has(command)) {
      cooldowns.set(command, new Discord.Collection());
    }
    

    以毫秒为单位的当前时间放在一个变量中:

    const now = Date.now();
    

    所请求命令的集合被放置在一个变量中;这包含在 1 分钟内使用过请求的命令的所有用户:

    const timestamps = cooldowns.get(command);
    

    默认冷却时间设置为 1 分钟:

    const cooldownAmount = 1 * 60 * 1000;
    

    这会检查用户是否是请求命令集合的一部分;如果是,则计算他们可以再次使用该命令的时间,并检查是否超过了过期时间;如果没有,则计算剩余时间,向用户发送消息并退出消息处理程序:

    if (timestamps.has(message.author.id)) {
      const expirationTime = timestamps.get(message.author.id) + cooldownAmount;
    
      if (now < expirationTime) {
        const timeLeft = (expirationTime - now) / 1000;
        return message.reply(`Please wait ${timeLeft.toFixed(1)} more second(s) before reusing the \`${command}\` command.`);
      }
    }
    

    如果用户在 1 分钟内未使用该命令,则将其用户 ID 添加到集合中,并创建一个计时器以在一分钟后自动从集合中删除其用户 ID:

    timestamps.set(message.author.id, now);
    setTimeout(() => timestamps.delete(message.author.id), cooldownAmount);
    

    最后,机器人会检查用户输入了什么命令并执行某些代码;如果该命令未被识别,则向用户发送一条消息:

    switch (command) {
      case 'random':
        let tomb = ['something1', 'something2', 'something3'];
    
        let i = tomb[Math.floor(Math.random() * tomb.length)];
        message.channel.send(i);
        break;
      default:
        message.reply(`The command \`${command}\` was not recognized.`);
    }
    

    参考文献

    Discord.js (documentation)

    JavaScript (documentation)

    【讨论】:

      【解决方案2】:

      有些细节:

      第一个问题是您对msg 的引用不存在,因此您的第二个条件永远不会通过。 您似乎想要做的是引用参数message,这将包含您需要的数据的对象。

      {
          author: {
              id: 'm5000'
          }
      }
      

      试试下面的

      if (message.content.startsWith("!random") && talkedRecently.has(message.author.id)) {
         ... Your code here
      }
      

      第二期只是一个“Woops”,将来您可以研究 ESLint 以尽早发现这些问题。

      您似乎也错误地使用 )}; 而不是 }); 关闭了 client.on() 方法

      【讨论】:

        猜你喜欢
        • 2021-07-08
        • 1970-01-01
        • 2018-03-20
        • 1970-01-01
        • 2021-09-12
        • 1970-01-01
        • 2021-10-08
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多