JavaScript Discord Bot Crashes on Startup

My Discord bot keeps crashing whenever I try to run it. The command window opens for a second and then immediately closes. I’m trying to make a moderation bot that can automatically remove inappropriate messages from my server. The bot worked fine before I added the word filtering feature, but now it won’t even start up properly. I think there might be a syntax error or missing bracket somewhere in my message handling code. Can someone help me figure out what’s wrong?

My Code:

const Discord = require('discord.js');
const client = new Discord.Client();
const fs = require('fs');
let previousUser;

const botToken = 'YOUR_TOKEN_HERE';

client.on('ready', () => {
  console.log('Bot is online!');
});

client.on('message', msg => {
  let messageWords = msg.content.split(' ');
  if(messageWords[0] == '!addcmd') {
    let cmdContent = msg.content.split('|', 2);
    let cmdTitle = msg.content.split(' ');
    if(cmdTitle[1].charAt(0) == '!') {
      saveNewCommand(cmdContent, cmdTitle);
      msg.channel.send('New command ' + cmdTitle[1] + ' added successfully');
    } else {
      msg.channel.send('Commands must start with !');
    }
  }

  fs.readFile('./data/cmdlist.txt', 'utf8', function(error, data) {
    let cmdArray = data.toString().split(';');
    for(let j = 0; j < cmdArray.length; j++) {
      if(msg.content == cmdArray[j]) {
        if(cmdArray[j] == '!list') {
          msg.channel.send(cmdArray);
          break;
        }
        if(cmdArray[j] == '!info') {
          msg.channel.send('Available commands: !info, !list, !database, !hello');
          break;
        }
        let cmdFile = './data/' + cmdArray[j] + '.txt';
        fs.readFile(cmdFile, 'utf8', function(error, content) {
          try {
            let responses = content.toString().split(';');
            let randomIndex = Math.random() * responses.length;
            msg.channel.send(responses[Math.floor(randomIndex)]);
          } catch(error) {
            console.log('Error:', error);
          }
        });
      }
    }
  });
});

function saveNewCommand(cmdContent, cmdTitle) {
  let commandName = cmdTitle[1];
  let commandDesc = cmdContent[1];
  let exists = false;
  
  fs.readFile('./data/cmdlist.txt', 'utf8', function(error, fileData) {
    let existingCmds = fileData.toString().split(';');
    for(let k = 0; k < existingCmds.length; k++) {
      if(commandName == existingCmds[k]) {
        exists = true;
      }
    }
    if(exists) {
      writeCommand(commandDesc, true, commandName);
    } else {
      writeCommand(commandDesc, false, commandName);
    }
  });
}

client.on('message', msg => {
  let user = msg.author;
  let content = msg.content.toLowerCase();
  let adminPrefix = '>';
  
  if(user.id === 'ADMIN_ID_HERE') {
    return;
  }
  
  if(content.includes('badword')) {
    msg.delete();
    msg.author.send('That word is not allowed here. Please watch your language!');
  }
}) // Missing semicolon here causes the crash

function writeCommand(desc, exists, cmdName) {
  let filePath = './data/' + cmdName + '.txt';
  if(exists) {
    fs.writeFile(filePath, desc, function(error) {
      if(error) {
        console.error(error);
      }
    });
  } else {
    fs.appendFile('./data/cmdlist.txt', cmdName + ';', (error) => {
      if(error) throw error;
    });
    
    fs.writeFile(filePath, desc, function(error) {
      if(error) {
        console.error(error);
      }
    });
  }
}

client.login(botToken);

You’re missing a semicolon at the end of your second client.on('message') event handler. That’s what’s stopping your bot from starting up. I see you already spotted it in your comment - just add the semicolon and you should be good to go. I’ve hit the same issue before. These tiny syntax errors always seem to break everything.

Others already covered the syntax error, but you’ve got a bigger problem. Running file operations inside message events kills performance once your bot gets traffic. I found this out the hard way when my bot started timing out under load.

Load your command data into memory at startup instead of reading files every message. Also check that your data directory and cmdlist.txt actually exist - missing files throw errors you won’t see when the window closes right away. Run your script from command line instead of double-clicking to see what’s actually breaking.

First, make sure discord.js is actually installed - run npm install discord.js in your project folder. Also check that you’re using your real bot token, not just placeholder text. These two things cause most startup issues.

This topic was automatically closed 4 days after the last reply. New replies are no longer allowed.