首页 > 解决方案 > 如何安排来自 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 作业和间隔,但我不确定如何将这些添加到我目前拥有的代码中。

任何帮助将不胜感激!

标签: javascriptnode.jsdiscord.js

解决方案


内特,

这里有一些基础知识,可以帮助您入门。您展示的现有项目将您的机器人设置为在消息到达时处理它们。那里的一切都保持原样。您想添加一个新部分来处理计时器。

首先,这是一个必须处理 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();

推荐阅读