In my Discord Bot that I am making, it needs to select a random object from a JSON file. My current code is this:
function spawn(){
if (randomNum === 24) return
const name = names.randomNum
const embed = new Discord.RichEmbed()
.setTitle(`${name} has been found!`)
.setColor(0x00AE86)
.setThumbnail(`attachment://./sprites/${randomNum}.png`)
.setTimestamp()
.addField("Quick! Capture it with `>capture`!")
msg.channel.send({embed});
}
The JSON file looks like this:
{
"311": "Blargon",
"310": "Xryzoz",
"303": "Noot",
"279": "",
"312": "Arragn",
"35": "Qeud",
...
}
I want it to pick a random one of those, such as 303, and post it in a rich embed. What do I do from here?
You can select a random name like this:
// Create array of object keys, ["311", "310", ...]
const keys = Object.keys(names)
// Generate random index based on number of keys
const randIndex = Math.floor(Math.random() * keys.length)
// Select a key from the array of keys using the random index
const randKey = keys[randIndex]
// Use the key to get the corresponding name from the "names" object
const name = names[randKey]
// ...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With