Creating multiple unique alphanumeric codes with a single array in a Discord bot using Node.js

I’m working on a Discord bot and I’m stuck. I want to make it generate several different random alphanumeric codes when a user types a command. Right now, it only makes one code twice. Here’s what I have so far:

const { MessageEmbed } = require('discord.js');
const settings = require('../settings.json');

module.exports = {
  name: 'generate',
  description: 'Create random alphanumeric codes',

  run(msg) {
    if (msg.channel.id !== settings.codeChannel) {
      msg.channel.send(
        new MessageEmbed()
          .setColor(settings.colors.main)
          .setTitle('Incorrect Channel')
          .setDescription(`Please use <#${settings.codeChannel}> to generate codes`)
          .setFooter(msg.author.tag, msg.author.displayAvatarURL({ dynamic: true, size: 64 }))
          .setTimestamp()
      );
      return;
    }

    const code = Math.random().toString(36).substring(7);
    msg.channel.send(
      new MessageEmbed()
        .setColor(settings.colors.main)
        .setTitle('Codes Generated')
        .setDescription(`${code}\n${code}`)
        .setFooter(msg.author.tag, msg.author.displayAvatarURL({ dynamic: true, size: 64 }))
        .setTimestamp()
    );
  }
};

How can I change this to create multiple unique codes instead of repeating the same one? Any help would be great!

I’ve experienced this issue before and managed to solve it by ensuring each code is unique. Instead of generating the same code twice, I created an array and used a while loop to check for duplicates before adding a new code. For instance:

const uniqueCodes = [];
while (uniqueCodes.length < 5) {
  const newCode = Math.random().toString(36).substring(7);
  if (!uniqueCodes.includes(newCode)) {
    uniqueCodes.push(newCode);
  }
}

Then, simply join the codes with a newline in your embed:

.setDescription(uniqueCodes.join('\n'))

This ensures you get a set of 5 unique codes every time.

neo, i had a simlar issue. try using a loop to gen unique codes:

const codes = [];
for(let i=0;i<5;i++){
  codes.push(Math.random().toString(36).substring(7));
}

then join the codes with ‘\n’ for diff codes!

I encountered a similar challenge when developing a code generator for my project. Here’s a solution that worked well for me:

Create an array to store your unique codes, then use a Set to ensure uniqueness. You can adjust the number and length of codes as needed.

const uniqueCodes = new Set();
while (uniqueCodes.size < 5) {
uniqueCodes.add(Math.random().toString(36).substr(2, 8));
}

const codesArray = Array.from(uniqueCodes);

This approach guarantees distinct codes every time. You can then use codesArray.join(‘\n’) in your embed description to display them. Hope this helps with your Discord bot!