javascript - 如何安排来自 Discord 机器人的消息在每个星期五发送?
问题描述
我对编程非常陌生,我正在尝试设置一个基本的不和谐机器人,每周五发送一个视频。目前我有:
Index.js 包含:
const Discord = require("discord.js");
const fs = require("fs");
require("dotenv").config()
const token = process.env.token;
const { prefix } = require("./config.js");
const client = new Discord.Client();
const commands = {};
// load commands
const commandFiles = fs.readdirSync("./commands").filter(file => file.endsWith(".js"));
for (const file of commandFiles) {
const command = require(`./commands/${file}`);
commands[command.name] = command;
}
// login bot
client.on("ready", () => {
console.log(`Logged in as ${client.user.tag}`);
});
client.on("message", message => {
if(!message.content.startsWith(prefix) || message.author.bot) return;
const args = message.content.slice(prefix.length).trim().split(/ +/);
const command = args.shift().toLowerCase();
let cmd = commands[command];
if(cmd)
cmd.execute(message, args)
});
client.login(token);
和一个包含 beeame.js 的命令文件夹,其中包含:
module.exports = {
name: "beeame",
description: "b",
execute: (message) => {
message.channel.send("It's Friday!", { files: ["./beeame.mp4"] });
}
}
我听说过 cron 作业和间隔,但我不确定如何将这些添加到我目前拥有的代码中。
任何帮助将不胜感激!
解决方案
内特,
这里有一些基础知识,可以帮助您入门。您展示的现有项目将您的机器人设置为在消息到达时处理它们。那里的一切都保持原样。您想添加一个新部分来处理计时器。
首先,这是一个必须处理 Cron Jobs 的实用程序文件的片段:
const CronJob = require('cron').CronJob;
const job = new CronJob('* * * * *', function() {
const d = new Date();
console.log('At each 1 Minute:', d);
});
job.start();
学习和注意的是' * * * '区域。您需要了解这一点,才能正确设置时间。
所以用你的消息替换控制台日志,正确设置你的时间,你应该很高兴。要记住的另一件事是,无论您的机器人在哪里运行,时区都可能与您(或其他人)所在的位置不同……因此,如果您有特定的时间需求,您可能需要对此进行调整。
编辑:根据后续问题....请注意,我没有设置正确的时间。你需要做更多的研究才能理解它。
const cron = require('cron').CronJob;
const sendMessageWeekly = new cron('* * * * *', async function() {
const guild = client.guilds.cache.get(server_id_number);
if (guild) {
const ch = guild.channels.cache.get(channel_id_number);
await ch.send({ content: 'This is friendly reminder it is Friday somewhere' })
.catch(err => {
console.error(err);
});
}
});
sendMessageWeekly.start();
推荐阅读
- android - Android Alert dialog is dismissing on Back press?
- php - PHP not working in HTML
- javascript - 第二行无法在 php 中更新
- ios - 将 Facebook 的提要列表与图形 api 集成时的问题
- javascript - 分组 Object3D 几何中顶点的世界位置
- php - 不显示我的 json
- sql - 在同一表中的另一列中设置 DateTime 中的时间
- antd - setFieldsValue 与 getFieldDecorator 自定义元素结构在 getFieldDecorator
- java - 使用 Gradle 构建时出错:原因:error=2,没有这样的文件或目录
- ios - 如何在 swift 中从 api 生成模型