首页 > 解决方案 > Discord.js Bot 仅在特定时间响应消息或命令

问题描述

如果是东部时区上午 9:30 到下午 4:00之间的工作日,如何将检查日期应用于此消息,以便 discord.js 机器人不会响应“nio down ” ?(股市时间)

请原谅我的代码。我是一个完全的菜鸟,并试图通过它的经验和执行来学习。我倾向于通过例子来学习,而不是通过书籍来学习和阅读。一旦我对这一切有了更好的了解,我就会缩小范围并通读书籍,以微调或纠正我的一些坏习惯,如果这是有道理的话。

  if (message.content.toLowerCase().includes("nio down")) {
    message.channel.startTyping();
    setTimeout(() => message.channel.send("y’all got duped. nio CEO on the run now"), 56500);
    setTimeout(() => message.channel.send("pookie made more money hustling"), 69500);
    message.channel.stopTyping(true);
  } else

标签: javascriptdiscorddiscord.js

解决方案


您可以使用Date对象。访问createdTimestamp消息的属性使用getDay()方法检查是否是工作日:

const { createdTimestamp } = message;
const date = new Date(createdTimestamp);
const day = date.getDay();

// The getDay() method returns the day of the week for the specified date according to local time, where 0 represents Sunday
if (day > 0 && day < 6) {
  console.log("weekday");
  const UTCHours = date.getUTCHours();
  const ESTHours = UTCHours - 5.0;

  if (ESTHours == 9) {
    const minutes = date.getUTCMinutes();

    if (minutes < 30) {
      console.log("Not in time", ESTHours, minutes);
    }
  } else if (ESTHours > 10 || ESTHours < 16) {
    console.log("In time", ESTHours);
  } else {
    console.log("Not in time", ESTHours);
  }
} else {
  console.log("No weekday");
}

东部时区检查更复杂。Native Date 对象只知道两个时区,UTC 和用户的区域设置时区(但是您可以提取的有关区域设置时区的信息量是有限的)。您可以在 UTC 中工作并从消息对象中减去/添加必要的小时数。

或者您查看更适合处理此类问题的日期库之一,例如LuxonDay.js。

编辑

您可以通过getUTCHours方法获取 UTC 时间。然后减去时间差,检查时间是否在9:30 - 16:00的范围内。


推荐阅读