【问题标题】:Discord.js interval messageDiscord.js 间隔消息
【发布时间】:2022-02-07 20:11:46
【问题描述】:

有没有办法根据指定的消息内容停止间隔?还是让用户在开始新的间隔之前先停止间隔?

这是开始间隔的代码:

const ms = require('ms')

let interval;
function isNumeric(str) {
    return !isNaN(str) && !isNaN(parseFloat(str));
}
module.exports = {
    name: 'interval',
    aliases: ['int'],
    run: async (client, message, args) => {
        let time = args[0];
        if(!time) return message.reply('Please enter the duration of message interval!').then(msg => {
    setTimeout(() => {
  msg.delete()
}, 5000)    
  })
  .catch()

  let reason = args.slice(1).join(' ');
  if(!reason) return message.reply('Please enter a message!').then(msg => {
    setTimeout(() => {
  msg.delete()
}, 5000)
  })
  .catch()

        interval = setInterval(function() {
            message.channel.send(reason)
            .catch(console.error);
        }, ms(time));
    },
    stopInterval() {
        if(interval) {
            clearInterval(interval);
        }
    }
}

指定的消息内容将是

let reason = args.slice(1).join(' ');

关于停止区间的代码:

const stopInt = require('./interval');

module.exports = {
    name: 'stopinterval',
    aliases: 'stopint',
    run: async (client, message, args) => {
        message.channel.send("Message reminder has been stopped.");
        stopInt.stopInterval();
    }
}

我还有一个问题,如果我使用间隔两次,我只能停止我创建的最后一个间隔而无法停止第一个。

【问题讨论】:

    标签: javascript node.js discord.js


    【解决方案1】:

    您可以使用Set 或数组来跟踪间隔列表:

    const ms = require("ms");
    
    const intervals = new Set()
    function isNumeric(str) {
      return !isNaN(str) && !isNaN(parseFloat(str));
    }
    
    module.exports = {
      name: "interval",
      aliases: ["int"],
      run: async (client, message, args) => {
        let time = args[0];
        if (!time)
          return message
            .reply("Please enter the duration of message interval!")
            .then((msg) => {
              setTimeout(() => {
                msg.delete();
              }, 5000);
            })
            .catch();
    
        let reason = args.slice(1).join(" ");
        if (!reason)
          return message
            .reply("Please enter a message!")
            .then((msg) => {
              setTimeout(() => {
                msg.delete();
              }, 5000);
            })
            .catch();
    
        intervals.add(setInterval(function () {
          message.channel.send(reason).catch(console.error);
        }, ms(time)));
      },
      stopInterval() {
        for (const interval of intervals) {
          intervals.delete(interval);
          clearInterval(interval);
        }
      },
    };
    
    

    (我冒昧地使用 prettier 格式化您的代码)

    与您的问题无关,但我注意到:

    • 你把async / await.then / .catch 混在一起了
    • 应删除空的.catch() 调用

    【讨论】:

      猜你喜欢
      • 2017-10-17
      • 2021-05-12
      • 2020-08-24
      • 2020-07-02
      • 1970-01-01
      • 2013-03-16
      • 1970-01-01
      • 2017-09-06
      相关资源
      最近更新 更多