Currently I am trying to work on my bot and update its responses. Right now I am trying to use the code below to make it respond with the random embeds I made. For some reason when doing using this code the bot either responds with “NaN” or “3”?
const embeds = [`${yellowinfocommandembed}`, `${whiteinfocommandembed}`, `${redinfocommandembed}`, `${purpleinfocommandembed}`, `${pinkinfocommandembed}`, `${orangeinfocommandembed}`,`${limeinfocommandembed}`,`${greeninfocommandembed}`,`${cyaninfocommandembed}`,`${browninfocommandembed}`,`${blueinfocommandembed}`,`${blackinfocommandembed}` ];
const embed = Math.floor(Math.random() * embeds.length);
if(message.channel.type == "dm") {
message.channel.send(embed);
}
else {
message.delete ();
message.channel.send(embed);
}
}
Advertisement
Answer
The purpose of:
Math.floor(Math.random() * embeds.length);
Is to generate a pseudo-random integer between 0 and the length of the array (floored). This does not provide a random element from an array. You can use this number to get an element from an array using bracket syntax.
const arr = ['Peach', 'Pear', 'Plum', 'Pomegranate'];
const num = Math.floor(Math.random() * arr.length);
console.log(`The random number: ${num}`);
console.log(`The corresponding array element: ${arr[num]}`);
Edit:
You’ll have to understand template literals to realize why your bot is sending [object Object]
. Template literals (${variable}
) are mainly used for two purposes
- To merge together a string and variable, or multiple variables
- To coerce a variable’s data type to a string
Here’s an example of the second purpose.
// normal usage: (`1 + 1 is ${1 + 1}`) => 1 + 1 is 2
console.log(typeof 10); // just the number 10
console.log(typeof `${10}`); // but if I put it in a teplate literal, it coerces itself to a string
// of course, this also applies for concatenation using the + operator
// normal usage: ('1 + 1 is ' + (1 + 1)) => 1 + 1 is 2
console.log(typeof 10); // just the number two
console.log(typeof ('' + 10)); // but if I merge it with an empty string, it coerces itself to a string
Why is this important? orangeinfocommandembed
, for example, is an instance of the MessageEmbed
class. So when that gets coerced to a string, it becomes [object Object]
.
const obj = { foo: 'bar' };
console.log(`${obj}`); // [object Object]
Sorry, that’s a long explanation for a relatively easy fix. Just remove the template literals and only use the base variables.
const embeds = [
yellowinfocommandembed,
whiteinfocommandembed,
redinfocommandembed,
purpleinfocommandembed,
pinkinfocommandembed,
orangeinfocommandembed,
limeinfocommandembed,
greeninfocommandembed,
cyaninfocommandembed,
browninfocommandembed,
blueinfocommandembed,
blackinfocommandembed,
];