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

Is there a comparable Javascript alternative to the Ruby gem "site_prism" for Page Objects design?

Is there a JavaScript framework for Protractor in NodeJS that provides a clean way to define Page Object Elements similar to site_prism? I've explored astrolabe but it doesn't quite meet the requirements. This is an example of how Page Objects a ...

Text displayed in dropdown when selecting autocomplete option from Material UI

I'm facing a problem with the Material UI's Autocomplete Component. The issue is that the value is being shown instead of the text element. My data source format looks like this: [{value: 'someValue', text: 'My Text'}, {value ...

Display a hoverable button for a singular element within an array during the process of mapping through the array

const ChatWidget = () => { const bodyRef = useRef(null) const [{messages,roomMessages,roomID,socket,user}, dispatch] = useStateValue() const [dropdown, setDropdown] = useState(false) useEffect(()=>{ const setScreen = () =>{ bodyRef.cur ...

Is the disable feature for React buttons not functioning properly when incorporating Tailwind CSS?

import React, { useState } from "react"; import facebook from "../UI/icons/facebook.png"; import Button from "../UI/Button/Button"; import Card from "../UI/Card/Card"; import twitter f ...

Add data to a DataTable without the need to manually refresh the page

I am looking to dynamically append a DataTable on my webpage. The goal is to have a form that users can fill out multiple times and each time they submit their inputs, the results will be added to the DataTable for display. <table id="table" class="di ...

AngularJS radio buttons are interactive HTML elements that allow users

I've been looking for a solution to bind my radio inputs to a model in a simple and clean way, but I haven't found one that works for me yet. In my HTML, I have: <input ng-model="searchByRma" type="radio" name="search-type"> <input ng-m ...

Struggling to maintain context with axios in React despite diligent use of arrow functions

In my component, I have a function for posting data. Although it works well, the context of my component is lost in the success message. This is puzzling because I am using arrow functions. Why does the "this" context get lost in this situation? The issu ...

Easily validate the contenteditable attribute of <td> element

I am currently working on a table that displays data from a MYSQL database. Whenever a user makes changes to an element in the table, I want the database to be updated using AJAX. Below is my JavaScript code for sending data in an editable row. function s ...

What is the best approach for sending mapbox coordinates to a higher-level class in a react application?

As a beginner in learning React, I'm currently working on setting a map marker with a click event on a Mapbox GL map. The challenge I'm facing is passing the lngLat object back up to the parent component. Can someone guide me on how to achieve th ...

A step-by-step guide on fetching multiple iframe contents simultaneously with Selenium in Java

Today, I am facing an interesting challenge. I need to extract the page source of a webpage that includes an iframe. Surprisingly, when using the PhantomJSDriver with the code snippet below, I am only able to retrieve either the page content or the iframe ...

Tips for utilizing global functions in VUE 2 CLI crowd

I have multiple components that require the same functions. Is there a way to avoid duplicating the code in each component and instead use it globally...? Even if I put the function in the App.vue, it still isn't accessible in the components. ...

Error message: The module '@project-serum/anchor' does not export the object 'AnchorProvider' as intended

I encountered an issue while attempting to run my react application. The issue: Attempted import error: 'AnchorProvider' is not exported from '@project-serum/anchor'. The import declaration in my code: import idl from './idl.json ...

What is the best way to adjust the screen to display the toggle element when it is opened?

Here is the code I'm currently using to create a toggle button that shows or hides extra content when clicked: $(".toggle .button").click(function() { $(this).next().slideToggle('fast'); }); The issue I am encountering is that if t ...

PHP MySQL - Automatically trigger email notification upon insertion of a new record

Is there a way to trigger an email alert only when a new record is added, not when the user edits input fields in a table? The database I'm working with stores equipment delivery dates. Users schedule deliveries and input the dates into a SQL Server ...

Encountering a Typescript error while attempting to remove an event that has a FormEvent type

Struggling to remove an event listener in Typescript due to a mismatch between the expected type EventListenerOrEventListenerObject and the actual type of FormEvent: private saveHighScore (event: React.FormEvent<HTMLInputElement>) { This is how I t ...

The React setState function isn't updating the state as expected when used within the useEffect hook

I'm new to using hooks and I'm facing an issue with setState when trying to update data received from an API. Despite logging the response data successfully, it seems that the state does not update as expected. My useEffect function is set to run ...

Contrasting bracket notation property access with Pick utility in TypeScript

I have a layout similar to this export type CameraProps = Omit<React.HTMLProps<HTMLVideoElement>, "ref"> & { audio?: boolean; audioConstraints?: MediaStreamConstraints["audio"]; mirrored?: boolean; screenshotFormat?: "i ...

Overflow is causing interference with the scrollY value

I've been attempting to retrieve the scrollY value in my React app, but it seems to be affected by overflow-related issues. Below is the code snippet I used to access the scrollY value: import React from "react"; import { useEffect, use ...

Tips for removing the default hover and click effects from a Material-UI CardActionArea

Check out the card sample with a lizard photo on https://material-ui.com/components/cards. When you hover over the cardActionArea, it will get darker or lighter based on the theme. Clicking on the card will make the picture change its brightness relative ...

script locate the div ID within a given text and clear its content

My string contains some dynamic HTML with a div element having an id of "time", Here's an example: myString = "<div class="class">blahblah</div><div id="time">1:44</div>" How can I generate a new string that is identical to ...