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

Converting an array into a string, transitioning from PHP to JavaScript

Hey everyone, I'm currently working on passing an array to a JavaScript file and encountering this error: An exception has been thrown during the rendering of a template ("Notice: Array to string conversion"). What I need is: data: ['2017/7&a ...

Tips for displaying identical tab content across various tabs using jquery or javascript

For instance, if we have tabs labeled as 1, 2, 3, 4, and 5, and a user has selected tabs 2, 3, and 4, how can we display the same content for those tabs while showing different content for the remaining ones? ...

Using Fabric.js to manage image controls situated beneath another overlay image

I'm currently working on a canvas user interface using jquery and the fabric.js library. I managed to add an overlay png image with transparency by implementing the code below: var bgImgSrc = bgImg.attr('src'); canvas.setOverlayImage(bgImgS ...

casperjs is encountering difficulty locating the id even after setting it

Issue with CasperJS not locating the ID after setting it Casper.then(function () { screenLog(); var id = String("_newid_"); var arrow = this.evaluate(function () { var arrows = document.querySelectorAll('span.select2-selection__a ...

What could be the reason for the child element not occupying the full height of its parent container?

* { padding: 0; margin: 0; box-sizing: border-box; } body { margin: 50px; } .navbar { display: flex; align-items: center; justify-content: center; color: darkgreen; font-family: 'Vollkorn', serif; font-size: 1.2rem; font-w ...

Adding choices to dropdown menu in AngularJS

As a beginner in AngularJs, I am struggling with appending options to select boxes created by javascript. Below is the code snippet that is causing the issue. var inputElements = $('<div><label style="float:left;">' + i + '</ ...

Retrieving an HTML page from one location and automatically populating textboxes with preexisting values on the receiving end

I'm currently facing a dilemma. Here's the issue: I need to load an HTML page (let's call it test.html) when a button is clicked on another page (referred to as home page). The test.html page has input boxes that I want to populate with p ...

Utilizing Async.each fails to trigger the ultimate callback function

Here's the scenario: I expect the function finalCallBack to be triggered after we finish looping through all elements. var rows = [ { name: 'first'}, { name: 'second'} ]; var execForEachRow = function(row, callback){ var ...

Have you considered retrieving POST parameters using Ajax POST in jQuery?

Below is the code snippet: $.ajax({ type: "POST", url: "http://localhost:3000/rcm/global_config/update", data: {k: 'sdfa', v: 'dsfas'}, success: function(data, textStatus, XMLHttpRequest){ alert("Data ...

Retrieve the heading from a pop-up box

This jQuery tooltip allows for popups from another HTML page to be created. UPDATE: I have provided an example HERE The issue arises when trying to retrieve the title from the popup. Currently, using document.title displays the title of the current page ...

Convert the PHP datetime and timezone function to a JavaScript function

I have a helpful function in my solution that I'd like to share: public static function formatTime($time, $timezone) { $timezone = new \DateTimeZone($timezone); $time = $time->setTimezone($timezone); return \Locale::getDefaul ...

Arranging Check Boxes Side by Side

I am struggling to properly align the three checkboxes and tables next to each other. I have managed to get the checkboxes on the same row, but aligning them neatly has proven to be a challenge. Using Notepad++ as my development tool, I am facing formattin ...

Plot data points from geojson onto a leaflet map using markers

How can I efficiently import geoJson data (containing over 2000 coordinates) into a leaflet map? Below is a brief snippet of geo json: { "type": "FeatureCollection", "features": [ { "type": "Feature", "geometry": { ...

Unlock the mystery of identifying which trace is selected in the plot.ly JS legend

When using plot.ly, it is possible to set up a listener for legend click events. I am wondering how to determine which trace in the legend was clicked on. To provide a more specific example, let's say there are two traces (trace0, trace1) in a line gr ...

Unexpected error: JSON data at line 1 column 1 of the JSON data is incomplete

I've encountered an issue with my script related to a JSON response error. Below is the code snippet in question: $(document).ready(function() { $('#btndouble').click(function(){ var address = $('#btcaddress').val(); ...

Disabling vertical scrollbar in textarea within Bootstrap modal using CSS, jQuery, and C# in .NET MVC framework

I am passing data to the Bootstrap modal using jQuery from my database. The form values can change from a single row to multiple rows. I do not want a scrollbar, but instead I want the textarea element to automatically adjust its height to fit the content. ...

Incorporate this form created externally onto my website

I have been working on my website and I am looking to incorporate a form that opens up once the login button is clicked. This form was generated using an online form builder which provides an embed code for seamless integration onto websites. Below, you wi ...

Having trouble launching the Socket.io Chat Demo? Encounter an issue with the error message at ..//

Hello, I am a novice in the world of programming and recently attempted to run the socket.io chat demo. Unfortunately, I encountered an error message at line 5 stating that it cannot find ('../..'). Can someone please shed some light on why this ...

Unable to establish cookie via frontend React application

I am currently working with a backend node server that offers two APIs, one to set cookies and another to get cookies. Here is the backend code for setting and retrieving cookies: Server : localhost:4001 router.get("/addCartToCookie", function( ...

Does AngularJS have a similar function to $(document).ajaxSuccess()?

When working with AngularJS, I am looking to implement a universal ajax loader that does not require integration into each controller to function. In jQuery, this can be achieved through the following code: (function globalAjaxLoader($){ "use strict"; ...