Newbie needs help: How to make Discord bot send automatic messages?

Hey everyone! I’m totally new to coding and I’m trying to figure out how to make a Discord bot send messages automatically in a specific channel. Can anyone help me out? I’m using DiscordJS and this is what I’ve got so far:

const Discord = require('discord.js');
const bot = new Discord.Client();

bot.once('ready', () => {
  console.log('CherryBot is ready to roll!');
});

const express = require('express');
const server = express();
const serverId = '123456789012345678';
const roomId = '987654321098765432';
const autoMessage = 'Time to party!';

bot.login('your_bot_token_here');

I’m not sure what to do next. How can I make the bot send the message automatically? Any tips or pointers would be awesome. Thanks a bunch!

yo alexr1990, i’ve got a simple trick for ya. try using setTimeout() function. it’s easy peasy:

bot.once(‘ready’, () => {
console.log(‘CherryBot is ready to roll!’);
setTimeout(function() {
const channel = bot.channels.cache.get(roomId);
channel.send(autoMessage);
}, 5000); // sends after 5 seconds
});

this sends the message once. for repeated messages, wrap it in a function and call it again. hope this helps!

I’ve been in your shoes, and here’s what worked for me. Instead of using node-schedule, I found setInterval() to be simpler for beginners. After your bot.once(‘ready’) event, add this:

bot.once(‘ready’, () => {
console.log(‘CherryBot is ready to roll!’);
setInterval(() => {
const channel = bot.channels.cache.get(roomId);
if (channel) {
channel.send(autoMessage);
}
}, 3600000); // 3600000 ms = 1 hour
});

This will send your message every hour. You can adjust the interval as needed. Just remember to keep your bot running continuously, either on your local machine or by hosting it on a service like Heroku or Replit. Good luck with your bot!

To make your Discord bot send automatic messages, you’ll need to set up a scheduled task. One way to do this is by using the ‘node-schedule’ package. First, install it with npm. Then, in your code, require it and create a job that runs at specified intervals. Here’s an example:

const schedule = require('node-schedule');

const job = schedule.scheduleJob('0 * * * *', function() {
  const channel = bot.channels.cache.get(roomId);
  if (channel) {
    channel.send(autoMessage);
  }
});

This will send your message every hour. Adjust the cron string (‘0 * * * *’) to change the frequency. Remember to handle potential errors, like the bot not having permissions to send messages in the channel. Also, make sure your bot stays connected by adding error handling and reconnection logic to your main bot code.