What is causing the default switch to constantly loop in repetition?

Currently, I am working on a Discord bot using discord.js and utilizing a switch statement. However, I am encountering an issue where the "default:" case keeps repeating itself every time any other case is executed.

I have already investigated for cases without breaks and attempted to switch between double quotation marks and single quotation marks. Can someone please explain why this is happening and suggest a solution?

const wrongResponse = ["1", "2", "3"];
var randomResponse = wrongResponse[Math.floor(Math.random() * wrongResponse.length)];

bot.on("message", message => {
    let args = message.content.substring(calling.length).split(" ");
    switch (args[0]) {
        case 'commands':
            const embed = new Discord.RichEmbed()
                .setDescription("commands here");
            message.channel.send(embed);
            break;

        case 'search':
            message.reply("nothing yet");
            break;

        default:
            message.reply(randomResponse);
            break;
    };
});

Answer №1

The issue with default is that it keeps repeating itself because the code within default continuously triggers the message event by responding with a reply, creating an endless loop. To prevent this, your bot should disregard any message events triggered by its own actions. One way to achieve this is by comparing message.author.id to the bot's id, but a simpler approach is to ignore all messages from bots, which is generally a good practice.

bot.on("message", message => {
    if(message.author.bot) { return; }
    // This message is from a human, take action!
}

Answer №2

When a message is sent to a channel, it triggers the message event as well. If the message does not match any of the specified cases, the bot will respond with a randomResponse. However, since this random response also does not match any case, it creates a loop of repeating actions. To prevent this loop, it is advisable to include a check at the beginning of your event listener to verify if the message was not sent by the bot itself.

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

Why isn't the jQuery click() function functioning on my modified HTML?

I am trying to create a unique version of the go-moku game using different programming languages and databases. My aim is to enhance the game's functionality by incorporating jQuery, PHP, and a MySQL database. var moveCount = -1; setInterval(function ...

purging data from javascript objects

In my Node.js HTTP server, I am using 'connect' to build a web service that currently parses JSON requests into an Object, performs operations, and returns a synchronous response. The JSON data comes from an ecommerce cart and results in an Objec ...

Locating the source of the function call within a file in Node.js

Is it possible to determine the location of a file if a method from a module is called within that file? For example: // my-module.js module.exports = { method: function () { // I would like to know the path to my-app.js here } } // my-other-mod ...

Using v-model in Vue, the first option has been chosen

Is there a way to set a default value for myselect when a user visits the site for the first time? I want the first option to be selected initially, but allow the user to change their choice if they prefer another option. Can this be achieved using v-model ...

Looking for a jQuery Gantt Chart that includes a Treeview, Zoom functionality, and editing capabilities?

I am in need of integrating a dynamic Gantt Chart tool into a room booking solution using jQuery. The Gantt chart should be highly interactive, allowing for drag-and-drop functionality, a tree view on the left to group tasks, and a zoom feature for adjusti ...

Is there a way to remove the old React component when there are two instances of it still active while passing variables?

Recently, I've encountered some unusual behavior with my React component. As a newcomer to React, I have a page where users can configure toast notifications that are displayed. For this functionality, I'm utilizing the react-hot-toast package. U ...

How come I am unable to pass JavaScript values to my PHP5 code?

I'm struggling with this code snippet: <?php $html=file_get_contents('testmaker_html.html'); echo $html; ?> <script type="text/javascript"> document.getElementById('save_finaly_TEST').addEventLis ...

Acquiring an icon of a program using its handle

I am looking for a way to extract a program's icon from its handle, which I acquired using User32.dll with EnumWindow/FindWindow. While I am aware of ExtractAssociatedIcon, it seems to work from a file instead of a handle. My question is how can I con ...

Do I need to utilize getStaticProps along with JSON imports in Next.js?

Is it necessary to use getStaticProps in order to render static data from a JSON or typescript file, or can the data be imported without using getStaticProps? The documentation I read didn't provide a clear answer. projects.tsx const projects: [ { ...

Utilizing jQuery and DOM to interact with form elements

Below is the form content <form method="post"> <input type="hidden" name="resulttype" value="Create"> <table> <tr> <td>Full Name</td> <td><input ...

Tracking tool for monitoring progress of HTTP POST requests

Hi, I am still a beginner when it comes to NodeJS and its modules. I could really use some assistance with creating a progress bar for an application I'm working on. Right now, the progress bar only reaches 100% upon completion and I suspect my piping ...

An arrow function fails to activate

Here is the code snippet that I am dealing with: class App extends React.Component { loginComponent = <button onClick={this.signUp}>Sign Up</button>; signUp = () => { alert("test"); } rende ...

Establishing session management for tasks in Node.js

I'm currently developing a web application using Node JS and encountering an issue with the session store in req. For my sessions to work, I have set up my app.js like this: // Enable sessions app.use(session({ secret: '***********', ...

Customizing Webpack 4's Entry Point

Below is the layout of my project: -node_modules -src -client -js -styles -views -index.js -webpack.config.js -server -.babelrc -package -package-lock -README.md -webpack ...

Encountering net::ERR_CONNECTION_RESET and experiencing issues with fetching data when attempting to send a post request

I am facing a React.js task that involves sending a POST request to the server. I need to trigger this POST request when a user clicks on the submit button. However, I keep encountering two specific errors: App.js:19 POST http://localhost:3001/ net::ERR_CO ...

When the div is loaded, automatically navigate to the crucial li element within it, such as the one with the class "import

Welcome to my first webpage: <html> <head> <script type="text/javascript" src="js/jquery.min.js"></script> </head> <body> <div id="comment"></div> <script type="text/ja ...

Inserting an HTML element into Handlebars.js during a specific iteration of an each loop

I have a channel.json file containing 7 objects of data which are iterated in hb. I am looking for a way to insert a date between these iterations without modifying the .json file. How can I add an html tag to display after the 3rd iteration within the loo ...

Encountering difficulties when attempting to inject NotifierService into an Angular Service

I am attempting to incorporate Angular NotifierService into my service class so that I can display error notifications in case of any exceptions from the service side. I attempted to inject a bean of NotifierService in the constructor of my service class, ...

Implement a function to trigger and refresh components in various Vuejs2 instances simultaneously

I currently have index.html with two Vue instances in different files: <!DOCTYPE html> <html lang="en"> <body> <div id="appOne"> </div> <div id="appTwo"> </div> </body> </html ...

What method is most effective for duplicating objects in Angular 2?

Is it just me, or does Angular 1.x have methods on the global angular object like angular.copy and angular.shallowCopy that are missing in Angular 2? It seems like there is no equivalent version in Angular 2 documentation. If Angular 2 doesn't plan on ...