Automatically deliver a message regularly at set intervals on Discord across all groups and guilds

Currently, I am developing an event-bot to use in multiple Discord groups. Here is the code snippet I have been working on:

if (command === "init")
  {
    message.channel.send("BunnBot starting...");
    var interval = setInterval (function () {
      message.channel.send("123");
 }, 30 * 1000);
  }

The issue I'm facing is that this command only works within one group, requiring me to use the init command separately in each group. How can I modify my code to make the Bot send messages to every group?

Edit: I made some changes to the code as follows:

client.on("ready", () => {
console.log('Logged in as BunnyBot');
setInterval (function () {
    client.guilds.forEach(() => { 
        let defaultChannel = "";
        client.guilds.forEach((channel) => {
            if(channel.type == "text" && defaultChannel == "") {
           if(channel.permissionsFor(guild.me).has("SEND_MESSAGES")) {
               defaultChannel = channel;
           }
            }
        })
        message.defaultChannel.send("Message here"); 
        console.log("Sending Messages");
   })
}, 1 * 1000);
})

However, I encountered a problem where I received an error stating that send is not a function.

Answer №1

Let's set aside the issue with the #general-channel for now and focus on achieving guild posting using the following method:

Update:

const Discord = require("discord.js");
const bot = new Discord.Client();
bot.on("ready", () => {
    bot.guilds.forEach((guild) => { //loop through each guild where the bot is present
         let defaultChannel = "";
         guild.channels.forEach((channel) => {
               if(channel.type == "text" && defaultChannel == "") {
               if(channel.permissionsFor(guild.me).has("SEND_MESSAGES")) {
                   defaultChannel = channel;
               }
               }
         })
         setInterval (function () {
              defaultChannel.send("Message here") //send the message to a channel where the bot has permission to send messages
         }, 30 * 1000);
   })
})

This code snippet will broadcast the specified message at regular intervals to all guilds that your bot belongs to, although it may not target the exact desired channel.

Answer №2

If you are working with node.js version 12.x, there are some changes that may affect your code. To ensure everything runs smoothly, consider making the following adjustments:

  bot.guilds.cache.forEach((guild) => { //loop through each guild where the bot is present
    let defaultChannel = "";
    guild.channels.cache.forEach((channel) => {
          if(channel.type == "text" && defaultChannel == "") {
          if(channel.permissionsFor(guild.me).has("SEND_MESSAGES")) {
              defaultChannel = channel;
            }
          }
    })
    setInterval (function () {
         defaultChannel.send("Message here") //send a message to a channel where the bot has permission to send
    }, 5000);})

Answer №3

This is a straightforward approach, perhaps not the most optimal, but it gets the job done.

while(true) {
    channel = client.channels.cache.get('channel-id');
    channel.send("message you want to send")
    sleep.sleep(seconds);
}

To use this code, make sure to install the npm package called sleep:

npm install sleep

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

The progress bar in Next JS 13 seems to be malfunctioning and is not displaying any

After transitioning to the new Next JS 13 app directory, I encountered an issue where the progress bar at the top does not function when the page loads. In the previous version, Next JS 12, there was a package named nprogress and nextNprogress that simpli ...

Having trouble with JavaScript/JQuery not functioning properly in HTML content loaded using the load() method

My goal is to load an input form from a separate file called new_machine.php into my index.php. This form includes an input with a dropdown that retrieves options from a MySQL database and displays them as anchors. The issue arises when I attempt to manipu ...

How can you create a personalized sorting order using odata?

Within my AngularApp, I retrieve data from a WebAPI using OData queries. All the retrieved results contain both a date and an integer status code. The status codes range from 1 to 4. I am aiming to organize my results in such a way that all items with a ...

The error message appeared as "ENOTDIR npm install"

I'm encountering an issue while attempting to install discord.js on my Ubuntu server using the following command: npm install discord.js The error message I received is as follows: npm ERR! Linux 4.15.0 npm ERR! argv "/usr/bin/node" "/ ...

Utilizing JavaScript to iterate through objects retrieved via Ajax calls

Recently, I've been diving into the world of Javascript and delving deep into AJAX. Utilizing Vanilla JS along with simple AJAX, my current task involves fetching a user object from a URL based on the user's input ID. Despite attempting to use .d ...

Express app issues error: JSON response not returned properly - Uncaught SyntaxError: Unexpected end of data

I'm in need of some fresh perspective. My goal is to have a basic Express app return JSON data (in this case, a Firebase token) every time a request is made to it. Here's the code for my Express server: app.get('/validate', function ...

I am trying to move to a different page, but for some reason the router.navigate function is not functioning within the subscribe

//I am attempting to redirect to another page once the subscribe method is executed, however I am encountering issues with the router.navigate function within the subscribe method. //In an effort to address this issue, I have attempted to store the data r ...

Accessing a factory's functions within itself in Angular

I'm really trying to understand how all of this operates. It seems like it should be working as intended. I have an Auth factory that, when the jwt token expires, calls its 'delegate' method which obtains a new token using the refresh token. ...

What is the reason for my algorithm's inability to work with this specific number?

I'm currently working on creating an algorithm to compute the sum of prime numbers that are less than or equal to a specified number. Below is my attempt: function calculatePrimeSum(num) { // initialize an array with numbers up to the given num let ...

Dynamic Visibility Control of GridPanel Header in ExtJS

I have a GridPanel that needs to display a limited number of resources. If there are more resources available than what is currently shown, I would like the panel's header/title to indicate this by displaying text such as "more items available - displ ...

Issues with Bootstrap's hamburger menu not functioning properly when clicked

Can't seem to get my hamburger button working. I've followed the bootstrap documentation and ensured that Bootstrap and jQuery are in the correct order, but still no luck. Any suggestions on what could be causing this issue? Are my links misplace ...

Changing the icon on click in react: a step-by-step guide

I have two MUI icons that I need to toggle with every click. I created a component for them, and one of the props (called btnClicked) controls the state. However, when clicking on the component, the icon buttons do not change. Here is the code: import Reac ...

What steps do I need to take to ensure that when running npm start, Chrome opens in incognito mode or that caching is

During my development process, I have encountered frustrating issues related to caching that are difficult to debug. I am looking for a way to disable caching in order to alleviate this problem. One approach I am considering is modifying the default beha ...

I must pause for a specified period before initializing the subsequent component in React Native

Due to restrictions on my API key, I can only make one request every 5 seconds. Therefore, I need to wait for 5 seconds before making another request for NearbyJobs (with the first request being made for PopularJobs). <ScrollView showsVerticalScrollIndi ...

ng-grid defines different cellClass based on the value of the field

I am currently using the ng-grid and I want the column to display in a different color based on different values. I have tried, but not succeeded so far... $scope.gridOptions = { ........ columnDefs: [ { field: "status", displayName: "St ...

Web pages that dynamically update without the need for reloading

Recently, I stumbled upon slack.com and was immediately captivated by its user interface. For those unfamiliar with it, navigating the site is quite simple: There's a sidebar on the left and a main content area on the right. When you click on an item ...

Having trouble importing a package into my React boilerplate

Having trouble importing the react-image-crop package with yarn and integrating it into a react boilerplate. Encountered an error after installing the package: Module parse failed: /Users/...../frontend/node_modules/react-image-crop/lib/ReactCrop.js Unex ...

Ways to fix the issue of an unspecified user error in authjs

Having trouble with creating a web token using passport LocalStrategy and passport-jwt. I keep getting a user undefined error in auth.js ****401 Unauthorized**** (if (!user) { return res.json(401, { error: 'message' });}). How can I fix this issu ...

When switching between classes, it is not possible to apply a different value to the same CSS property

I am currently working on a project that involves toggling a class on a ul tag with an id of sideNav using JavaScript. In this scenario, I have set the left attribute of the id to 0, while the same attribute in the class has a value of -100%. After sever ...

The function you are trying to use is not a valid jQuery function

Although I've come across this issue in previous posts, none of the solutions worked for me and it's really frustrating. I'm a newbie to javascript and I'm sure the answer is probably simple. I'm attempting to incorporate the rapt ...