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:
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:
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:
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:
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 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.
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.