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?
This can be done in two steps
Loading Json file using Javascript and local server
1> Create a Json file, name it botNames.json, add your data.
Note: .json files can only contain Json Object, Array or Json literal
Use XMLHttpRequest() to load the data, you can use below function to load the .json file passing a callback function and the path as an argument.
To generate a random index you can use the below expression
Math.floor(lowerLimt + (upperLimit - lowerLimit+1)*Math.Random())
this will give you values in the range [lowerLimit,upperLimit)
Note: This is possible because Math.random() generates a fractional number in the range [0,1)
Your callback function will be
You can use above concepts in your code as
You can select a random name like this: