Bot command for unit conversion shows 'undefined' result

Hey everyone, I need some help with my Discord bot. I made a command to change meters to centimeters. But when I use it, I just get ‘undefined’ as the answer. I can’t figure out why.

Here’s what my code looks like:

if (message.content.startsWith('!change ')) {
  let input = message.content.replace('!change ', '');
  input.split(' ');

  let num = input[0];
  let fromUnit = input[1];
  let toUnit = input[3];
  let answer;
  let text;
  let mathInfo;

  if (fromUnit === 'meters' && toUnit === 'cm') {
    const calculate = (start) => {
      return start * 100;    
    }
    
    answer = calculate(num);
    text = `${num} meters is ${answer} cm`;
    mathInfo = '`Times the number by 100`';    
  }

  const resultBox = new Discord.MessageEmbed()
    .setTitle('Unit Switch')
    .setDescription(text)
    .setColor('#00FF00')
    .addFields(
      { name: 'How to do it', value: mathInfo }
    )

  message.delete();
  message.channel.send(resultBox);
}

The command should work when you type ‘!change 1 meters to cm’. But it’s not. Any ideas what I’m doing wrong? Thanks!

I see the issue in your code. The problem is with how you’re splitting the input. When you do input.split(' '), it creates an array, but you’re not assigning it to anything. So when you try to access input[0], input[1], etc., you’re actually accessing characters of the string, not the split parts.

To fix this, change:

input.split(' ');

to:

input = input.split(' ');

This will properly split your input into an array. Also, make sure to parse num as a number:

let num = parseFloat(input[0]);

With these changes, your command should work correctly. Remember to always check your variable assignments and data types when debugging!

hey mate, i think i see the problem. ur not actually saving the split input anywhere. try changing that line to input = input.split(' '); and it should work. also, maybe use parseFloat(input[0]) to make sure the number is treated as a number. good luck with ur bot!

I’ve run into similar issues with Discord bots before. One thing that helped me was adding some console.log statements to see what values your variables actually hold at different points in the code. For example, try logging ‘input’ right after you split it, and ‘num’, ‘fromUnit’, and ‘toUnit’ before you do the calculation. This way, you can pinpoint exactly where things are going wrong.

Also, don’t forget to handle potential errors. What if someone types the command incorrectly? You might want to add some checks to make sure all the necessary parts of the command are there before trying to process it.

Lastly, consider using a switch statement instead of if-else if you plan to add more unit conversions later. It’ll make your code much cleaner and easier to maintain in the long run.