Discord bot won't execute commands - JavaScript setup issue

Hey everyone, need some help with my Discord bot setup

I’m working on creating my first Discord bot using JavaScript and I’m running into problems. The bot comes online fine but when I try to use commands it just ignores them completely.

I’ve double checked all the bot permissions in the Discord developer portal and everything looks correct there. The bot has message read permissions and can send messages.

Here’s the code I’m using:

const { Client, Intents } = require('discord.js');

const bot = new Client();

bot.once('ready', () => {
    console.log('Bot is running');

    const botToken = 'MyBotToken';
});

const COMMAND_PREFIX = '!';

bot.on('message', msg => {

    let commandArgs = msg.content.substring(COMMAND_PREFIX.length).split(" ");

    switch(commandArgs[0]) {
        case 'hello':
            msg.reply('Hi there!');
        break;
    }
})

bot.login(botToken);

When I type !hello in the chat the bot doesn’t respond at all. What am I missing here? Any help would be great thanks.

Looking at your code, there’s another issue that might be causing problems beyond what was already mentioned. You’re not checking if the message actually starts with your command prefix before processing it. This means your bot is trying to parse every single message as a potential command. Add a check like if (!msg.content.startsWith(COMMAND_PREFIX)) return; at the beginning of your message event handler. Also make sure you’re not responding to your own bot messages by adding if (msg.author.bot) return;. I ran into similar silent failures when I started out and these basic filters solved most of my command recognition issues.

dude ur bot token is defined inside the ready event but ur trying to use it outside at the bottom. move const botToken = 'MyBotToken'; to the top of ur file before the ready event. thats probly why its not even connecting properly

It seems like you might be encountering two key issues. First, the botToken variable is declared inside the ready event, which makes it unavailable at the time of the login call. You should move the declaration out of that event. Second, with the newer versions of discord.js, you need to specify intents when you instantiate the Client. Modify your client initialization to include { intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES] }. I faced the same problem early on, and these adjustments resolved it for me.