I'm having trouble getting my bot command handler to function properly

When it comes to my command handler, the commands function properly. However, when I attempt to include arguments like $user-info @user instead of just $user-info, it returns an error stating that the command is invalid.

Code

//handler
 const prefix = '$';

const fs = require('fs');
const { args } = require('./commands/utility/user-info');


client.commands = new Discord.Collection();

const commandFolders = fs.readdirSync('./commands');

for (const folder of commandFolders) {
 const commandFiles = fs.readdirSync(`./commands/${folder}`).filter(file => file.endsWith('.js'));
for (const file of commandFiles) {
const command = require(`./commands/${folder}/${file}`);
client.commands.set(command.name, command);
}
}

client.on('message', message => {


 if (!message.content.startsWith(prefix) || message.author.bot) return;

  const args = message.content.slice(prefix.length).trim().split("/ +/");
  const commandName = args.shift().toLowerCase();
  const command = client.commands.get(commandName);

  if (!client.commands.has(commandName)) return message.channel.send('I don\'t think that\'s a valid command...');

  if (command.args && !args.length) {
    return message.channel.send(`You didn't provide any arguments!`);
  }

  if (command.guildOnly && message.channel.type === 'dm') {
    return message.reply('I can\'t execute that command inside DMs!');
  }

  try {
    client.commands.get(commandName).execute(message, args);
  } catch (error) {
    console.error(error);
    message.reply('there was an error trying to execute that command!');
  }

});

//user-info
const { MessageEmbed } = require("discord.js");

    module.exports = {
    name: "user-info",
    description: "Returns user information",
    args: true,

      async execute(message, args){
    let member = await message.mentions.members.first() ||                                   message.guild.members.cache.get(args[0]) || message.guild.members.cache.find(r => r.user.username.toLowerCase() === args.join(' ').toLocaleLowerCase()) || message.guild.members.cache.find(r => r.displayName.toLowerCase() === args.join(' ').toLocaleLowerCase()) || message.member;
  
    if(!member)
    return message.channel.send("**Enter A Valid User!**");
  
    const joined = formatDate(member.joinedAt);
    const roles = member.roles.cache
        .filter(r => r.id !== message.guild.id)
        .map(r => r.name).join(", ") || 'none';
    const created = formatDate(member.user.createdAt);

    const embed = new MessageEmbed()
        .setTitle("User Info")
        .setFooter(message.guild.name, message.guild.iconURL())
        .setThumbnail(member.user.displayAvatarURL({ dynamic: true}))
        .setColor("GREEN")
        .addField("**User information**", `${member.displayName}`)
        .addField("**ID**", `${member.user.id}`)
        .addField("**Username**",`${member.user.username}`)
        .addField("**Tag**", `${member.user.tag}`)
        .addField("**Created at**", `${created}`)
        .addField("**Joined at**", `${joined}`)
        .addField("**Roles**", `${roles}`, true)
        .setTimestamp()

        member.presence.activities.forEach((activity) => {
    if (activity.type === 'PLAYING') {
        embed.addField('Currently playing',`\n**${activity.name}**`)
    }
        })

    message.channel.send(embed);
}
}

That's all the code. I have attempted to debug it but haven't found a solution yet. For debugging, I tried:

if (!client.commands.startsWith(commandName)) return message.channel.send('I don't think that's a valid command...');

Instead of:

if (!client.commands.has(commandName)) return message.channel.send('I don't think that's a valid command...');

However, this resulted in some errors.

Answer №1

When using the <code>split() method of the String prototype, the separator parameter can accept either a string or a regular expression. It seems like you are attempting to provide a regular expression in its literal form, so there should be no quotation marks around it. Otherwise, it will be interpreted as a string to search for in the message. Your current code interprets "/ +/" as the string to split by rather than the pattern +. To fix this, you can adjust your code as follows:

const arguments = message.content.slice(prefix.length).trim().split(/ +/);

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

React.js, encountering unusual behavior while implementing a timer

I'm currently working on a React project to create a basic timer. The start button should initialize the timer, while the stop button should pause it. However, I've encountered some unexpected behavior. When I click on start for the first time, ...

Creating a basic bootstrap modal dialog in ASP.NET MVC: A step-by-step guide

After navigating from the login page, the user clicks on the "ForgotPassword" link and is directed to a separate page where they can fill out a form to request a new password. http://localhost:2350/Account/ForgotPassword Once the user clicks on the "Save ...

Show the current Date and Time dynamically using only one line of JavaScript code

After running this command, I encountered an issue: $("#dateTime").text(new Date().toLocaleString()); The result displayed was 2/21/2020, 10:29:14 AM To make the time increase every second, I attempted this code: setInterval($("#dateTime").text(new Dat ...

Top method for transferring the result of a function to descendant components in Vue

In my parent component, I have a data object named config structured like this: data() { return { config: { Groups: [ { name: "A", Types: [ { mask: 1234, name: ...

How to handle multiple radio inputs and determine the checked value in Vue?

Currently, I am in the process of learning Vue.js and developing a basic poll generator. However, I have encountered an issue with radio inputs. In this application, each question can be of two types - 'select' or 'range.' 'Select ...

Instructions for utilizing lodash or JavaScript to apply a filter to an object

Received this object from the Server: var data = { test1: { documents: [] }, test2: { documents: [{ vId: 'sdfas23', TypeId: '81', isDeleted: false }], answer: true }, test3: { documents: ...

Contrast the differences between arrays and inserting data into specific index positions

In this scenario, I have two arrays structured as follows: arr1=[{room_no:1,bed_no:'1A'}, {room_no:1,bed_no:'1B'}, {room_no:2,bed_no:'2A'}, {room_no:3,bed_no:'3A'}, {room_no:3,bed_no:'3B ...

What would cause this to result in a blank array?

I have a main component that contains multiple sub-components, which I navigate between by clicking on different elements. These sub-components are all Vue files. What I am trying to achieve is to dynamically highlight the active component when it is bein ...

Pass data from a Firebase JavaScript callback function in the Data Access Layer (DAL) to another function in the controller

I have been developing a basic chat application that enables users to send messages in a group chat and see them instantly updated. To achieve this, I opted for Firebase and spent time familiarizing myself with its web API. However, I encountered difficult ...

Having trouble parsing JSON elements separately

I am currently working on generating data to be utilized in a chart.js plot by utilizing C# Controller and javascript. The Controller method I have returns a JSONResult to a javascript function. public JsonResult GetPlansPerDoc(){ //Code to retrieve d ...

Utilizing hooks in node.js functions

Is there a way to apply before and after hooks on a function? I need these hooks to trigger whenever the function is called. While Express.js middleware concept works for routes, I require similar hooks for functions on the server side. function main(){ ...

Navigating websites: Clicking buttons and analyzing content

When looking to navigate a website's directory by utilizing buttons on the page or calling the associated functions directly, what language or environment is most suitable for this task? After experimenting with Python, Java, Selenium, and JavaScript, ...

Retrieve the page dimensions from a Material UI component `<DataGrid autoPageSize/>`

When utilizing <DataGrid autoPageSize/>, as outlined in the documentation, you can have a Material UI table that adjusts its page size based on the browser height. However, if you are fetching data from the server progressively, it becomes essential ...

Utilizing Selenium to locate an element by its class name and then deleting it from the document object model through

I have found a code that worked really well for me. It involves getting the quantity of messages first and then removing them from the DOM. public static void RemoveMessages() { // Removing messages from the DOM using JavaScript ...

The compiler option 'esnext.array' does not provide support for utilizing the Array.prototype.flat() method

I'm facing an issue with getting my Angular 2 app to compile while using experimental JavaScript array features like the flat() method. To enable these features, I added the esnext.array option in the tsconfig.json file, so the lib section now includ ...

Troubleshooting VueJS route naming issues

I am having an issue with named routes in my Vue app. Strangely, the same setup is working perfectly fine in another Vue project. When I click on a named router-link, the section just disappears. Upon inspecting the element in the browser, I noticed there ...

Tips for ensuring only one dropdown is opened at a time

Hey there! I've been struggling with getting my dropdowns to open one at a time on my website. I attempted to hide them all by default, but they still insist on opening simultaneously. Any ideas on what I might be overlooking? Thank you for your help! ...

A guide on performing CRUD operations on locally stored JSON data using React JS

Retrieve the JSON data from any endpoint and store it locally fetch("any endpoint") .then((response) => response.json()) .then((responseJson) => { this.state ={ data:responseJson } }) How to perform CRUD operations on a sample JSO ...

Maximizing the efficiency of this JavaScript code

Is there a way to optimize this code for better efficiency? I'm trying to enhance my coding skills and would appreciate some feedback on this particular section: $(function(){ $('#buscar').focus(function(){ if(($(this).val() === ...

How to toggle between arrays using ng-repeat

Currently, I am managing 3 arrays and wish to toggle between them using ng-repeat: $scope.fooDataObj = { array1:[{name:'john', id:'1'},{name:'jerry', id:'2'}], array2[{name:'bill', id:'1'},{name: ...