Repeat a command in Discord.js indefinitely

Looking for help with this discord.js code I have. Currently, when someone runs the command "!cat", it sends a random image from r/cats. Here is the snippet:

var Discord = require('discord.js');
var bot = new Discord.Client()
randomPuppy = require('random-puppy') 

bot.on('ready', function() {
    console.log(bot.user.username);
});

bot.on('message', async message => {
    if (message.content === "!cat") { 
            const img = await randomPuppy('cats')
            message.channel.send(img);
         
    }
});

My goal is to have it send this every 20 minutes instead of waiting for a user's input. I've tried a few methods but they don't seem to work in an asynchronous manner. Any help would be greatly appreciated!

Answer №1

Consider implementing setInterval() in this way:

setInterval(async function(){
     client.channels.cache.get(channelID).send("Custom message")
}, 1200000)

This will execute the specified code every 20 minutes. It is recommended to include this within the client.once("ready") section. Keep in mind that you can only send messages to a specific channel without accessing the message content.

Below is the complete functioning example:

const Discord = require("discord.js");
const client = new Discord.Client();
randomPuppy = require("random-puppy");

//Insert your channelID here, obtained by enabling Developer mode
channelID = "channelID";

prefix = "!";

//Triggered when bot is ready
client.once('ready', ()=>{
    console.log("Bot is Active!");

    //The core logic using setInterval to run the designated function at set intervals
    setInterval(async function(){

        //Code to be executed
        const img = await randomPuppy('cats');
        client.channels.cache.get(channelID).send(img);
        
    }, 1200000);

    console.log("This should print");
});

//Irrelevant message event handler
client.on("message", async message => {
    if(!message.content.startsWith(prefix) || message.author.bot) return;

    const args = message.content.slice(prefix.length).split(/ +/);
    const command = args.shift().toLowerCase();

    if(command === "test"){
        message.channel.send("Despite your best efforts, I am still alive...");    
    }
});

client.login('BOT_TOKEN_HERE');

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

retrieve the data-initial-value's value through JavaScript

Hello, I am currently attempting to retrieve the text from this input field but all I'm getting is an empty value. <input type="text" class="quantumWizTextinputPaperinputInput exportInput" jsname="YPqjbf" autocomplete= ...

JQuery does not have the ability to compare the current date and

I've encountered an issue while comparing two date scripts that resulted in incorrect output. Here is the code that I used: var current = new Date(); var date = new Date($(this).val()); alert(current) == "Sat Aug 23 2014 14:42:00 GMT+0700 (ICT)" aler ...

Is there a way to disable auto rotation on a website when accessed from a mobile phone?

My current solution involves the following code: @media (max-height: 480px) and (min-width: 480px) and (max-width: 600px) { html{ -webkit-transform: rotate(-90deg); -moz-transform: rotate(-90deg); -ms-transform: rotate(- ...

Using jQuery to send a GET request to the current page with specified parameters

Within my application, hosted on a PHP page, I am aiming to trigger a GET request upon selecting an option from a dropdown menu. The URL of the page is: www.mydomain.it/admin/gest-prenotazioni-piazzola.php I intend to utilize jQuery to execute this GET r ...

Transferring information using "this.$router.push" in Vue.js

I'm currently developing a restaurant review project using Django REST and Vue.js. To ensure uniqueness, I have adopted Google Place ID as the primary key for my restaurants. The project also incorporates Google Place Autocomplete functionality. The ...

Resources for Vue.js stylesheets

Vue.js is my latest discovery and I have been experimenting with the single file component architecture. A small issue I encountered was that all of my components' styles were being loaded on the page, even if they weren't currently active. Is t ...

Including additional data to a page after each iteration in order to display the current progress

I am currently working on a loop that iterates through the lines of a text area and processes each line sequentially. However, I am facing an issue where the page becomes unresponsive until all the data has been processed. Is there a way to dynamically u ...

Modal's ng-click not triggering component's function

I am currently working on resolving an issue. My choice to use AngularJS is intentional, as I prefer not to load the entire NPM of Angular. Additionally, we heavily rely on Razor Syntax for the Web Layer. Implementation in Create.cshtml file <button ...

Installing Eclipse for PHP and JavaScript on your computer is a simple process. Here

Currently, I am working on a web project that consists mostly of PHP and JavaScript files, as well as some HTML and CSS files. I have decided to use Eclipse as my Integrated Development Environment (IDE) for this project. However, upon visiting eclipse.org ...

Unveiling Parameters from a Function Transferred as an Argument to Another Function in JavaScript

I'm just getting started with JavaScript and I've encountered a small program where a function takes another function as an argument. My goal is to figure out how to extract or access the arguments of that passed in function. Here's a specif ...

Leveraging async/await in tandem with a for loop and mongodb

My goal is to send an order confirmation email using nodemailer to customers once they have completed their purchase. I also want to include some data from the purchased products in this email. I have tried various combinations of async/await but have not ...

Tips for including subjects in JSON data

I am trying to include the subject in JSON data so that I can fetch it using $.each(data.subject). Below is my API code where I am retrieving all the data encoded in JSON format. Any assistance would be greatly appreciated. [{"id":"79","FirstName":"Elon", ...

Prevent clicking through slides on React by disabling the Swiper feature

Is there a way to handle the global document click event (using React hook useClickAway) so that it still fires even when clicking on a slide? For example, think of a circle in the header like an avatar dropdown - when you click on it, a menu pops up. Th ...

Generate an array using hyperlinks within a list item created by the user

In the process of developing a program, I have included a feature where users can drag and drop .wav files into a playlist-container. These files are then played in the order they are arranged within the playlist-container. Currently, I am working on imple ...

I am looking to initiate the animation by triggering the keyframe upon clicking a button

Is there a way to create an animation triggered by a button click instead of loading the page? Each table data cell has its own class with a unique keyframe defining the style changes over time. @-webkit-keyframes fadeIn { from { opacity:0; ...

Is there a way to extract the MIME type from a base64 string?

My base64 String appears as "UklGRkAdEQBXQVZFZm10IBIAAAABAAEAg...". I am attempting to download this file using my browser. Therefore, I convert it to a blob with the following function: b65toBlob: function(b64Data, sliceSize = 512) { ...

A stationary webpage nested within a lively pathway on NuxtJS

I have a Nuxt app with a list of cars available at: /cars. You can select a specific car at /cars/:id. I would like to have a toolbar that routes to different views such as: /cars/:id/routes, /cars/:id/drivers, etc. Within the /cars/:id page, I have creat ...

Learn the process of transferring information through ajax while managing dependent drop-down menus

I have successfully set the initial value from the first combo-box and now I am looking to send the second variable from the second combo-box and receive it in the same PHP file. Below is the Ajax code snippet: $(document).ready(function(){ $(".rutas") ...

steps to adjust screen zoom back to default after automatic zoom in forms

I'm not very well-versed in javascript/jquery and have been on an extensive search for a solution to my specific problem. While I've come across some close answers, I am struggling to adapt them to fit my own scenario. On my website, I have a fo ...

Enhanced JavaScript Autocompletion in Integrated Development Environments

What is the inner workings of Intellisense in IDEs like Webstorm and Eclipse for JavaScript? From which source do the suggestions originate? Is it possible to tweak the code to enhance the accuracy of the suggestions? https://i.sstatic.net/ZVBB3.png ...