How to schedule Discord bot to automatically post messages at 12:00 AM daily using JavaScript

I need help setting up my Discord bot to automatically send messages from an array exactly at midnight every day. Right now I only know how to use delays but that’s not what I want. I want the bot to trigger a function precisely at 00:00 CET time.

I have an array with different messages that the bot should broadcast when midnight hits. Can someone guide me on the right approach for this?

Here’s the current function I use for storing the data that needs to be sent:

if (cmd === 'event'){
  const userInput = msg.content.toLowerCase();
  if(validLocations.includes(userInput.slice(config.prefix.length+cmd.length+1)) === true) {
    scheduledAnnouncements.push(userInput.slice(config.prefix.length+cmd.length+1));
  } else return msg.channel.send("Location doesn't exist, please verify the name");
}

Here’s another solid approach - just use native JavaScript Date with setInterval to check every minute. I’ve run this for months without any problems. Calculate milliseconds until next midnight, then setTimeout for the first run and setInterval for the rest.

function schedulemidnight() {
  const now = new Date();
  const midnight = new Date();
  midnight.setHours(24, 0, 0, 0); // Next midnight
  
  const msUntilMidnight = midnight.getTime() - now.getTime();
  
  setTimeout(() => {
    sendMessages();
    setInterval(sendMessages, 24 * 60 * 60 * 1000); // Every 24 hours
  }, msUntilMidnight);
}

function sendMessages() {
  scheduledAnnouncements.forEach(msg => {
    channel.send(msg);
  });
}

For CET timezone, use toLocaleString('en-US', {timeZone: 'Europe/Berlin'}) to get the right local time. No external dependencies needed and you get full control over timing logic.

Just use moment-timezone with setInterval - way easier than doing the math yourself. Check moment.tz('Europe/Berlin').format('HH:mm') === '00:00' every 30 seconds. I’ve been doing this for years and it’s bulletproof.

Use node-cron for this - it’s way better than delays or intervals for scheduling. Just run npm install node-cron and set up a cron job that fires at midnight CET. The cron expression ‘0 0 * * *’ runs daily at midnight. Since you need CET, specify that timezone in your options. Here’s what I did: const cron = require(‘node-cron’); cron.schedule(‘0 0 * * *’, () => { // Your midnight function here sendScheduledMessages(); }, { timezone: “Europe/Berlin” // CET timezone }); function sendScheduledMessages() { scheduledAnnouncements.forEach(announcement => { // Send each message from your array channel.send(announcement); }); } This beats setTimeout or setInterval because it handles server restarts and daylight saving changes automatically. The cron job keeps running as long as your bot’s up.

This topic was automatically closed 4 days after the last reply. New replies are no longer allowed.