I'm very very new to programming and I'm trying to set up a basic discord bot that sends a video every Friday. Currently I have:
Index.js which contains:
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);
and a commands folder which contains beeame.js and that contains:
module.exports = {
name: "beeame",
description: "b",
execute: (message) => {
message.channel.send("It's Friday!", { files: ["./beeame.mp4"] });
}
}
I have heard about cron jobs and intervals but I'm not sure how to add these to the code I currently have.
Any help would be super appreciated!
Nate,
Here's some basics, to get you started. Your existing project you showed, sets up your bot to handle messages whenever they arrive. Everything there stays as is. You want to add a new section to deal with the timers.
First, here's a snippet of a utility file having to deal with 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();
the thing to study and pay attention to is the ' * * * ' area. You will want to understand this, to set the timing correctly.
so replace the console logging with your messages, set your timing correctly and you should be good to go. The other thing to remember is that wherever your bot is running, the time zone might be different than where you (or others are)...so you might need to adjust for that if you have specific time of day needs.
Edit: Based on subsequent questions....and note, I didn't set the time right. you need to really do more research to understand it.
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();