【问题标题】:Making Discord bot do things automatically on a daily routine让 Discord 机器人在日常生活中自动做事
【发布时间】:2020-04-22 15:31:35
【问题描述】:

我是 java 脚本和 discord 编程的新手,我希望我的 discord 服务器上的机器人在早上 5 点进行频道清除。 但是,我想在专用服务器上运行它,但不知道如何正确设置时间触发机制。 会

if (date.getHours()==5){
   //do stuff
}

工作?

【问题讨论】:

    标签: javascript discord discord.js


    【解决方案1】:

    您可以使用client.setInterval() 来设置定时功能。

    例如:client.setInterval(() => purgeChannel(), 300000); 将每 5 分钟运行一次函数 purgeChannel(300000 是以毫秒为单位的 5 分钟)。

    【讨论】:

    【解决方案2】:

    我能看到你这样做的最简单的方法是一个对象,每个动作都保存到一个时间。我选择使用<HOUR><MINUTE> 来存储每个值。所以下午 4:12 的时间是:1612。然后 setInterval 每分钟运行一次并检查它是否需要执行新操作。

    function hello() {
      console.log('Hello');
    }
    let actions = {
      "0630": function() {
        console.log('Its 6:30');
      },
      "1200": hello, //NOON
      "1400": hello, //2:00 PM
      "0000": function() {
        console.log('New Day / Midnight');
      },
    };
    let codeStartTime = new Date();
    
    function checkActions() {
      let date = new Date();
      let action = actions[`${date.getHours() >= 10 ? "" : "0"}${date.getHours()}${date.getMinutes() >= 9 ? "" : "0"}${date.getMinutes()}`];
      if (typeof action === "function") action(); //If an action exists for this time, run it.
    }
    setTimeout(function() {
      checkActions();
      setInterval(checkActions, 60000); //Run the function every minute. Can increase/decrease this number
    }, ((60 - codeStartTime.getSeconds()) * 1000) - codeStartTime.getMilliseconds()); // Start the interval at the EXACT time it starts at a new minute
    
    
    /** CODE for the Stack Overflow Snippet **/
    console.log(`Starting first interval in ${((60 - codeStartTime.getSeconds()))} seconds.`);
    console.log(`Adding in StackOverflow function, set to run at: ${codeStartTime.getHours() >= 10 ? "" : "0"}${codeStartTime.getHours()}${codeStartTime.getMinutes() >= 9 ? "" : "0"}${codeStartTime.getMinutes() + 1}`);
    actions[`${codeStartTime.getHours() >= 10 ? "" : "0"}${codeStartTime.getHours()}${codeStartTime.getMinutes() >= 9 ? "" : "0"}${codeStartTime.getMinutes() + 1}`] = function() {
      console.log('Ran the StackOverflow Function');
    };

    如果您愿意,您可以在 actions 对象中等待我的任何示例时间,以证明它有效。但是 StackOverflow 代码只是在 actions 对象中为您的当前时间 +1 分钟添加了一个示例时间,只是为了更容易看到它的运行情况。

    setInterval 在这里只是为了简单起见,但如果它会运行一整天,则不建议这样做。 Reason Why为了获得更准确的时间,我建议将setInterval 替换为setTimeout,并在每次运行时重新定义setTimeout

    【讨论】:

      猜你喜欢
      • 2021-04-15
      • 2021-09-09
      • 2021-01-08
      • 2021-10-24
      • 1970-01-01
      • 2021-03-14
      • 1970-01-01
      • 2020-07-29
      • 2021-04-30
      相关资源
      最近更新 更多