javascript - 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
解决方案
您可以使用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 中工作并从消息对象中减去/添加必要的小时数。
或者您查看更适合处理此类问题的日期库之一,例如Luxon或Day.js。
编辑
您可以通过getUTCHours方法获取 UTC 时间。然后减去时间差,检查时间是否在9:30 - 16:00的范围内。
推荐阅读
- php - Wordpress - 使用 Ajax 分页按最高帖子浏览量列出的顶级作者列表
- openshift - 在 OpenShift 中以声明方式挂载服务帐户密钥
- php - 标注在 stdClass 中创建的字段?
- python-3.x - spark-shell 抛出异常
- angular - 如何在地图中为主题观察者调用异常?
- ocaml - 如何强制 OCaml 内联函数?
- java - 在 onActivityResult 之后设置 TextView 文本
- php - WooCommerce:自定义产品维度输出
- python - PyCharm 2018.3.3 的 Flask 运行配置中的红色 X 是什么意思?
- r - 合并数据框列集