I’m building my first Discord bot using Node.js and discord.js library. Right now I can only get basic echo-style commands to work properly. Whenever I attempt to add more complex functionality or even simple features like command prefixes, the entire bot crashes and stops responding.
Here’s my current working code that handles a simple response command:
I keep getting errors about undefined variables and the bot won’t start. What am I doing wrong with the message handling? Any help would be great since I’m pretty stuck here.
The main issue you’re encountering is likely due to the discord.js version you’re using. Your code looks like it’s written for discord.js v12, but if you’re using v13 or v14, the intents system is required and the message event handling has changed significantly. For v13+, you need to specify intents when creating your client and use messageCreate instead of message. Try updating your client initialization to:
Then change your event listener from bot.on('message', msg => { to bot.on('messageCreate', msg => {. Also, replace msg.channel.type !== 'text' with msg.channel.type !== 0 since channel types are now numbers. These changes should resolve the undefined variable errors you’re seeing and get your prefix system working properly.
Looking at your code, there’s another potential issue that might be causing crashes - you’re not handling empty echo commands properly. When someone types just !echo without any arguments, your args.slice(1).join(' ') will return an empty string, which some Discord configurations reject as invalid messages. I ran into this exact problem when building my first bot. Add a simple check before sending the echo response: javascript else if (msg.content.startsWith('!echo')) { const args = msg.content.split(' '); const echoText = args.slice(1).join(' '); if (echoText.length > 0) { msg.channel.send(echoText); } else { msg.channel.send('Please provide text to echo!'); } } Also check your console output when the bot crashes - Node.js usually provides specific error messages that pinpoint exactly which line is causing the undefined variable errors. The crash logs will tell you whether it’s a discord.js version mismatch or a logic error in your command handling.