Creating multiple unique random strings from single constant array in Discord.js bot

I’m having trouble with my Discord bot command. I want to create several different random alphanumeric strings each time someone uses my command, but I can’t figure out how to do it properly.

Here’s what I have so far for my !generate command:

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

module.exports = {
    name: 'generate',
    description: 'Creates random alphanumeric sequences',

    async execute(interaction) {
        
        if (interaction.channel.id !== settings.targetChannel) {
            await interaction.reply({
                embeds: [new EmbedBuilder()
                    .setColor(settings.colors.error)
                    .setTitle('Invalid Channel')
                    .setDescription(`Please use <#${settings.targetChannel}> for string generation`)
                    .setFooter({ text: interaction.user.tag, iconURL: interaction.user.displayAvatarURL() })
                    .setTimestamp()]
            });
            return;
        }
        
        const randomStr = [`${Math.random().toString(36).slice(2)}`+'\n'];
        
        await interaction.reply({
            embeds: [new EmbedBuilder()
                .setColor(settings.colors.success)
                .setTitle('Generated String')
                .setDescription(`${randomStr}${randomStr}`)
                .setFooter({ text: interaction.user.tag, iconURL: interaction.user.displayAvatarURL() })
                .setTimestamp()]
        });
    }
};

The issue is that when I run this command, I get the same string repeated instead of multiple different random strings. How can I modify this to generate several unique random strings each time?

You’re creating the random string once, then reusing the same variable. When you do ${randomStr}${randomStr} you’re just duplicating the same string. Each Math.random() call needs to happen separately for different results. Replace your randomStr line with:

const generateRandomString = () => Math.random().toString(36).slice(2);
const string1 = generateRandomString();
const string2 = generateRandomString();
const string3 = generateRandomString();

Then use ${string1}\n${string2}\n${string3} in your description. You could loop this if you need more strings, but this way you control exactly how many unique strings get generated.

You’re creating the random string once and reusing the same reference. Your randomStr array has one generated string that gets repeated when you concatenate it. Don’t store the result - generate fresh strings when you need them. Try this:

const getRandomString = () => Math.random().toString(36).slice(2);

await interaction.reply({
    embeds: [new EmbedBuilder()
        .setColor(settings.colors.success)
        .setTitle('Generated String')
        .setDescription(`${getRandomString()}\n${getRandomString()}\n${getRandomString()}`)
        .setFooter({ text: interaction.user.tag, iconURL: interaction.user.displayAvatarURL() })
        .setTimestamp()]
});

Each function call now produces a completely new random string. Add more getRandomString() calls separated by newlines if you want more strings.

You’re storing the random string in a variable, then using that same variable multiple times. That’s why you get identical values - it’s just referencing the same computed string.

Don’t store it first. Put Math.random().toString(36).slice(2) directly in your template string:

.setDescription(`${Math.random().toString(36).slice(2)}\n${Math.random().toString(36).slice(2)}\n${Math.random().toString(36).slice(2)}`)

This makes JavaScript run the random generation each time it hits that code in the template. You could also wrap it in a function and call it multiple times. Either way works - you’ll get fresh random values instead of the same one repeated.

you’re creating an array with the random string already in it, then reusing that same array. make a function instead:

function makeRandomStr() {
  return Math.random().toString(36).slice(2);
}

const str1 = makeRandomStr();
const str2 = makeRandomStr();

then drop those into your embed description. much cleaner than jamming the whole Math.random() mess directly in there.

You’re only running Math.random().toString(36).slice(2) once when you assign it to randomStr. After that, JavaScript just reuses that same value everywhere - it doesn’t recalculate.

Hit this same issue when I built my first bot. Easy fix is forcing fresh evaluation each time. Skip the function and use a simple loop:

let randomStrings = '';
for (let i = 0; i < 3; i++) {
    randomStrings += Math.random().toString(36).slice(2) + '\n';
}

.setDescription(randomStrings.trim())

Way easier to adjust the count this way without messing with multiple function calls. The trim() kills the trailing newline. Works great for generating however many unique strings you want without duplicating code.

Here’s a better approach that scales:

const randomStrings = Array.from({length: 5}, () => Math.random().toString(36).slice(2));

Then join them:

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

Just change the length value to get more or fewer strings. Way more flexible than hardcoding each one.

Honestly though, for Discord bots generating random strings, you might want to check out Latenode. Set up workflows that trigger on messages and generate multiple strings without all this JavaScript. You can store the strings, send them to different channels, or schedule automatic generation.

Latenode handles the Discord API so you can focus on logic instead of wrestling with embed builders.