Is there a way for me to schedule a daily message to be sent at a designated time each day

I'm looking to automate bot messages for specific times. For example:

const Discord = require("discord.js");
const client = new Discord.Client();
client.on("ready", () => {
  console.log("Bot is Online!");
});
var now = new Date();
var hour = now.getUTCHours();
var minute = now.getUTCMinutes();
client.on("message", (message) => {
  if (hour === 10 && minute === 30) {
    client.channels.get("ChannelID").send("Hello World!");
  }
});

However, it seems to only work when triggered by another command like:

if (message.content.startsWith("!ping")) {
  message.channel.send("pong!");
}
my message: !ping (at 10:10 o'clock)
-> pong!
-> Hello World!

I suppose I need something that continuously checks the time variables.

Answer №1

To automate tasks based on a specific schedule, I recommend using the cron package. This package allows you to set functions to be executed when the date matches a given pattern.
When constructing the pattern, you can use wildcards like * for any value and specify ranges such as 1-3, 7 which includes values 1, 2, 3, 7.

The following are the possible ranges:

  • Seconds: 0-59
  • Minutes: 0-59
  • Hours: 0-23
  • Day of Month: 1-31
  • Months: 0-11 (Jan-Dec)
  • Day of Week: 0-6 (Sun-Sat)

Here's an example implementation:

var cron = require("cron");

function test() {
  console.log("Action executed.");
}

let job1 = new cron.CronJob('01 05 01,13 * * *', test); // executes daily at 01:05:01 and 13:05:01
let job2 = new cron.CronJob('00 00 08-16 * * 1-5', test); // runs Monday to Friday, every hour from 8 am to 16

// Start a job with job.start()
job1.start();
// To pause a job, use job.stop()
job1.stop();

In your scenario, consider the following approach:

const cron = require('cron');

client.on('message', ...); // No changes needed in the message event listener

let scheduledMessage = new cron.CronJob('00 30 10 * * *', () => {
  // Executes daily at 10:30:00, perform desired actions
  let channel = yourGuild.channels.get('id');
  channel.send('Your message');
});

// Start the job using:
scheduledMessage.start()
// Implement commands to pause and resume the job if needed

Answer №2

According to Federico's wisdom, tackling this issue requires following the right approach. However, due to recent updates in discord.js (v12), the syntax has evolved as shown below:

    // Including Discord.js and Cron modules
    const Discord = require('discord.js');
    const cron = require('cron');
            
    // Setting up a new Discord client
    const client = new Discord.Client();
        
    // Executing the code only once when the client is ready
    // To prevent errors if the client isn't fully loaded
    client.once("ready", () => {
      console.log(`Online as ${client.user.tag}`);
        
      let scheduledMessage = new cron.CronJob('00 30 10 * * *', () => {
      // This will run daily at 10:30:00; you can customize it to your needs
      // Targeting the specific guild (server) and channel for sending messages
         const guild = client.guilds.cache.get('id');
         const channel = guild.channels.cache.get('id');
         channel.send('Your message here');
        });
            
        // Begin the scheduled task with:
        scheduledMessage.start()
    };

// Optionally, additional commands can be implemented to pause or resume the job

Kudos to Federico for his invaluable assistance!

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

retrieving the parent of the a tag from a jquery form

When using the jQuery code below: $('#trade-offer form').on("submit", function(event) { event.preventDefault(); var stock = $(this).closest('.allloopedover'); console.log(stock); return; $.ajax({ url: ajaxur ...

Is it possible to execute custom Javascript code when navigating forwards or backwards on a webpage?

My main goal is to recreate the back button functionality using AJAX without needing to add #uglyhashes to every URL, as many solutions currently do. (Just to clarify, I am completely okay with a solution that doesn't support Internet Explorer at all ...

Fixed position is used on elements that should always remain in the exact

I have a fixed menu on my website that is working perfectly fine. I also have a container (not using Bootstrap) that should stay fixed when it reaches the static menu. Everything is functioning as expected, except when I resize the window, the container se ...

What steps should I take to grant API access if cross-browser requests are restricted?

Creating a C# web service to retrieve data from a server raises the question of how to grant API access to other users who want to query it using client-side code. For example, imagine the web service is hosted on Domain1.com. How can someone from Domain2 ...

Issue with vue-router redirection when pushing a route

I have set up my router configuration as follows: const router = new Router({ mode: 'history', routes: [ // root { path: '/', component: ComponentPage, redirect: routePrefix.public, children: [ ...

jQuery is optimized to work specifically with select id tags

Here is the HTML code snippet I've put together, along with my script. While I admit it might look a bit messy, please bear with me as I'm still in the learning phase. If anyone could offer some assistance on this matter, I would be extremely gra ...

Creating a text-filled alphabet design using HTML, CSS, and JavaScript: A step-by-step guide

I have a creative project in mind where I want to design various shapes resembling English alphabets, and each shape should include text. I already have an image file illustrating my idea. My objective is to accomplish this using only html css javascript. ...

What is the reason behind Google Closure Compiler appending a variable to the global namespace when the original namespace was blank?

My long script is neatly enclosed within a (function() {/.../})() to prevent any name pollution. It has been typed with complete accuracy and zero warnings. I recently discovered that Google Closure compiler initially redefines i and j in the global names ...

Broadcasting TypeScript Data Structures via Socket.IO

In my Typescript code, I have created a basic User class as shown below: export class User { constructor(public id: string); } When I emit a message from my socket.io server, I include an instance of the User class like this: var user = new User(&ap ...

After an AJAX request is completed, the event.keyCode is not returning the key codes for the up and

I have a function that uses AJAX to autocomplete a text field. The results are added to a specific div element. I am trying to implement the functionality where users can navigate through the results using the up and down arrow keys. However, I am encoun ...

Refreshing the child component based on the child's action and sending information to the parent in a React application

Within my Parent Component, I am utilizing an Ajax call to populate two children Components. C1 requires the data only once, while C2 has the ability to fetch additional data through subsequent Ajax calls and needs to render accordingly. I find it more co ...

Vue alert - Cannot access indexOf property of a value that is undefined

After browsing through numerous similar issues on StackOverflow, none seem to address the specific problem I encountered... I have been smoothly working on a Vue JS project + Laravel until I suddenly encountered an error that seems unsolvable (even though ...

Is it possible to delete an element from both local storage and HTML by referencing its ID?

Experience a simple flashcard game where you enter a question and answer to create a new flash card stored as an object within the cards array. The newly created flash card is also displayed by appending a new element to the flash cards section on the webp ...

Sending parameters to a personalized Angular directive

I am currently facing a challenge in creating an Angular directive as I am unable to pass the necessary parameters for displaying it. The directive code looks like this: (function () { "use strict"; angular.module("customDirectives", []) .directive ...

Creating a Geometric Shape using Three.js

I'm currently utilizing Three.js to procedurally create a regular N-sided polygon based on a user-input number of sides. The ultimate objective is to use this as the initial phase in displaying a polyhedral prism. To determine the vertices of the N-g ...

Modifying a variable within the return statement in a React Native component

I am relatively new to React and React-native and I am facing challenges in understanding how to update a variable within the return method. Here is my current code snippet: import React, { Component } from "react"; import { View, StyleSheet, Platform, T ...

extracting the ID from within an iframe

Currently, I am developing a script using pure javascript. parent.*nameofiframe*.document.getElementById('error').value; However, when attempting to achieve the same using jQuery, it doesn't seem to work: $('*nameofiframe*', win ...

Check to see if a variable has been assigned a value in the form of a jquery

Scenario: <div> <div class="application-section active"></div> <div class="application-section"></div> </div> I need to define the following variables var $activeSection = $("div.application-section.active") ...

Tips for including a JSON file within the utils directory of a Node.js project

I have a JavaScript file located in the utils folder of my Node.js project. This JS file is responsible for retrieving data from a database. However, at the moment, I only have mock data stored in a local JSON file. Now, I need to figure out how to load th ...

Having difficulty accessing attributes within the template - encountering errors for all attributes except for 'name', stating '[attributename] is not defined'

There seems to be an issue with accessing Object attributes other than 'name' in the template. When trying to access attributes like id or url, errors such as 'id/url/whatever is not defined' are logged in the console. The JSON file pas ...