I'm facing a challenge with discord.js where I can't seem to get multiple prefixes to work. Do you have any suggestions on how I can modify it to

As the title suggests, I've been experimenting with different versions of the code below. The current version can recognize firstPrefix but not secondPrefix. I simply want my discord bot to be able to identify both prefixes and split the Args accordingly.

const firstPrefix = '!test ';
const secondPrefix = '!testtwo ';

//Prefix
bot.on('message', message => {
    message.content = message.content.toLowerCase();
    if (message.author.bot || !message.content.startsWith(firstPrefix || secondPrefix)) {
        return;
    }

//Args split
    if (message.content.startsWith(firstPrefix)) {
        console.log("A")
        var args = message.content.slice(firstPrefix.length).split(/ +/);
    }
    else if (message.content.startsWith(secondPrefix)) {
        console.log("B")
        var args = message.content.slice(secondPrefix.length).split(/ +/);
    } 

I've attempted:

if (message.author.bot || !message.content.startsWith(firstPrefix) || !message.content.startsWith(secondPrefix))

However, that approach did not work at all. I'm quite puzzled here, any assistance would be greatly appreciated. Thank you.

Answer №1

One effective method is to save your prefixes in an array and then verify if the input begins with any of the prefixes by utilizing the Array#some() function

const prefixes = ['!start ', '!begin '];

bot.on('message', message => {
   ...
   if (prefixes.some(prefix => message.content.startsWith(prefix)) {
      ...
   }
});

Answer №2

The current code you have (in the second code block) is not functioning correctly. It will only work if it begins with one prefix and not the other, resulting in a true if statement that does not execute your desired command.

In the first code block, both firstPrefix and secondPrefix are defined with values, so firstPrefix || secondPrefix will evaluate to firstPrefix.

To include both firstPrefix AND secondPrefix, you should modify the code as follows:

if (
  message.author.bot || /* if it is a bot */
  (!message.content.startsWith(firstPrefix) && /* does not start with first */
  !message.content.startsWith(secondPrefix))) /* and does not start with second */ {
  return;
}

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

What is the proper way to send an AJAX request with the data type set to

I am currently working on creating my own POST request. Below is the function I have written: function sendPost(o) { var h = new XMLHttpRequest(); h.onreadystatechange = requestComplete; function requestComplete() { if (h.readyState = ...

JavaScript library jQuery is unable to locate the element tagged as "<."

I've encountered an issue with setting the value of dropdown options in a web page using strings that contain < and >. Here is an example code snippet: <select id="m" name="m" > <option value="" selected="selected" >All</option& ...

How can I retrieve routing parameters in a Vue.js/Nuxt/TypeScript app?

In the process of developing my website based on the Nuxt TypeScript Starter template, I've encountered a challenge. Specifically, I have created a dynamically routed page named _id.vue within my pages folder and am looking to access the id property i ...

Removing items in vue.js

I'm currently in the process of learning Vue.js. This is my first attempt at creating a small to-do application, and I am encountering issues with deleting each individual task upon clicking. Despite watching multiple YouTube tutorials, I have not bee ...

Tips for setting up my bot to pull random messages from a channel and send one when an autoresponse is activated

As per the headline, I attempted to utilize fetchMessages in order to monitor the messages being sent in a specific channel. However, when I experimented with this method, it simply generated never-ending blocks of data in the console. Upon inspection, I ...

Run a PHP function using <button onclick=""> tag

Is it possible to trigger the execution of a PHP script when clicking an HTML button? I am aware that simply calling a PHP function directly from the button's onclick event like this: <button onclick="myPhpFunction("testString")">Button</butt ...

Node.js promises are often throwing Unhandled Promise Rejection errors, but it appears that they are being managed correctly

Despite my efforts to handle all cases, I am encountering an UNhandledPromiseRejection error in my code. The issue seems to arise in the flow from profileRoutes to Controller to Utils. Within profileRoutes.js router.get('/:username', async (r, s ...

Operate on Nested JSON Arrays

I have the following JSON array: var salesData = [ { "products": "Cars", "solddate" : "2022-01-01", "noofitems" : " ...

Testing a React component using the `ua-parser-js` plugin with Jest and React Testing Library

I've developed a simple component that displays an image depending on the operating system you are using (in this case, iOS and Android). import { UAParser } from "ua-parser-js"; export const DownloadApp = ({ appleStoreUrl, playStoreUrl }: ...

Optimizing Backend Access with Laravel and Vue JS: How to Choose the Most Effective Approach

Currently, I am utilizing Laravel API passport to handle authentication in my Single Page Application (SPA) built with Vue. At the moment, whenever I need to access the backend server, I have to include a header in order to be allowed through the protected ...

Looking for a method to substitute "test" with a different value

Showing a section of the menu using <li id="userInfo" role="presentation" data-toggle="tab" class="dropdown"> <a href="#" name="usernameMenu" class="dropdown-toggle" data-toggle="dropdown" role="button"> <span class="glyphicon glyph ...

The issue with the trigger function in jQuery is specifically affecting Chrome browser

When attempting to load a modal window using a link like , I am encountering issues in Chrome, Safari, and IE. However, Opera and FF are functioning properly. The modal window is being called as an iframe. Other buttons that are supposed to open the modal ...

What is the best way to efficiently input identical data into multiple controllers ($scope) using just one call in AngularJS?

I have a situation where I am using a factory to make a call in two controllers on the same page. However, I want to avoid making an AJAX call twice. I tried using $q.defer(), but it doesn't seem to be working! Here is the code snippet: (function ...

According to npm, the JSON is not valid, but jsonlint.com confirms that it is valid

Here is the json file for package.json that I used npm install on (specifically for the angularfire-seed project on github): { "name": "angularfire-seed", "description": "A starter project for Angular + Firebase with AngularFire", "version": "1.0.0 ...

The function Mediarecorder.start() is experiencing issues on Firefox for Android and is not functioning

Recently, I've been facing a peculiar issue while developing a web application. The purpose of this app is to capture about 10 seconds of video intermittently from the device webcam and then upload it to a server. For this functionality, I utilized th ...

The component in React does not refresh after updating the state

I have a React page where I am displaying a list of quizzes fetched from an external API. There's also a "New Quiz" button that opens a dialog with a form for users to create a new quiz. My issue is with making the table re-render once the POST reque ...

Are there any SVG libraries available that can create line graphs similar to those seen in Google Analytics?

The line graph in Google Analytics that is created using SVG is quite impressive. Are there any libraries available that can generate similar line graphs to those in Google Analytics? ...

Issue with BrowserRouter, improperly looping through the array using map

Encountering an issue with importing content in my React app project using <BrowserRouter>. Within the app, there are 3 Material-UI Tabs: /lights, /animations, /settings. <Switch> <Route path="/lights" component={LightsMenu} /> ...

Discover the process of connecting a REST controller with AngularJS and Spring

I have a list of file paths stored in an array within the scope variable of an AngularJS Controller. My goal is to properly map these file paths to a Java REST controller for further processing. When I pass it as "/ABC/Scope-Variable," it successfully ma ...

The time parameter in jQuery's ScrollLeft animation method seems to be disregarded

Hey everyone, I'm having trouble understanding this: thumb.animate( {'scrollLeft': active.width()*3}, 'slow' ); The scrolling works fine, but the "slow" parameter seems to be ignored. Instead of moving slowly, it moves instan ...